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/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/entity/descriptor/EntityDescriptorValidator.java | package ai.timefold.solver.core.impl.domain.entity.descriptor;
import static ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor.VARIABLE_ANNOTATION_CLASSES;
import java.lang.reflect.Member;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.entity.PlanningPin;
import ai.timefold.solver.core.api.domain.entity.PlanningPinToIndex;
import ai.timefold.solver.core.config.util.ConfigUtils;
public class EntityDescriptorValidator {
private static final Class[] ADDITIONAL_VARIABLE_ANNOTATION_CLASSES = {
PlanningPin.class,
PlanningPinToIndex.class
};
private EntityDescriptorValidator() {
}
/**
* Mixed inheritance is not permitted. Therefore, inheritance must consist only of classes or only of interfaces.
*/
public static void assertNotMixedInheritance(Class<?> entityClass, List<Class<?>> declaredInheritedEntityClassList) {
if (declaredInheritedEntityClassList.isEmpty()) {
return;
}
var hasClass = false;
var hasInterface = false;
for (var declaredEntityClass : declaredInheritedEntityClassList) {
if (!hasClass && !declaredEntityClass.isInterface()) {
hasClass = true;
}
if (!hasInterface && declaredEntityClass.isInterface()) {
hasInterface = true;
}
if (hasClass && hasInterface) {
break;
}
}
if (hasClass && hasInterface) {
var classes = declaredInheritedEntityClassList.stream()
.filter(clazz -> !clazz.isInterface())
.map(Class::getSimpleName)
.toList();
var interfaces = declaredInheritedEntityClassList.stream()
.filter(Class::isInterface)
.map(Class::getSimpleName)
.toList();
throw new IllegalStateException(
"""
The class %s extends another class marked as an entity (%s) and also implements an interface that is annotated as an entity (%s). Mixed inheritance is not permitted.
Maybe remove either the entity class or one of the entity interfaces from the inheritance chain."""
.formatted(classes, interfaces, entityClass));
}
}
public static void assertSingleInheritance(Class<?> entityClass, List<Class<?>> declaredInheritedEntityClassList) {
if (declaredInheritedEntityClassList.size() > 1) {
var classes = declaredInheritedEntityClassList.stream()
.filter(clazz -> !clazz.isInterface())
.map(Class::getSimpleName)
.toList();
var interfaces = declaredInheritedEntityClassList.stream()
.filter(Class::isInterface)
.map(Class::getSimpleName)
.toList();
throw new IllegalStateException(
"""
The class %s inherits its @%s annotation both from entities (%s) and interfaces (%s).
Remove either the entity classes or entity interfaces from the inheritance chain to create a single-level inheritance structure."""
.formatted(entityClass.getName(), PlanningEntity.class.getSimpleName(), classes, interfaces));
}
}
/**
* If a class declares any variable (genuine or shadow), it must be annotated as an entity,
* even if a supertype already has the annotation.
*/
public static void assertValidPlanningVariables(Class<?> clazz) {
// We first check the entity class
if (clazz.getAnnotation(PlanningEntity.class) == null && hasAnyGenuineOrShadowVariables(clazz)) {
var planningVariables = extractPlanningVariables(clazz).stream()
.map(Member::getName)
.toList();
throw new IllegalStateException(
"""
The class %s is not annotated with @PlanningEntity but defines genuine or shadow variables.
Maybe annotate %s with @PlanningEntity.
Maybe remove the planning variables (%s)."""
.formatted(clazz.getName(), clazz.getName(), planningVariables));
}
// We check the first level of the inheritance chain
var classList = new ArrayList<Class<?>>();
classList.add(clazz.getSuperclass());
classList.addAll(Arrays.asList(clazz.getInterfaces()));
for (var otherClazz : classList) {
if (otherClazz != null && otherClazz.getAnnotation(PlanningEntity.class) == null
&& hasAnyGenuineOrShadowVariables(otherClazz)) {
var planningVariables = extractPlanningVariables(otherClazz).stream()
.map(Member::getName)
.toList();
throw new IllegalStateException(
"""
The class %s is not annotated with @PlanningEntity but defines genuine or shadow variables.
Maybe annotate %s with @PlanningEntity.
Maybe remove the planning variables (%s)."""
.formatted(otherClazz.getName(), otherClazz.getName(), planningVariables));
}
}
}
private static List<Member> extractPlanningVariables(Class<?> entityClass) {
var membersList = ConfigUtils.getDeclaredMembers(entityClass);
return membersList.stream()
.filter(member -> ConfigUtils.extractAnnotationClass(member, VARIABLE_ANNOTATION_CLASSES) != null
|| ConfigUtils.extractAnnotationClass(member, ADDITIONAL_VARIABLE_ANNOTATION_CLASSES) != null)
.toList();
}
@SuppressWarnings("unchecked")
private static boolean hasAnyGenuineOrShadowVariables(Class<?> entityClass) {
return !extractPlanningVariables(entityClass).isEmpty();
}
public static boolean isEntityClass(Class<?> clazz) {
return clazz.getAnnotation(PlanningEntity.class) != null
|| clazz.getSuperclass() != null && clazz.getSuperclass().getAnnotation(PlanningEntity.class) != null
|| Arrays.stream(clazz.getInterfaces()).anyMatch(i -> i.getAnnotation(PlanningEntity.class) != null);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/entity/descriptor/EntityForEachFilter.java | package ai.timefold.solver.core.impl.domain.entity.descriptor;
import java.util.Collection;
import java.util.function.Predicate;
import ai.timefold.solver.core.impl.domain.variable.declarative.ConsistencyTracker;
import ai.timefold.solver.core.impl.domain.variable.declarative.DeclarativeShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
public class EntityForEachFilter<Solution_> {
private final EntityDescriptor<Solution_> entityDescriptor;
private final Predicate<Object> assignedPredicate;
private final boolean hasDeclarativeShadowVariables;
EntityForEachFilter(EntityDescriptor<Solution_> entityDescriptor) {
var solutionDescriptor = entityDescriptor.getSolutionDescriptor();
var listVariableDescriptor = solutionDescriptor.getListVariableDescriptor();
this.entityDescriptor = entityDescriptor;
this.assignedPredicate = getAssignedPredicate(entityDescriptor, listVariableDescriptor);
this.hasDeclarativeShadowVariables = !getDeclarativeShadowVariables(entityDescriptor).isEmpty();
}
public Predicate<Object> getAssignedAndConsistentPredicate(ConsistencyTracker<Solution_> consistencyTracker) {
if (!hasDeclarativeShadowVariables) {
return assignedPredicate;
}
var entityConsistencyState = consistencyTracker.getDeclarativeEntityConsistencyState(entityDescriptor);
return assignedPredicate.and(entityConsistencyState::isEntityConsistent);
}
@Nullable
public Predicate<Object> getConsistentPredicate(ConsistencyTracker<Solution_> consistencyTracker) {
if (!hasDeclarativeShadowVariables) {
return null;
}
var entityConsistencyState = consistencyTracker.getDeclarativeEntityConsistencyState(entityDescriptor);
return entityConsistencyState::isEntityConsistent;
}
private static Collection<? extends ShadowVariableDescriptor>
getDeclarativeShadowVariables(EntityDescriptor<?> entityDescriptor) {
return entityDescriptor.getShadowVariableDescriptors()
.stream()
.filter(shadowVariableDescriptor -> shadowVariableDescriptor instanceof DeclarativeShadowVariableDescriptor<?>)
.toList();
}
private static Predicate<Object> getAssignedPredicate(EntityDescriptor<?> entityDescriptor,
ListVariableDescriptor<?> listVariableDescriptor) {
var isListVariableValue =
listVariableDescriptor != null && listVariableDescriptor.acceptsValueType(entityDescriptor.getEntityClass());
if (isListVariableValue) {
var listInverseVariable = listVariableDescriptor.getInverseRelationShadowVariableDescriptor();
if (listInverseVariable != null) {
return entity -> entityDescriptor.hasNoNullVariables(entity) && listInverseVariable.getValue(entity) != null;
} else {
return ignored -> {
throw new IllegalStateException("""
Impossible state: assigned predicate for list variable value should not be used
when there is no inverse relation shadow variable descriptor.
""");
};
}
} else {
return entityDescriptor::hasNoNullVariables;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/entity/descriptor/MovableFilter.java | package ai.timefold.solver.core.impl.domain.entity.descriptor;
import java.util.function.BiPredicate;
@FunctionalInterface
interface MovableFilter<Solution_> extends BiPredicate<Solution_, Object> {
default MovableFilter<Solution_> and(MovableFilter<Solution_> other) {
return (solution, entity) -> test(solution, entity) && other.test(solution, entity);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/entity/descriptor/PinEntityFilter.java | package ai.timefold.solver.core.impl.domain.entity.descriptor;
import ai.timefold.solver.core.api.domain.entity.PlanningPin;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
/**
* Filters out entities that return true for the {@link PlanningPin} annotated boolean member.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
record PinEntityFilter<Solution_>(MemberAccessor memberAccessor) implements MovableFilter<Solution_> {
@Override
public boolean test(Solution_ solution, Object entity) {
var pinned = (Boolean) memberAccessor.executeGetter(entity);
if (pinned == null) {
throw new IllegalStateException("The entity (" + entity + ") has a @" + PlanningPin.class.getSimpleName()
+ " annotated property (" + memberAccessor.getName() + ") that returns null.");
}
return !pinned;
}
@Override
public String toString() {
return "Non-pinned entities only";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/entity | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/entity/descriptor/PlanningPinToIndexReader.java | package ai.timefold.solver.core.impl.domain.entity.descriptor;
import java.util.function.ToIntFunction;
@FunctionalInterface
public interface PlanningPinToIndexReader extends ToIntFunction<Object> {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/lookup/EqualsLookUpStrategy.java | package ai.timefold.solver.core.impl.domain.lookup;
import java.util.Map;
import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty;
public final class EqualsLookUpStrategy implements LookUpStrategy {
@Override
public void addWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject) {
Object oldAddedObject = idToWorkingObjectMap.put(workingObject, workingObject);
if (oldAddedObject != null) {
throw new IllegalStateException("The workingObjects (" + oldAddedObject + ", " + workingObject
+ ") are equal (as in Object.equals()). Working objects must be unique.");
}
}
@Override
public void removeWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject) {
Object removedObject = idToWorkingObjectMap.remove(workingObject);
if (workingObject != removedObject) {
throw new IllegalStateException("The workingObject (" + workingObject
+ ") differs from the removedObject (" + removedObject + ").");
}
}
@Override
public <E> E lookUpWorkingObject(Map<Object, Object> idToWorkingObjectMap, E externalObject) {
E workingObject = (E) idToWorkingObjectMap.get(externalObject);
if (workingObject == null) {
throw new IllegalStateException("The externalObject (" + externalObject
+ ") has no known workingObject (" + workingObject + ").\n"
+ "Maybe the workingObject was never added because the planning solution doesn't have a @"
+ ProblemFactCollectionProperty.class.getSimpleName()
+ " annotation on a member with instances of the externalObject's class ("
+ externalObject.getClass() + ").");
}
return workingObject;
}
@Override
public <E> E lookUpWorkingObjectIfExists(Map<Object, Object> idToWorkingObjectMap, E externalObject) {
return (E) idToWorkingObjectMap.get(externalObject);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/lookup/ImmutableLookUpStrategy.java | package ai.timefold.solver.core.impl.domain.lookup;
import java.util.Map;
public final class ImmutableLookUpStrategy implements LookUpStrategy {
@Override
public void addWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject) {
// Do nothing
}
@Override
public void removeWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject) {
// Do nothing
}
@Override
public <E> E lookUpWorkingObject(Map<Object, Object> idToWorkingObjectMap, E externalObject) {
// Because it is immutable, we can use the same one.
return externalObject;
}
@Override
public <E> E lookUpWorkingObjectIfExists(Map<Object, Object> idToWorkingObjectMap, E externalObject) {
// Because it is immutable, we can use the same one.
return externalObject;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/lookup/LookUpManager.java | package ai.timefold.solver.core.impl.domain.lookup;
import java.util.HashMap;
import java.util.Map;
import ai.timefold.solver.core.api.domain.lookup.PlanningId;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
/**
* @see PlanningId
* @see ScoreDirector#lookUpWorkingObject(Object)
*/
public class LookUpManager {
private final LookUpStrategyResolver lookUpStrategyResolver;
private Map<Object, Object> idToWorkingObjectMap;
public LookUpManager(LookUpStrategyResolver lookUpStrategyResolver) {
this.lookUpStrategyResolver = lookUpStrategyResolver;
reset();
}
public void reset() {
idToWorkingObjectMap = new HashMap<>();
}
public void addWorkingObject(Object workingObject) {
LookUpStrategy lookUpStrategy = lookUpStrategyResolver.determineLookUpStrategy(workingObject);
lookUpStrategy.addWorkingObject(idToWorkingObjectMap, workingObject);
}
public void removeWorkingObject(Object workingObject) {
LookUpStrategy lookUpStrategy = lookUpStrategyResolver.determineLookUpStrategy(workingObject);
lookUpStrategy.removeWorkingObject(idToWorkingObjectMap, workingObject);
}
/**
* As defined by {@link ScoreDirector#lookUpWorkingObject(Object)}.
*
* @param externalObject sometimes null
* @return null if externalObject is null
* @throws IllegalArgumentException if there is no workingObject for externalObject, if it cannot be looked up
* or if the externalObject's class is not supported
* @throws IllegalStateException if it cannot be looked up
* @param <E> the object type
*/
public <E> E lookUpWorkingObject(E externalObject) {
if (externalObject == null) {
return null;
}
LookUpStrategy lookUpStrategy = lookUpStrategyResolver.determineLookUpStrategy(externalObject);
return lookUpStrategy.lookUpWorkingObject(idToWorkingObjectMap, externalObject);
}
/**
* As defined by {@link ScoreDirector#lookUpWorkingObjectOrReturnNull(Object)}.
*
* @param externalObject sometimes null
* @return null if externalObject is null or if there is no workingObject for externalObject
* @throws IllegalArgumentException if it cannot be looked up or if the externalObject's class is not supported
* @throws IllegalStateException if it cannot be looked up
* @param <E> the object type
*/
public <E> E lookUpWorkingObjectOrReturnNull(E externalObject) {
if (externalObject == null) {
return null;
}
LookUpStrategy lookUpStrategy = lookUpStrategyResolver.determineLookUpStrategy(externalObject);
return lookUpStrategy.lookUpWorkingObjectIfExists(idToWorkingObjectMap, externalObject);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/lookup/LookUpStrategy.java | package ai.timefold.solver.core.impl.domain.lookup;
import java.util.Map;
public sealed interface LookUpStrategy
permits EqualsLookUpStrategy, ImmutableLookUpStrategy, NoneLookUpStrategy, PlanningIdLookUpStrategy {
void addWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject);
void removeWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject);
<E> E lookUpWorkingObject(Map<Object, Object> idToWorkingObjectMap, E externalObject);
<E> E lookUpWorkingObjectIfExists(Map<Object, Object> idToWorkingObjectMap, E externalObject);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/lookup/LookUpStrategyResolver.java | package ai.timefold.solver.core.impl.domain.lookup;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentMap;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.domain.lookup.LookUpStrategyType;
import ai.timefold.solver.core.api.domain.lookup.PlanningId;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory;
import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy;
import ai.timefold.solver.core.impl.domain.solution.cloner.DeepCloningUtils;
import ai.timefold.solver.core.impl.util.ConcurrentMemoization;
/**
* This class is thread-safe.
*/
public final class LookUpStrategyResolver {
private final LookUpStrategyType lookUpStrategyType;
private final DomainAccessType domainAccessType;
private final MemberAccessorFactory memberAccessorFactory;
private final ConcurrentMap<Class<?>, LookUpStrategy> decisionCache = new ConcurrentMemoization<>();
public LookUpStrategyResolver(DescriptorPolicy descriptorPolicy, LookUpStrategyType lookUpStrategyType) {
this.lookUpStrategyType = lookUpStrategyType;
this.domainAccessType = descriptorPolicy.getDomainAccessType();
this.memberAccessorFactory = descriptorPolicy.getMemberAccessorFactory();
}
/**
* This method is thread-safe.
*
* @param object never null
* @return never null
*/
public LookUpStrategy determineLookUpStrategy(Object object) {
return decisionCache.computeIfAbsent(object.getClass(), objectClass -> {
if (DeepCloningUtils.isImmutable(objectClass)) {
return new ImmutableLookUpStrategy();
}
return switch (lookUpStrategyType) {
case PLANNING_ID_OR_NONE -> {
var memberAccessor =
ConfigUtils.findPlanningIdMemberAccessor(objectClass, memberAccessorFactory, domainAccessType);
if (memberAccessor == null) {
yield new NoneLookUpStrategy();
}
yield new PlanningIdLookUpStrategy(memberAccessor);
}
case PLANNING_ID_OR_FAIL_FAST -> {
var memberAccessor =
ConfigUtils.findPlanningIdMemberAccessor(objectClass, memberAccessorFactory, domainAccessType);
if (memberAccessor == null) {
throw new IllegalArgumentException("The class (" + objectClass
+ ") does not have a @" + PlanningId.class.getSimpleName() + " annotation,"
+ " but the lookUpStrategyType (" + lookUpStrategyType + ") requires it.\n"
+ "Maybe add the @" + PlanningId.class.getSimpleName() + " annotation"
+ " or change the @" + PlanningSolution.class.getSimpleName() + " annotation's "
+ LookUpStrategyType.class.getSimpleName() + ".");
}
yield new PlanningIdLookUpStrategy(memberAccessor);
}
case EQUALITY -> {
Method equalsMethod;
Method hashCodeMethod;
try {
equalsMethod = objectClass.getMethod("equals", Object.class);
hashCodeMethod = objectClass.getMethod("hashCode");
} catch (NoSuchMethodException e) {
throw new IllegalStateException(
"Impossible state because equals() and hashCode() always exist.", e);
}
if (equalsMethod.getDeclaringClass().equals(Object.class)) {
throw new IllegalArgumentException("The class (" + objectClass.getSimpleName()
+ ") doesn't override the equals() method, neither does any superclass.");
}
if (hashCodeMethod.getDeclaringClass().equals(Object.class)) {
throw new IllegalArgumentException("The class (" + objectClass.getSimpleName()
+ ") overrides equals() but neither it nor any superclass"
+ " overrides the hashCode() method.");
}
yield new EqualsLookUpStrategy();
}
case NONE -> new NoneLookUpStrategy();
};
});
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/lookup/NoneLookUpStrategy.java | package ai.timefold.solver.core.impl.domain.lookup;
import java.util.Map;
import ai.timefold.solver.core.api.domain.lookup.LookUpStrategyType;
import ai.timefold.solver.core.api.domain.lookup.PlanningId;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
public final class NoneLookUpStrategy implements LookUpStrategy {
@Override
public void addWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject) {
// Do nothing
}
@Override
public void removeWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject) {
// Do nothing
}
@Override
public <E> E lookUpWorkingObject(Map<Object, Object> idToWorkingObjectMap, E externalObject) {
throw new IllegalArgumentException("The externalObject (" + externalObject
+ ") cannot be looked up. Some functionality, such as multithreaded solving, requires this ability.\n"
+ "Maybe add a @" + PlanningId.class.getSimpleName()
+ " annotation on an identifier property of the class (" + externalObject.getClass() + ").\n"
+ "Or otherwise, maybe change the @" + PlanningSolution.class.getSimpleName() + " annotation's "
+ LookUpStrategyType.class.getSimpleName() + " (not recommended).");
}
@Override
public <E> E lookUpWorkingObjectIfExists(Map<Object, Object> idToWorkingObjectMap, E externalObject) {
throw new IllegalArgumentException("The externalObject (" + externalObject
+ ") cannot be looked up. Some functionality, such as multithreaded solving, requires this ability.\n"
+ "Maybe add a @" + PlanningId.class.getSimpleName()
+ " annotation on an identifier property of the class (" + externalObject.getClass() + ").\n"
+ "Or otherwise, maybe change the @" + PlanningSolution.class.getSimpleName() + " annotation's "
+ LookUpStrategyType.class.getSimpleName() + " (not recommended).");
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/lookup/PlanningIdLookUpStrategy.java | package ai.timefold.solver.core.impl.domain.lookup;
import java.util.Map;
import ai.timefold.solver.core.api.domain.lookup.LookUpStrategyType;
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.ProblemFactCollectionProperty;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.util.Pair;
public final class PlanningIdLookUpStrategy implements LookUpStrategy {
private final MemberAccessor planningIdMemberAccessor;
public PlanningIdLookUpStrategy(MemberAccessor planningIdMemberAccessor) {
this.planningIdMemberAccessor = planningIdMemberAccessor;
}
@Override
public void addWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject) {
var planningId = extractPlanningId(workingObject);
var oldAddedObject = idToWorkingObjectMap.put(planningId, workingObject);
if (oldAddedObject != null) {
throw new IllegalStateException("The workingObjects (" + oldAddedObject + ", " + workingObject
+ ") have the same planningId (" + planningId + "). Working objects must be unique.");
}
}
@Override
public void removeWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject) {
var planningId = extractPlanningId(workingObject);
var removedObject = idToWorkingObjectMap.remove(planningId);
if (workingObject != removedObject) {
throw new IllegalStateException("The workingObject (" + workingObject
+ ") differs from the removedObject (" + removedObject + ") for planningId (" + planningId + ").");
}
}
@Override
public <E> E lookUpWorkingObject(Map<Object, Object> idToWorkingObjectMap, E externalObject) {
var planningId = extractPlanningId(externalObject);
var workingObject = (E) idToWorkingObjectMap.get(planningId);
if (workingObject == null) {
throw new IllegalStateException("The externalObject (" + externalObject + ") with planningId (" + planningId
+ ") has no known workingObject (" + workingObject + ").\n"
+ "Maybe the workingObject was never added because the planning solution doesn't have a @"
+ ProblemFactCollectionProperty.class.getSimpleName()
+ " annotation on a member with instances of the externalObject's class ("
+ externalObject.getClass() + ").");
}
return workingObject;
}
@Override
public <E> E lookUpWorkingObjectIfExists(Map<Object, Object> idToWorkingObjectMap, E externalObject) {
var planningId = extractPlanningId(externalObject);
return (E) idToWorkingObjectMap.get(planningId);
}
private Pair<Class<?>, Object> extractPlanningId(Object externalObject) {
var planningId = planningIdMemberAccessor.executeGetter(externalObject);
if (planningId == null) {
throw new IllegalArgumentException("The planningId (" + planningId
+ ") of the member (" + planningIdMemberAccessor + ") of the class (" + externalObject.getClass()
+ ") on externalObject (" + externalObject
+ ") must not be null.\n"
+ "Maybe initialize the planningId of the class (" + externalObject.getClass().getSimpleName()
+ ") instance (" + externalObject + ") before solving.\n" +
"Maybe remove the @" + PlanningId.class.getSimpleName() + " annotation"
+ " or change the @" + PlanningSolution.class.getSimpleName() + " annotation's "
+ LookUpStrategyType.class.getSimpleName() + ".");
}
return new Pair<>(externalObject.getClass(), planningId);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/lookup/package-info.java | /**
* @deprecated When multi-threaded solving,
* ensure your domain classes use @{@link ai.timefold.solver.core.api.domain.lookup.PlanningId} instead.
*/
@Deprecated(forRemoval = true, since = "1.10.0")
package ai.timefold.solver.core.impl.domain.lookup; |
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/policy/DescriptorPolicy.java | package ai.timefold.solver.core.impl.domain.policy;
import static ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory.MemberAccessorType.FIELD_OR_GETTER_METHOD_WITH_SETTER;
import java.lang.reflect.Member;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.domain.solution.PlanningScore;
import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.api.score.IBendableScore;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.buildin.bendable.BendableScore;
import ai.timefold.solver.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore;
import ai.timefold.solver.core.api.score.buildin.bendablelong.BendableLongScore;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoftbigdecimal.HardMediumSoftBigDecimalScore;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoftlong.HardMediumSoftLongScore;
import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
import ai.timefold.solver.core.api.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScore;
import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore;
import ai.timefold.solver.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore;
import ai.timefold.solver.core.api.score.buildin.simplelong.SimpleLongScore;
import ai.timefold.solver.core.config.solver.PreviewFeature;
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.common.accessor.MemberAccessorFactory;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.score.descriptor.ScoreDescriptor;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.domain.valuerange.descriptor.CompositeValueRangeDescriptor;
import ai.timefold.solver.core.impl.domain.valuerange.descriptor.FromEntityPropertyValueRangeDescriptor;
import ai.timefold.solver.core.impl.domain.valuerange.descriptor.FromSolutionPropertyValueRangeDescriptor;
import ai.timefold.solver.core.impl.domain.valuerange.descriptor.ValueRangeDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.score.buildin.BendableBigDecimalScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.BendableLongScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.BendableScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.HardMediumSoftBigDecimalScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.HardMediumSoftLongScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.HardMediumSoftScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.HardSoftBigDecimalScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.HardSoftLongScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.HardSoftScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.SimpleBigDecimalScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.SimpleLongScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.SimpleScoreDefinition;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
public class DescriptorPolicy {
private Map<String, SolutionCloner> generatedSolutionClonerMap = new LinkedHashMap<>();
private final Map<String, MemberAccessor> fromSolutionValueRangeProviderMap = new LinkedHashMap<>();
private final Set<MemberAccessor> anonymousFromSolutionValueRangeProviderSet = new LinkedHashSet<>();
private final Map<String, MemberAccessor> fromEntityValueRangeProviderMap = new LinkedHashMap<>();
private final Set<MemberAccessor> anonymousFromEntityValueRangeProviderSet = new LinkedHashSet<>();
private DomainAccessType domainAccessType = DomainAccessType.REFLECTION;
private Set<PreviewFeature> enabledPreviewFeatureSet = EnumSet.noneOf(PreviewFeature.class);
@Nullable
private MemberAccessorFactory memberAccessorFactory;
private int entityDescriptorCount = 0;
private int valueRangeDescriptorCount = 0;
public <Solution_> EntityDescriptor<Solution_> buildEntityDescriptor(SolutionDescriptor<Solution_> solutionDescriptor,
Class<?> entityClass) {
var entityDescriptor = new EntityDescriptor<>(entityDescriptorCount++, solutionDescriptor, entityClass);
solutionDescriptor.addEntityDescriptor(entityDescriptor);
return entityDescriptor;
}
public <Score_ extends Score<Score_>> ScoreDescriptor<Score_> buildScoreDescriptor(Member member, Class<?> solutionClass) {
MemberAccessor scoreMemberAccessor = buildScoreMemberAccessor(member);
Class<Score_> scoreType = extractScoreType(scoreMemberAccessor, solutionClass);
PlanningScore annotation = extractPlanningScoreAnnotation(scoreMemberAccessor);
ScoreDefinition<Score_> scoreDefinition =
buildScoreDefinition(solutionClass, scoreMemberAccessor, scoreType, annotation);
return new ScoreDescriptor<>(scoreMemberAccessor, scoreDefinition);
}
public <Solution_> CompositeValueRangeDescriptor<Solution_> buildCompositeValueRangeDescriptor(
GenuineVariableDescriptor<Solution_> variableDescriptor,
List<ValueRangeDescriptor<Solution_>> childValueRangeDescriptorList) {
return new CompositeValueRangeDescriptor<>(valueRangeDescriptorCount++, variableDescriptor,
childValueRangeDescriptorList);
}
public <Solution_> FromSolutionPropertyValueRangeDescriptor<Solution_> buildFromSolutionPropertyValueRangeDescriptor(
GenuineVariableDescriptor<Solution_> variableDescriptor, MemberAccessor valueRangeProviderMemberAccessor) {
return new FromSolutionPropertyValueRangeDescriptor<>(valueRangeDescriptorCount++, variableDescriptor,
valueRangeProviderMemberAccessor);
}
public <Solution_> FromEntityPropertyValueRangeDescriptor<Solution_> buildFromEntityPropertyValueRangeDescriptor(
GenuineVariableDescriptor<Solution_> variableDescriptor, MemberAccessor valueRangeProviderMemberAccessor) {
return new FromEntityPropertyValueRangeDescriptor<>(valueRangeDescriptorCount++, variableDescriptor,
valueRangeProviderMemberAccessor);
}
@SuppressWarnings("unchecked")
private static <Score_ extends Score<Score_>> Class<Score_> extractScoreType(MemberAccessor scoreMemberAccessor,
Class<?> solutionClass) {
Class<?> memberType = scoreMemberAccessor.getType();
if (!Score.class.isAssignableFrom(memberType)) {
throw new IllegalStateException(
"The solutionClass (%s) has a @%s annotated member (%s) that does not return a subtype of Score."
.formatted(solutionClass, PlanningScore.class.getSimpleName(), scoreMemberAccessor));
}
if (memberType == Score.class) {
throw new IllegalStateException(
"""
The solutionClass (%s) has a @%s annotated member (%s) that doesn't return a non-abstract %s class.
Maybe make it return %s or another specific %s implementation."""
.formatted(solutionClass, PlanningScore.class.getSimpleName(), scoreMemberAccessor,
Score.class.getSimpleName(), HardSoftScore.class.getSimpleName(),
Score.class.getSimpleName()));
}
return (Class<Score_>) memberType;
}
private static PlanningScore extractPlanningScoreAnnotation(MemberAccessor scoreMemberAccessor) {
PlanningScore annotation = scoreMemberAccessor.getAnnotation(PlanningScore.class);
if (annotation != null) {
return annotation;
}
// The member was auto-discovered.
try {
return ScoreDescriptor.class.getDeclaredField("PLANNING_SCORE").getAnnotation(PlanningScore.class);
} catch (NoSuchFieldException e) {
throw new IllegalStateException("Impossible situation: the field (PLANNING_SCORE) must exist.", e);
}
}
@SuppressWarnings("unchecked")
private static <Score_ extends Score<Score_>, ScoreDefinition_ extends ScoreDefinition<Score_>> ScoreDefinition_
buildScoreDefinition(Class<?> solutionClass,
MemberAccessor scoreMemberAccessor, Class<Score_> scoreType, PlanningScore annotation) {
Class<ScoreDefinition_> scoreDefinitionClass = (Class<ScoreDefinition_>) annotation.scoreDefinitionClass();
int bendableHardLevelsSize = annotation.bendableHardLevelsSize();
int bendableSoftLevelsSize = annotation.bendableSoftLevelsSize();
if (!Objects.equals(scoreDefinitionClass, PlanningScore.NullScoreDefinition.class)) {
if (bendableHardLevelsSize != PlanningScore.NO_LEVEL_SIZE
|| bendableSoftLevelsSize != PlanningScore.NO_LEVEL_SIZE) {
throw new IllegalArgumentException(
"The solutionClass (%s) has a @%s annotated member (%s) that has a scoreDefinition (%s) that must not have a bendableHardLevelsSize (%d) or a bendableSoftLevelsSize (%d)."
.formatted(solutionClass, PlanningScore.class.getSimpleName(), scoreMemberAccessor,
scoreDefinitionClass, bendableHardLevelsSize, bendableSoftLevelsSize));
}
return ConfigUtils.newInstance(() -> scoreMemberAccessor + " with @" + PlanningScore.class.getSimpleName(),
"scoreDefinitionClass", scoreDefinitionClass);
}
if (!IBendableScore.class.isAssignableFrom(scoreType)) {
if (bendableHardLevelsSize != PlanningScore.NO_LEVEL_SIZE
|| bendableSoftLevelsSize != PlanningScore.NO_LEVEL_SIZE) {
throw new IllegalArgumentException(
"The solutionClass (%s) has a @%s annotated member (%s) that returns a scoreType (%s) that must not have a bendableHardLevelsSize (%d) or a bendableSoftLevelsSize (%d)."
.formatted(solutionClass, PlanningScore.class.getSimpleName(), scoreMemberAccessor, scoreType,
bendableHardLevelsSize, bendableSoftLevelsSize));
}
if (scoreType.equals(SimpleScore.class)) {
return (ScoreDefinition_) new SimpleScoreDefinition();
} else if (scoreType.equals(SimpleLongScore.class)) {
return (ScoreDefinition_) new SimpleLongScoreDefinition();
} else if (scoreType.equals(SimpleBigDecimalScore.class)) {
return (ScoreDefinition_) new SimpleBigDecimalScoreDefinition();
} else if (scoreType.equals(HardSoftScore.class)) {
return (ScoreDefinition_) new HardSoftScoreDefinition();
} else if (scoreType.equals(HardSoftLongScore.class)) {
return (ScoreDefinition_) new HardSoftLongScoreDefinition();
} else if (scoreType.equals(HardSoftBigDecimalScore.class)) {
return (ScoreDefinition_) new HardSoftBigDecimalScoreDefinition();
} else if (scoreType.equals(HardMediumSoftScore.class)) {
return (ScoreDefinition_) new HardMediumSoftScoreDefinition();
} else if (scoreType.equals(HardMediumSoftLongScore.class)) {
return (ScoreDefinition_) new HardMediumSoftLongScoreDefinition();
} else if (scoreType.equals(HardMediumSoftBigDecimalScore.class)) {
return (ScoreDefinition_) new HardMediumSoftBigDecimalScoreDefinition();
} else {
throw new IllegalArgumentException(
"""
The solutionClass (%s) has a @%s annotated member (%s) that returns a scoreType (%s) that is not recognized as a default %s implementation.
If you intend to use a custom implementation, maybe set a scoreDefinition in the @%s annotation."""
.formatted(solutionClass, PlanningScore.class.getSimpleName(), scoreMemberAccessor, scoreType,
Score.class.getSimpleName(), PlanningScore.class.getSimpleName()));
}
} else {
if (bendableHardLevelsSize == PlanningScore.NO_LEVEL_SIZE
|| bendableSoftLevelsSize == PlanningScore.NO_LEVEL_SIZE) {
throw new IllegalArgumentException(
"The solutionClass (%s) has a @%s annotated member (%s) that returns a scoreType (%s) that must have a bendableHardLevelsSize (%d) and a bendableSoftLevelsSize (%d)."
.formatted(solutionClass, PlanningScore.class.getSimpleName(), scoreMemberAccessor, scoreType,
bendableHardLevelsSize, bendableSoftLevelsSize));
}
if (scoreType.equals(BendableScore.class)) {
return (ScoreDefinition_) new BendableScoreDefinition(bendableHardLevelsSize, bendableSoftLevelsSize);
} else if (scoreType.equals(BendableLongScore.class)) {
return (ScoreDefinition_) new BendableLongScoreDefinition(bendableHardLevelsSize,
bendableSoftLevelsSize);
} else if (scoreType.equals(BendableBigDecimalScore.class)) {
return (ScoreDefinition_) new BendableBigDecimalScoreDefinition(bendableHardLevelsSize,
bendableSoftLevelsSize);
} else {
throw new IllegalArgumentException(
"""
The solutionClass (%s) has a @%s annotated member (%s) that returns a bendable scoreType (%s) that is not recognized as a default %s implementation.
If you intend to use a custom implementation, maybe set a scoreDefinition in the annotation."""
.formatted(solutionClass, PlanningScore.class.getSimpleName(), scoreMemberAccessor, scoreType,
Score.class.getSimpleName()));
}
}
}
public MemberAccessor buildScoreMemberAccessor(Member member) {
return getMemberAccessorFactory().buildAndCacheMemberAccessor(
member,
FIELD_OR_GETTER_METHOD_WITH_SETTER,
PlanningScore.class,
getDomainAccessType());
}
public void addFromSolutionValueRangeProvider(MemberAccessor memberAccessor) {
String id = extractValueRangeProviderId(memberAccessor);
if (id == null) {
anonymousFromSolutionValueRangeProviderSet.add(memberAccessor);
} else {
fromSolutionValueRangeProviderMap.put(id, memberAccessor);
}
}
public boolean isFromSolutionValueRangeProvider(MemberAccessor memberAccessor) {
return fromSolutionValueRangeProviderMap.containsValue(memberAccessor)
|| anonymousFromSolutionValueRangeProviderSet.contains(memberAccessor);
}
public boolean hasFromSolutionValueRangeProvider(String id) {
return fromSolutionValueRangeProviderMap.containsKey(id);
}
public MemberAccessor getFromSolutionValueRangeProvider(String id) {
return fromSolutionValueRangeProviderMap.get(id);
}
public Set<MemberAccessor> getAnonymousFromSolutionValueRangeProviderSet() {
return anonymousFromSolutionValueRangeProviderSet;
}
public void addFromEntityValueRangeProvider(MemberAccessor memberAccessor) {
String id = extractValueRangeProviderId(memberAccessor);
if (id == null) {
anonymousFromEntityValueRangeProviderSet.add(memberAccessor);
} else {
fromEntityValueRangeProviderMap.put(id, memberAccessor);
}
}
public boolean isFromEntityValueRangeProvider(MemberAccessor memberAccessor) {
return fromEntityValueRangeProviderMap.containsValue(memberAccessor)
|| anonymousFromEntityValueRangeProviderSet.contains(memberAccessor);
}
public boolean hasFromEntityValueRangeProvider(String id) {
return fromEntityValueRangeProviderMap.containsKey(id);
}
public Set<MemberAccessor> getAnonymousFromEntityValueRangeProviderSet() {
return anonymousFromEntityValueRangeProviderSet;
}
public DomainAccessType getDomainAccessType() {
return domainAccessType;
}
public void setDomainAccessType(DomainAccessType domainAccessType) {
this.domainAccessType = domainAccessType;
}
public Set<PreviewFeature> getEnabledPreviewFeatureSet() {
return enabledPreviewFeatureSet;
}
public void setEnabledPreviewFeatureSet(Set<PreviewFeature> enabledPreviewFeatureSet) {
this.enabledPreviewFeatureSet = enabledPreviewFeatureSet;
}
/**
* @return never null
*/
public Map<String, SolutionCloner> getGeneratedSolutionClonerMap() {
return generatedSolutionClonerMap;
}
public void setGeneratedSolutionClonerMap(Map<String, SolutionCloner> generatedSolutionClonerMap) {
this.generatedSolutionClonerMap = generatedSolutionClonerMap;
}
public MemberAccessorFactory getMemberAccessorFactory() {
return memberAccessorFactory;
}
public void setMemberAccessorFactory(MemberAccessorFactory memberAccessorFactory) {
this.memberAccessorFactory = memberAccessorFactory;
}
public MemberAccessor getFromEntityValueRangeProvider(String id) {
return fromEntityValueRangeProviderMap.get(id);
}
public boolean isPreviewFeatureEnabled(PreviewFeature previewFeature) {
return enabledPreviewFeatureSet.contains(previewFeature);
}
private @Nullable String extractValueRangeProviderId(MemberAccessor memberAccessor) {
ValueRangeProvider annotation = memberAccessor.getAnnotation(ValueRangeProvider.class);
String id = annotation.id();
if (id == null || id.isEmpty()) {
return null;
}
validateUniqueValueRangeProviderId(id, memberAccessor);
return id;
}
private void validateUniqueValueRangeProviderId(String id, MemberAccessor memberAccessor) {
MemberAccessor duplicate = fromSolutionValueRangeProviderMap.get(id);
if (duplicate != null) {
throw new IllegalStateException("2 members (%s, %s) with a @%s annotation must not have the same id (%s)."
.formatted(duplicate, memberAccessor, ValueRangeProvider.class.getSimpleName(), id));
}
duplicate = fromEntityValueRangeProviderMap.get(id);
if (duplicate != null) {
throw new IllegalStateException("2 members (%s, %s) with a @%s annotation must not have the same id (%s)."
.formatted(duplicate, memberAccessor, ValueRangeProvider.class.getSimpleName(), id));
}
}
public Collection<String> getValueRangeProviderIds() {
List<String> valueRangeProviderIds = new ArrayList<>(
fromSolutionValueRangeProviderMap.size() + fromEntityValueRangeProviderMap.size());
valueRangeProviderIds.addAll(fromSolutionValueRangeProviderMap.keySet());
valueRangeProviderIds.addAll(fromEntityValueRangeProviderMap.keySet());
return valueRangeProviderIds;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/score/descriptor/ScoreDescriptor.java | package ai.timefold.solver.core.impl.domain.score.descriptor;
import java.lang.reflect.Member;
import ai.timefold.solver.core.api.domain.solution.PlanningScore;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
public final class ScoreDescriptor<Score_ extends Score<Score_>> {
// Used to obtain default @PlanningScore attribute values from a score member that was auto-discovered,
// as if it had an empty @PlanningScore annotation on it.
@PlanningScore
private static final Object PLANNING_SCORE = new Object();
private final MemberAccessor scoreMemberAccessor;
private final ScoreDefinition<Score_> scoreDefinition;
public ScoreDescriptor(MemberAccessor scoreMemberAccessor, ScoreDefinition<Score_> scoreDefinition) {
this.scoreMemberAccessor = scoreMemberAccessor;
this.scoreDefinition = scoreDefinition;
}
public ScoreDefinition<Score_> getScoreDefinition() {
return scoreDefinition;
}
public Class<Score_> getScoreClass() {
return scoreDefinition.getScoreClass();
}
@SuppressWarnings("unchecked")
public Score_ getScore(Object solution) {
return (Score_) scoreMemberAccessor.executeGetter(solution);
}
public void setScore(Object solution, Score_ score) {
scoreMemberAccessor.executeSetter(solution, score);
}
public void failFastOnDuplicateMember(DescriptorPolicy descriptorPolicy, Member member, Class<?> solutionClass) {
MemberAccessor memberAccessor = descriptorPolicy.buildScoreMemberAccessor(member);
// A solution class cannot have more than one score field or bean property (name check), and the @PlanningScore
// annotation cannot appear on both the score field and its getter (member accessor class check).
if (!scoreMemberAccessor.getName().equals(memberAccessor.getName())
|| !scoreMemberAccessor.getClass().equals(memberAccessor.getClass())) {
throw new IllegalStateException("The solutionClass (" + solutionClass
+ ") has a @" + PlanningScore.class.getSimpleName()
+ " annotated member (" + memberAccessor
+ ") that is duplicated by another member (" + scoreMemberAccessor + ").\n"
+ "Maybe the annotation is defined on both the field and its getter.");
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/ConstraintConfigurationBasedConstraintWeightSupplier.java | package ai.timefold.solver.core.impl.domain.solution;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.domain.solution.ConstraintWeightOverrides;
import ai.timefold.solver.core.api.score.IBendableScore;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintRef;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.score.definition.AbstractBendableScoreDefinition;
/**
* @deprecated Use {@link ConstraintWeightOverrides} instead.
*/
@Deprecated(forRemoval = true, since = "1.13.0")
public final class ConstraintConfigurationBasedConstraintWeightSupplier<Score_ extends Score<Score_>, Solution_>
implements ConstraintWeightSupplier<Solution_, Score_> {
public static <Solution_, Score_ extends Score<Score_>> ConstraintWeightSupplier<Solution_, Score_> create(
SolutionDescriptor<Solution_> solutionDescriptor, Class<?> constraintConfigurationClass) {
var configDescriptor = new ConstraintConfigurationDescriptor<>(Objects.requireNonNull(solutionDescriptor),
Objects.requireNonNull(constraintConfigurationClass));
return new ConstraintConfigurationBasedConstraintWeightSupplier<>(configDescriptor);
}
private final ConstraintConfigurationDescriptor<Solution_> constraintConfigurationDescriptor;
private final Map<ConstraintRef, Function<Solution_, Score_>> constraintWeightExtractorMap = new LinkedHashMap<>();
private ConstraintConfigurationBasedConstraintWeightSupplier(
ConstraintConfigurationDescriptor<Solution_> constraintConfigurationDescriptor) {
this.constraintConfigurationDescriptor = Objects.requireNonNull(constraintConfigurationDescriptor);
}
@SuppressWarnings("unchecked")
@Override
public void initialize(SolutionDescriptor<Solution_> solutionDescriptor, MemberAccessorFactory memberAccessorFactory,
DomainAccessType domainAccessType) {
var scoreDescriptor = solutionDescriptor.<Score_> getScoreDescriptor();
constraintConfigurationDescriptor.processAnnotations(memberAccessorFactory, domainAccessType,
scoreDescriptor.getScoreDefinition());
constraintConfigurationDescriptor.getSupportedConstraints().forEach(constraintRef -> {
var descriptor = constraintConfigurationDescriptor.findConstraintWeightDescriptor(constraintRef);
var weightExtractor = (Function<Solution_, Score_>) descriptor
.createExtractor(solutionDescriptor.getConstraintConfigurationMemberAccessor());
constraintWeightExtractorMap.put(constraintRef, weightExtractor);
});
}
@Override
public void validate(Solution_ workingSolution, Set<ConstraintRef> userDefinedConstraints) {
var missingConstraints = userDefinedConstraints.stream()
.filter(constraintRef -> !constraintWeightExtractorMap.containsKey(constraintRef))
.collect(Collectors.toSet());
if (!missingConstraints.isEmpty()) {
throw new IllegalStateException("""
The constraintConfigurationClass (%s) does not support the following constraints (%s).
Maybe ensure your constraint configuration contains all constraints defined in your %s."""
.formatted(constraintConfigurationDescriptor.getConstraintConfigurationClass(), missingConstraints,
ConstraintProvider.class.getSimpleName()));
}
// For backward compatibility reasons, we do not check for excess constraints.
}
@Override
public Class<?> getProblemFactClass() {
return constraintConfigurationDescriptor.getConstraintConfigurationClass();
}
@Override
public String getDefaultConstraintPackage() {
return constraintConfigurationDescriptor.getConstraintPackage();
}
@Override
public Score_ getConstraintWeight(ConstraintRef constraintRef, Solution_ workingSolution) {
var weightExtractor = constraintWeightExtractorMap.get(constraintRef);
if (weightExtractor == null) { // Should have been caught by validate(...).
throw new IllegalStateException(
"Impossible state: Constraint (%s) not supported by constraint configuration class (%s)."
.formatted(constraintRef, constraintConfigurationDescriptor.getConstraintConfigurationClass()));
}
var weight = weightExtractor.apply(workingSolution);
validateConstraintWeight(constraintRef, weight);
return weight;
}
private void validateConstraintWeight(ConstraintRef constraintRef, Score_ constraintWeight) {
if (constraintWeight == null) {
throw new IllegalArgumentException("""
The constraintWeight for constraint (%s) must not be null.
Maybe validate the data input of your constraintConfigurationClass (%s) for that constraint."""
.formatted(constraintRef, constraintConfigurationDescriptor.getConstraintConfigurationClass()));
}
var scoreDescriptor = constraintConfigurationDescriptor.getSolutionDescriptor().<Score_> getScoreDescriptor();
if (!scoreDescriptor.getScoreClass().isAssignableFrom(constraintWeight.getClass())) {
throw new IllegalArgumentException("""
The constraintWeight (%s) of class (%s) for constraint (%s) must be of the scoreClass (%s).
Maybe validate the data input of your constraintConfigurationClass (%s) for that constraint."""
.formatted(constraintWeight, constraintWeight.getClass(), constraintRef, scoreDescriptor.getScoreClass(),
constraintConfigurationDescriptor.getConstraintConfigurationClass()));
}
if (!scoreDescriptor.getScoreDefinition().isPositiveOrZero(constraintWeight)) {
throw new IllegalArgumentException("""
The constraintWeight (%s) for constraint (%s) must be positive or zero.
Maybe validate the data input of your constraintConfigurationClass (%s)."""
.formatted(constraintWeight, constraintRef,
constraintConfigurationDescriptor.getConstraintConfigurationClass()));
}
if (constraintWeight instanceof IBendableScore<?> bendableConstraintWeight) {
var bendableScoreDefinition = (AbstractBendableScoreDefinition<?>) scoreDescriptor.getScoreDefinition();
if (bendableConstraintWeight.hardLevelsSize() != bendableScoreDefinition.getHardLevelsSize()
|| bendableConstraintWeight.softLevelsSize() != bendableScoreDefinition.getSoftLevelsSize()) {
throw new IllegalArgumentException(
"""
The bendable constraintWeight (%s) for constraint (%s) has a hardLevelsSize (%d) or a softLevelsSize (%d) \
that doesn't match the score definition's hardLevelsSize (%d) or softLevelsSize (%d).
Maybe validate the data input of your constraintConfigurationClass (%s)."""
.formatted(bendableConstraintWeight, constraintRef, bendableConstraintWeight.hardLevelsSize(),
bendableConstraintWeight.softLevelsSize(), bendableScoreDefinition.getHardLevelsSize(),
bendableScoreDefinition.getSoftLevelsSize(),
constraintConfigurationDescriptor.getConstraintConfigurationClass()));
}
}
}
ConstraintConfigurationDescriptor<Solution_> getConstraintConfigurationDescriptor() {
return constraintConfigurationDescriptor;
}
@Override
public String toString() {
return "Constraint weights based on " + constraintConfigurationDescriptor.getConstraintConfigurationClass() + ".";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/ConstraintConfigurationDescriptor.java | package ai.timefold.solver.core.impl.domain.solution;
import static ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory.MemberAccessorType.FIELD_OR_READ_METHOD;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.domain.constraintweight.ConstraintConfiguration;
import ai.timefold.solver.core.api.domain.constraintweight.ConstraintConfigurationProvider;
import ai.timefold.solver.core.api.domain.constraintweight.ConstraintWeight;
import ai.timefold.solver.core.api.domain.solution.ConstraintWeightOverrides;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.constraint.ConstraintRef;
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.MemberAccessorFactory;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @deprecated Use {@link ConstraintWeightOverrides} instead.
*/
@Deprecated(forRemoval = true, since = "1.13.0")
final class ConstraintConfigurationDescriptor<Solution_> {
private final SolutionDescriptor<Solution_> solutionDescriptor;
private final Class<?> constraintConfigurationClass;
private String constraintPackage;
private final Map<String, ConstraintWeightDescriptor<Solution_>> constraintWeightDescriptorMap;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public ConstraintConfigurationDescriptor(SolutionDescriptor<Solution_> solutionDescriptor,
Class<?> constraintConfigurationClass) {
this.solutionDescriptor = solutionDescriptor;
this.constraintConfigurationClass = constraintConfigurationClass;
constraintWeightDescriptorMap = new LinkedHashMap<>();
}
public String getConstraintPackage() {
return constraintPackage;
}
public ConstraintWeightDescriptor<Solution_> getConstraintWeightDescriptor(String propertyName) {
return constraintWeightDescriptorMap.get(propertyName);
}
// ************************************************************************
// Lifecycle methods
// ************************************************************************
public void processAnnotations(MemberAccessorFactory memberAccessorFactory, DomainAccessType domainAccessType,
ScoreDefinition<?> scoreDefinition) {
processPackAnnotation();
var potentiallyOverwritingMethodList = new ArrayList<Method>();
// Iterate inherited members too (unlike for EntityDescriptor where each one is declared)
// to make sure each one is registered
for (var lineageClass : ConfigUtils.getAllAnnotatedLineageClasses(constraintConfigurationClass,
ConstraintConfiguration.class)) {
var memberList = ConfigUtils.getDeclaredMembers(lineageClass);
for (var member : memberList) {
if (member instanceof Method method && potentiallyOverwritingMethodList.stream().anyMatch(
m -> member.getName().equals(m.getName()) // Shortcut to discard negatives faster
&& ReflectionHelper.isMethodOverwritten(method, m.getDeclaringClass()))) {
// Ignore member because it is an overwritten method
continue;
}
processParameterAnnotation(memberAccessorFactory, domainAccessType, member, scoreDefinition);
}
potentiallyOverwritingMethodList.ensureCapacity(potentiallyOverwritingMethodList.size() + memberList.size());
memberList.stream()
.filter(Method.class::isInstance)
.forEach(member -> potentiallyOverwritingMethodList.add((Method) member));
}
if (constraintWeightDescriptorMap.isEmpty()) {
throw new IllegalStateException("The constraintConfigurationClass (" + constraintConfigurationClass
+ ") must have at least 1 member with a "
+ ConstraintWeight.class.getSimpleName() + " annotation.");
}
}
private void processPackAnnotation() {
var packAnnotation = constraintConfigurationClass.getAnnotation(ConstraintConfiguration.class);
if (packAnnotation == null) {
throw new IllegalStateException("The constraintConfigurationClass (" + constraintConfigurationClass
+ ") has been specified as a @" + ConstraintConfigurationProvider.class.getSimpleName()
+ " in the solution class (" + solutionDescriptor.getSolutionClass() + ")," +
" but does not have a @" + ConstraintConfiguration.class.getSimpleName() + " annotation.");
}
// If a @ConstraintConfiguration extends a @ConstraintConfiguration, their constraintPackage might differ.
// So the ConstraintWeightDescriptors parse packAnnotation.constraintPackage() themselves.
constraintPackage = packAnnotation.constraintPackage();
if (constraintPackage.isEmpty()) {
var pack = constraintConfigurationClass.getPackage();
constraintPackage = (pack == null) ? "" : pack.getName();
}
}
private void processParameterAnnotation(MemberAccessorFactory memberAccessorFactory, DomainAccessType domainAccessType,
Member member, ScoreDefinition<?> scoreDefinition) {
if (((AnnotatedElement) member).isAnnotationPresent(ConstraintWeight.class)) {
var memberAccessor = memberAccessorFactory.buildAndCacheMemberAccessor(member, FIELD_OR_READ_METHOD,
ConstraintWeight.class, domainAccessType);
if (constraintWeightDescriptorMap.containsKey(memberAccessor.getName())) {
var duplicate = constraintWeightDescriptorMap.get(memberAccessor.getName()).getMemberAccessor();
throw new IllegalStateException("The constraintConfigurationClass (" + constraintConfigurationClass
+ ") has a @" + ConstraintWeight.class.getSimpleName()
+ " annotated member (" + memberAccessor
+ ") that is duplicated by a member (" + duplicate + ").\n"
+ "Maybe the annotation is defined on both the field and its getter.");
}
if (!scoreDefinition.getScoreClass().isAssignableFrom(memberAccessor.getType())) {
throw new IllegalStateException("The constraintConfigurationClass (" + constraintConfigurationClass
+ ") has a @" + ConstraintWeight.class.getSimpleName()
+ " annotated member (" + memberAccessor
+ ") with a return type (" + memberAccessor.getType()
+ ") that is not assignable to the score class (" + scoreDefinition.getScoreClass() + ").\n"
+ "Maybe make that member (" + memberAccessor.getName() + ") return the score class ("
+ scoreDefinition.getScoreClass().getSimpleName() + ") instead.");
}
var constraintWeightDescriptor = new ConstraintWeightDescriptor<Solution_>(memberAccessor);
constraintWeightDescriptorMap.put(memberAccessor.getName(), constraintWeightDescriptor);
}
}
// ************************************************************************
// Worker methods
// ************************************************************************
public SolutionDescriptor<Solution_> getSolutionDescriptor() {
return solutionDescriptor;
}
public Class<?> getConstraintConfigurationClass() {
return constraintConfigurationClass;
}
public Set<ConstraintRef> getSupportedConstraints() {
return constraintWeightDescriptorMap.values()
.stream()
.map(ConstraintWeightDescriptor::getConstraintRef)
.collect(Collectors.toSet());
}
public ConstraintWeightDescriptor<Solution_> findConstraintWeightDescriptor(ConstraintRef constraintRef) {
return constraintWeightDescriptorMap.values().stream()
.filter(constraintWeightDescriptor -> constraintWeightDescriptor.getConstraintRef().equals(constraintRef))
.findFirst()
.orElse(null);
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + constraintConfigurationClass.getName() + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/ConstraintWeightDescriptor.java | package ai.timefold.solver.core.impl.domain.solution;
import java.util.Objects;
import java.util.function.Function;
import ai.timefold.solver.core.api.domain.constraintweight.ConstraintConfiguration;
import ai.timefold.solver.core.api.domain.constraintweight.ConstraintWeight;
import ai.timefold.solver.core.api.domain.solution.ConstraintWeightOverrides;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintRef;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @deprecated Use {@link ConstraintWeightOverrides} instead.
*/
@Deprecated(forRemoval = true, since = "1.13.0")
final class ConstraintWeightDescriptor<Solution_> {
private final ConstraintRef constraintRef;
private final MemberAccessor memberAccessor;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public ConstraintWeightDescriptor(MemberAccessor memberAccessor) {
ConstraintWeight constraintWeightAnnotation = memberAccessor.getAnnotation(ConstraintWeight.class);
String constraintPackage = constraintWeightAnnotation.constraintPackage();
if (constraintPackage.isEmpty()) {
// If a @ConstraintConfiguration extends a @ConstraintConfiguration, their constraintPackage might differ.
ConstraintConfiguration constraintConfigurationAnnotation = memberAccessor.getDeclaringClass()
.getAnnotation(ConstraintConfiguration.class);
if (constraintConfigurationAnnotation == null) {
throw new IllegalStateException("Impossible state: " + ConstraintConfigurationDescriptor.class.getSimpleName()
+ " only reflects over members with a @" + ConstraintConfiguration.class.getSimpleName()
+ " annotation.");
}
constraintPackage = constraintConfigurationAnnotation.constraintPackage();
if (constraintPackage.isEmpty()) {
Package pack = memberAccessor.getDeclaringClass().getPackage();
constraintPackage = (pack == null) ? "" : pack.getName();
}
}
this.constraintRef = ConstraintRef.of(constraintPackage, constraintWeightAnnotation.value());
this.memberAccessor = memberAccessor;
}
public ConstraintRef getConstraintRef() {
return constraintRef;
}
public MemberAccessor getMemberAccessor() {
return memberAccessor;
}
public Function<Solution_, Score<?>> createExtractor(MemberAccessor constraintConfigurationMemberAccessor) {
return (Solution_ solution) -> {
Object constraintConfiguration = Objects.requireNonNull(
constraintConfigurationMemberAccessor.executeGetter(solution),
"Constraint configuration provider (" + constraintConfigurationMemberAccessor +
") returns null.");
return (Score<?>) memberAccessor.executeGetter(constraintConfiguration);
};
}
@Override
public String toString() {
return constraintRef.toString();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/ConstraintWeightSupplier.java | package ai.timefold.solver.core.impl.domain.solution;
import java.util.Set;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.domain.constraintweight.ConstraintConfiguration;
import ai.timefold.solver.core.api.domain.solution.ConstraintWeightOverrides;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintRef;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
public sealed interface ConstraintWeightSupplier<Solution_, Score_ extends Score<Score_>>
permits OverridesBasedConstraintWeightSupplier, ConstraintConfigurationBasedConstraintWeightSupplier {
void initialize(SolutionDescriptor<Solution_> solutionDescriptor, MemberAccessorFactory memberAccessorFactory,
DomainAccessType domainAccessType);
/**
* Will be called after {@link #initialize(SolutionDescriptor, MemberAccessorFactory, DomainAccessType)}.
* Has the option of failing fast in case of discrepancies
* between the constraints defined in {@link ConstraintProvider}
* and the constraints defined in the configuration.
*
* @param userDefinedConstraints never null
*/
void validate(Solution_ workingSolution, Set<ConstraintRef> userDefinedConstraints);
/**
* The class that carries the constraint weights.
* It will either be annotated by {@link ConstraintConfiguration},
* or be {@link ConstraintWeightOverrides}.
*
* @return never null
*/
Class<?> getProblemFactClass();
String getDefaultConstraintPackage();
/**
* Get the weight for the constraint if known to the supplier.
* Supplies may choose not to provide a value for unknown constraints,
* which is the case for {@link OverridesBasedConstraintWeightSupplier}.
* {@link ConstraintConfigurationBasedConstraintWeightSupplier} will always provide a value.
*
* @param constraintRef never null
* @param workingSolution never null
* @return may be null, if the provider does not know the constraint
*/
Score_ getConstraintWeight(ConstraintRef constraintRef, Solution_ workingSolution);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/DefaultConstraintWeightOverrides.java | package ai.timefold.solver.core.impl.domain.solution;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import ai.timefold.solver.core.api.domain.solution.ConstraintWeightOverrides;
import ai.timefold.solver.core.api.score.Score;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;
public record DefaultConstraintWeightOverrides<Score_ extends Score<Score_>>(Map<String, Score_> constraintWeightMap)
implements
ConstraintWeightOverrides<Score_> {
public DefaultConstraintWeightOverrides(Map<String, Score_> constraintWeightMap) {
this.constraintWeightMap = new TreeMap<>(constraintWeightMap); // Keep consistent order for reproducibility.
}
@Override
public @Nullable Score_ getConstraintWeight(@NonNull String constraintName) {
return constraintWeightMap.get(constraintName);
}
@Override
public @NonNull Set<String> getKnownConstraintNames() {
return Collections.unmodifiableSet(constraintWeightMap.keySet());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/OverridesBasedConstraintWeightSupplier.java | package ai.timefold.solver.core.impl.domain.solution;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.domain.solution.ConstraintWeightOverrides;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintRef;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
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.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint;
public final class OverridesBasedConstraintWeightSupplier<Score_ extends Score<Score_>, Solution_>
implements ConstraintWeightSupplier<Solution_, Score_> {
public static <Solution_, Score_ extends Score<Score_>> ConstraintWeightSupplier<Solution_, Score_> create(
SolutionDescriptor<Solution_> solutionDescriptor, DescriptorPolicy descriptorPolicy,
Field field) {
var method = ReflectionHelper.getGetterMethod(field.getDeclaringClass(), field.getName());
Class<? extends ConstraintWeightOverrides<Score_>> overridesClass;
Member member;
// Prefer method to field
if (method == null) {
member = field;
overridesClass = (Class<? extends ConstraintWeightOverrides<Score_>>) field.getType();
} else {
member = method;
overridesClass = (Class<? extends ConstraintWeightOverrides<Score_>>) method.getReturnType();
}
var memberAccessor = descriptorPolicy.getMemberAccessorFactory().buildAndCacheMemberAccessor(member,
MemberAccessorFactory.MemberAccessorType.FIELD_OR_GETTER_METHOD_WITH_SETTER,
descriptorPolicy.getDomainAccessType());
return new OverridesBasedConstraintWeightSupplier<>(solutionDescriptor, memberAccessor, overridesClass);
}
private final SolutionDescriptor<Solution_> solutionDescriptor;
private final MemberAccessor overridesAccessor;
private final Class<? extends ConstraintWeightOverrides<Score_>> overridesClass;
private OverridesBasedConstraintWeightSupplier(SolutionDescriptor<Solution_> solutionDescriptor,
MemberAccessor overridesAccessor, Class<? extends ConstraintWeightOverrides<Score_>> overridesClass) {
this.solutionDescriptor = Objects.requireNonNull(solutionDescriptor);
this.overridesAccessor = Objects.requireNonNull(overridesAccessor);
this.overridesClass = Objects.requireNonNull(overridesClass);
}
@Override
public void initialize(SolutionDescriptor<Solution_> solutionDescriptor, MemberAccessorFactory memberAccessorFactory,
DomainAccessType domainAccessType) {
// No need to do anything.
}
@Override
public void validate(Solution_ workingSolution, Set<ConstraintRef> userDefinedConstraints) {
var userDefinedConstraintNames = userDefinedConstraints.stream()
.map(ConstraintRef::constraintName)
.collect(Collectors.toSet());
// Constraint verifier is known to cause null here.
var overrides = workingSolution == null ? ConstraintWeightOverrides.none()
: Objects.requireNonNull(getConstraintWeights(workingSolution));
var supportedConstraints = overrides.getKnownConstraintNames();
var excessiveConstraints = supportedConstraints.stream()
.filter(constraintName -> !userDefinedConstraintNames.contains(constraintName))
.collect(Collectors.toSet());
if (!excessiveConstraints.isEmpty()) {
throw new IllegalStateException("""
The constraint weight overrides contain the following constraints (%s) \
that are not in the user-defined constraints (%s).
Maybe check your %s for missing constraints."""
.formatted(excessiveConstraints, userDefinedConstraintNames,
ConstraintProvider.class.getSimpleName()));
}
// Constraints are allowed to be missing; the default value provided by the ConstraintProvider will be used.
}
@SuppressWarnings("unchecked")
private ConstraintWeightOverrides<Score_> getConstraintWeights(Solution_ workingSolution) {
return (ConstraintWeightOverrides<Score_>) overridesAccessor.executeGetter(workingSolution);
}
@Override
public Class<?> getProblemFactClass() {
return overridesClass;
}
@Override
public String getDefaultConstraintPackage() {
return solutionDescriptor.getSolutionClass().getPackageName();
}
@Override
public Score_ getConstraintWeight(ConstraintRef constraintRef, Solution_ workingSolution) {
if (!constraintRef.packageName().equals(getDefaultConstraintPackage())) {
throw new IllegalStateException("""
The constraint (%s) is not in the default package (%s).
Constraint packages are deprecated, check your constraint implementation."""
.formatted(constraintRef, getDefaultConstraintPackage()));
}
if (workingSolution == null) { // ConstraintVerifier is known to cause null here.
return null;
}
var weight = (Score_) getConstraintWeights(workingSolution).getConstraintWeight(constraintRef.constraintName());
if (weight == null) { // This is fine; use default value from ConstraintProvider.
return null;
}
AbstractConstraint.validateWeight(solutionDescriptor, constraintRef, weight);
return weight;
}
@Override
public String toString() {
return "Constraint weights based on " + overridesAccessor + ".";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner/DeepCloningFieldCloner.java | package ai.timefold.solver.core.impl.domain.solution.cloner;
import java.lang.reflect.Field;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import ai.timefold.solver.core.impl.domain.common.accessor.FieldHandle;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
/**
* @implNote This class is thread-safe.
*/
final class DeepCloningFieldCloner {
private final AtomicReference<Metadata> valueDeepCloneDecision = new AtomicReference<>();
private final AtomicInteger fieldDeepCloneDecision = new AtomicInteger(-1);
private final FieldHandle fieldHandle;
public DeepCloningFieldCloner(Field field) {
this.fieldHandle = FieldHandle.of(Objects.requireNonNull(field));
}
public FieldHandle getFieldHandles() {
return fieldHandle;
}
/**
*
* @param solutionDescriptor never null
* @param original never null, source object
* @param clone never null, target object
* @return null if cloned, the original uncloned value otherwise
* @param <C>
*/
public <C> Object clone(SolutionDescriptor<?> solutionDescriptor, C original, C clone) {
Object originalValue = FieldCloningUtils.getObjectFieldValue(original, fieldHandle);
if (deepClone(solutionDescriptor, original.getClass(), originalValue)) { // Defer filling in the field.
return originalValue;
} else { // Shallow copy.
FieldCloningUtils.setObjectFieldValue(clone, fieldHandle, originalValue);
return null;
}
}
/**
* Obtaining the decision on whether or not to deep-clone is expensive.
* This method exists to cache those computations as much as possible,
* while maintaining thread-safety.
*
* @param solutionDescriptor never null
* @param fieldTypeClass never null
* @param originalValue never null
* @return true if the value needs to be deep-cloned
*/
private boolean deepClone(SolutionDescriptor<?> solutionDescriptor, Class<?> fieldTypeClass, Object originalValue) {
if (originalValue == null) {
return false;
}
/*
* This caching mechanism takes advantage of the fact that, for a particular field on a particular class,
* the types of values contained are unlikely to change and therefore it is safe to cache the calculation.
* In the unlikely event of a cache miss, we recompute.
*/
boolean isValueDeepCloned = valueDeepCloneDecision.updateAndGet(old -> {
Class<?> originalClass = originalValue.getClass();
if (old == null || old.clz != originalClass) {
return new Metadata(originalClass, DeepCloningUtils.isClassDeepCloned(solutionDescriptor, originalClass));
} else {
return old;
}
}).decision;
if (isValueDeepCloned) { // The value has to be deep-cloned. Does not matter what the field says.
return true;
}
/*
* The decision to clone a field is constant once it has been made.
* The fieldTypeClass is guaranteed to not change for the particular field.
*/
if (fieldDeepCloneDecision.get() < 0) {
fieldDeepCloneDecision.set(
DeepCloningUtils.isFieldDeepCloned(solutionDescriptor, getFieldHandles().field(), fieldTypeClass) ? 1 : 0);
}
return fieldDeepCloneDecision.get() == 1;
}
private record Metadata(Class<?> clz, boolean decision) {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner/DeepCloningUtils.java | package ai.timefold.solver.core.impl.domain.solution.cloner;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.MonthDay;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.Period;
import java.time.Year;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.Set;
import java.util.UUID;
import ai.timefold.solver.core.api.domain.lookup.PlanningId;
import ai.timefold.solver.core.api.domain.solution.cloner.DeepPlanningClone;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.domain.common.ReflectionHelper;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
public final class DeepCloningUtils {
// Instances of these JDK classes will never be deep-cloned.
public static final Set<Class<?>> IMMUTABLE_CLASSES = Set.of(
// Numbers
Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, BigInteger.class, BigDecimal.class,
// Optional
Optional.class, OptionalInt.class, OptionalLong.class, OptionalDouble.class,
// Date and time
Duration.class, Instant.class, LocalDate.class, LocalDateTime.class, LocalTime.class, MonthDay.class,
OffsetDateTime.class, OffsetTime.class, Period.class, Year.class, YearMonth.class, ZonedDateTime.class,
ZoneId.class, ZoneOffset.class,
// Others
Boolean.class, Character.class, String.class, UUID.class);
/**
* Gets the deep cloning decision for a particular value assigned to a field,
* memoizing the result.
*
* @param field the field to get the deep cloning decision of
* @param owningClass the class that owns the field; can be different
* from the field's declaring class (ex: subclass)
* @param actualValueClass the class of the value that is currently assigned
* to the field; can be different from the field type
* (ex: for the field "List myList", the actual value
* class might be ArrayList).
* @return true iff the field should be deep cloned with a particular value.
*/
public static boolean isDeepCloned(SolutionDescriptor<?> solutionDescriptor, Field field, Class<?> owningClass,
Class<?> actualValueClass) {
return isClassDeepCloned(solutionDescriptor, actualValueClass)
|| isFieldDeepCloned(solutionDescriptor, field, owningClass);
}
/**
* Gets the deep cloning decision for a field.
*
* @param field The field to get the deep cloning decision of
* @param owningClass The class that owns the field; can be different
* from the field's declaring class (ex: subclass).
* @return True iff the field should always be deep cloned (regardless of value).
*/
public static boolean isFieldDeepCloned(SolutionDescriptor<?> solutionDescriptor, Field field, Class<?> owningClass) {
Class<?> fieldType = field.getType();
if (isImmutable(fieldType)) {
return false;
} else {
return needsDeepClone(solutionDescriptor, field, owningClass);
}
}
public static boolean needsDeepClone(SolutionDescriptor<?> solutionDescriptor, Field field, Class<?> owningClass) {
return isFieldAnEntityPropertyOnSolution(solutionDescriptor, field, owningClass)
|| isFieldAnEntityOrSolution(solutionDescriptor, field)
|| isFieldAPlanningListVariable(field, owningClass)
|| isFieldADeepCloneProperty(field, owningClass);
}
public static boolean isImmutable(Class<?> clz) {
if (clz.isPrimitive() || Score.class.isAssignableFrom(clz)) {
return true;
} else if (clz.isRecord() || clz.isEnum()) {
if (clz.isAnnotationPresent(DeepPlanningClone.class)) {
throw new IllegalStateException("""
The class (%s) is annotated with @%s, but it is immutable.
Deep-cloning enums and records is not supported."""
.formatted(clz.getName(), DeepPlanningClone.class.getSimpleName()));
} else if (clz.isAnnotationPresent(PlanningId.class)) {
throw new IllegalStateException("""
The class (%s) is annotated with @%s, but it is immutable.
Immutable objects do not need @%s."""
.formatted(clz.getName(), PlanningId.class.getSimpleName(), PlanningId.class.getSimpleName()));
}
return true;
} else if (PlanningImmutable.class.isAssignableFrom(clz)) {
if (PlanningCloneable.class.isAssignableFrom(clz)) {
throw new IllegalStateException("""
The class (%s) implements %s, but it is %s.
Immutable objects can not be cloned."""
.formatted(clz.getName(), PlanningCloneable.class.getSimpleName(),
PlanningImmutable.class.getSimpleName()));
}
return true;
}
return IMMUTABLE_CLASSES.contains(clz);
}
/**
* Return true only if a field represents an entity property on the solution class.
* An entity property is one who type is a PlanningEntity or a collection
* of PlanningEntity.
*
* @param field The field to get the deep cloning decision of
* @param owningClass The class that owns the field; can be different
* from the field's declaring class (ex: subclass).
* @return True only if the field is an entity property on the solution class.
* May return false if the field getter/setter is complex.
*/
static boolean isFieldAnEntityPropertyOnSolution(SolutionDescriptor<?> solutionDescriptor, Field field,
Class<?> owningClass) {
if (!solutionDescriptor.getSolutionClass().isAssignableFrom(owningClass)) {
return false;
}
// field.getDeclaringClass() is a superclass of or equal to the owningClass
String fieldName = field.getName();
// This assumes we're dealing with a simple getter/setter.
// If that assumption is false, validateCloneSolution(...) fails-fast.
if (solutionDescriptor.getEntityMemberAccessorMap().get(fieldName) != null) {
return true;
}
// This assumes we're dealing with a simple getter/setter.
// If that assumption is false, validateCloneSolution(...) fails-fast.
return solutionDescriptor.getEntityCollectionMemberAccessorMap().get(fieldName) != null;
}
/**
* Returns true iff a field represent an Entity/Solution or a collection
* of Entity/Solution.
*
* @param field The field to get the deep cloning decision of
* @return True only if the field represents or contains a PlanningEntity or PlanningSolution
*/
private static boolean isFieldAnEntityOrSolution(SolutionDescriptor<?> solutionDescriptor, Field field) {
Class<?> type = field.getType();
if (isClassDeepCloned(solutionDescriptor, type)) {
return true;
}
if (Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type)) {
return isTypeArgumentDeepCloned(solutionDescriptor, field.getGenericType());
} else if (type.isArray()) {
return isClassDeepCloned(solutionDescriptor, type.getComponentType());
}
return false;
}
public static boolean isClassDeepCloned(SolutionDescriptor<?> solutionDescriptor, Class<?> type) {
if (isImmutable(type)) {
return false;
}
return solutionDescriptor.hasEntityDescriptor(type)
|| solutionDescriptor.getSolutionClass().isAssignableFrom(type)
|| type.isAnnotationPresent(DeepPlanningClone.class);
}
private static boolean isTypeArgumentDeepCloned(SolutionDescriptor<?> solutionDescriptor, Type genericType) {
// Check the generic type arguments of the field.
// It is possible for fields and methods, but not instances.
if (genericType instanceof ParameterizedType parameterizedType) {
for (Type actualTypeArgument : parameterizedType.getActualTypeArguments()) {
if (actualTypeArgument instanceof Class class1
&& isClassDeepCloned(solutionDescriptor, class1)) {
return true;
}
if (isTypeArgumentDeepCloned(solutionDescriptor, actualTypeArgument)) {
return true;
}
}
}
return false;
}
private static boolean isFieldADeepCloneProperty(Field field, Class<?> owningClass) {
if (field.isAnnotationPresent(DeepPlanningClone.class)) {
return true;
}
Method getterMethod = ReflectionHelper.getGetterMethod(owningClass, field.getName());
return getterMethod != null && getterMethod.isAnnotationPresent(DeepPlanningClone.class);
}
private static boolean isFieldAPlanningListVariable(Field field, Class<?> owningClass) {
if (!field.isAnnotationPresent(PlanningListVariable.class)) {
Method getterMethod = ReflectionHelper.getGetterMethod(owningClass, field.getName());
return getterMethod != null && getterMethod.isAnnotationPresent(PlanningListVariable.class);
} else {
return true;
}
}
private DeepCloningUtils() {
// No external instances.
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner/FieldAccessingSolutionCloner.java | package ai.timefold.solver.core.impl.domain.solution.cloner;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Array;
import java.lang.reflect.Modifier;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import ai.timefold.solver.core.api.domain.solution.cloner.DeepPlanningClone;
import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.util.CollectionUtils;
import ai.timefold.solver.core.impl.util.ConcurrentMemoization;
import org.jspecify.annotations.NonNull;
/**
* This class is thread-safe; score directors from the same solution descriptor will share the same instance.
*/
public final class FieldAccessingSolutionCloner<Solution_> implements SolutionCloner<Solution_> {
private static final int MINIMUM_EXPECTED_OBJECT_COUNT = 1_000;
private final Map<Class<?>, ClassMetadata> classMetadataMemoization = new ConcurrentMemoization<>();
private final SolutionDescriptor<Solution_> solutionDescriptor;
// Exists to avoid creating a new lambda instance on every call to map.computeIfAbsent.
private final Function<Class<?>, ClassMetadata> classMetadataConstructor;
// Updated at the end of cloning, with the bet that the next solution to clone will have a similar number of objects.
private final AtomicInteger expectedObjectCountRef = new AtomicInteger(MINIMUM_EXPECTED_OBJECT_COUNT);
public FieldAccessingSolutionCloner(SolutionDescriptor<Solution_> solutionDescriptor) {
this.solutionDescriptor = solutionDescriptor;
this.classMetadataConstructor = clz -> new ClassMetadata(solutionDescriptor, clz);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public @NonNull Solution_ cloneSolution(@NonNull Solution_ originalSolution) {
var expectedObjectCount = expectedObjectCountRef.get();
var originalToCloneMap = CollectionUtils.newIdentityHashMap(expectedObjectCount);
var unprocessedQueue = new ArrayDeque<Unprocessed>(expectedObjectCount);
var cloneSolution = clone(originalSolution, originalToCloneMap, unprocessedQueue,
retrieveClassMetadata(originalSolution.getClass()));
while (!unprocessedQueue.isEmpty()) {
var unprocessed = unprocessedQueue.remove();
var cloneValue = process(unprocessed, originalToCloneMap, unprocessedQueue);
FieldCloningUtils.setObjectFieldValue(unprocessed.bean, unprocessed.cloner.getFieldHandles(), cloneValue);
}
expectedObjectCountRef.updateAndGet(old -> decideNextExpectedObjectCount(old, originalToCloneMap.size()));
validateCloneSolution(originalSolution, cloneSolution);
return cloneSolution;
}
private static int decideNextExpectedObjectCount(int currentExpectedObjectCount, int currentObjectCount) {
// For cases where solutions of vastly different sizes are cloned in a row,
// we want to make sure the memory requirements don't grow too large, or the capacity too small.
var halfTheDifference = (int) Math.round(Math.abs(currentObjectCount - currentExpectedObjectCount) / 2.0);
if (currentObjectCount > currentExpectedObjectCount) {
// Guard against integer overflow.
return Math.min(currentExpectedObjectCount + halfTheDifference, Integer.MAX_VALUE);
} else if (currentObjectCount < currentExpectedObjectCount) {
// Don't go exceedingly low; cloning so few objects is always fast, re-growing the map back would be.
return Math.max(currentExpectedObjectCount - halfTheDifference, MINIMUM_EXPECTED_OBJECT_COUNT);
} else {
return currentExpectedObjectCount;
}
}
/**
* Used by GIZMO when it encounters an undeclared entity class, such as when an abstract planning entity is extended.
*/
@SuppressWarnings("unused")
public Object gizmoFallbackDeepClone(Object originalValue, Map<Object, Object> originalToCloneMap) {
if (originalValue == null) {
return null;
}
var unprocessedQueue = new ArrayDeque<Unprocessed>(expectedObjectCountRef.get());
var fieldType = originalValue.getClass();
return clone(originalValue, originalToCloneMap, unprocessedQueue, fieldType);
}
private Object clone(Object originalValue, Map<Object, Object> originalToCloneMap, Queue<Unprocessed> unprocessedQueue,
Class<?> fieldType) {
if (originalValue instanceof Collection<?> collection) {
return cloneCollection(fieldType, collection, originalToCloneMap, unprocessedQueue);
} else if (originalValue instanceof Map<?, ?> map) {
return cloneMap(fieldType, map, originalToCloneMap, unprocessedQueue);
}
var originalClass = originalValue.getClass();
if (originalClass.isArray()) {
return cloneArray(fieldType, originalValue, originalToCloneMap, unprocessedQueue);
} else {
return clone(originalValue, originalToCloneMap, unprocessedQueue, retrieveClassMetadata(originalClass));
}
}
private Object process(Unprocessed unprocessed, Map<Object, Object> originalToCloneMap,
Queue<Unprocessed> unprocessedQueue) {
var originalValue = unprocessed.originalValue;
var field = unprocessed.cloner.getFieldHandles().field();
var fieldType = field.getType();
return clone(originalValue, originalToCloneMap, unprocessedQueue, fieldType);
}
@SuppressWarnings("unchecked")
private <C> C clone(C original, Map<Object, Object> originalToCloneMap, Queue<Unprocessed> unprocessedQueue,
ClassMetadata declaringClassMetadata) {
if (original == null) {
return null;
}
var existingClone = (C) originalToCloneMap.get(original);
if (existingClone != null) {
return existingClone;
}
var declaringClass = (Class<C>) original.getClass();
var clone = constructClone(original, declaringClassMetadata);
originalToCloneMap.put(original, clone);
copyFields(declaringClass, original, clone, unprocessedQueue, declaringClassMetadata);
return clone;
}
@SuppressWarnings("unchecked")
private static <C> C constructClone(C original, ClassMetadata classMetadata) {
if (original instanceof PlanningCloneable<?> planningCloneable) {
return (C) planningCloneable.createNewInstance();
} else {
return constructClone(classMetadata);
}
}
@SuppressWarnings("unchecked")
private static <C> C constructClone(ClassMetadata classMetadata) {
var constructor = classMetadata.getConstructor();
try {
return (C) constructor.invoke();
} catch (Throwable e) {
throw new IllegalStateException(
"Can not create a new instance of class (%s) for a planning clone, using its no-arg constructor."
.formatted(classMetadata.declaringClass.getCanonicalName()),
e);
}
}
private <C> void copyFields(Class<C> clazz, C original, C clone, Queue<Unprocessed> unprocessedQueue,
ClassMetadata declaringClassMetadata) {
for (var fieldCloner : declaringClassMetadata.getCopiedFieldArray()) {
fieldCloner.clone(original, clone);
}
for (var fieldCloner : declaringClassMetadata.getClonedFieldArray()) {
var unprocessedValue = fieldCloner.clone(solutionDescriptor, original, clone);
if (unprocessedValue != null) {
unprocessedQueue.add(new Unprocessed(clone, fieldCloner, unprocessedValue));
}
}
var superclass = clazz.getSuperclass();
if (superclass != null && superclass != Object.class) {
copyFields(superclass, original, clone, unprocessedQueue, retrieveClassMetadata(superclass));
}
}
private Object cloneArray(Class<?> expectedType, Object originalArray, Map<Object, Object> originalToCloneMap,
Queue<Unprocessed> unprocessedQueue) {
var arrayLength = Array.getLength(originalArray);
if (arrayLength == 0) {
return originalArray; // No need to clone an empty array.
}
var cloneArray = Array.newInstance(originalArray.getClass().getComponentType(), arrayLength);
if (!expectedType.isInstance(cloneArray)) {
throw new IllegalStateException("""
The cloneArrayClass (%s) created for originalArrayClass (%s) is not assignable to the field's type (%s).
Maybe consider replacing the default %s."""
.formatted(cloneArray.getClass(), originalArray.getClass(), expectedType,
SolutionCloner.class.getSimpleName()));
}
var reuseHelper = new ClassMetadataReuseHelper(this::retrieveClassMetadata);
for (var i = 0; i < arrayLength; i++) {
var cloneElement = cloneCollectionsElementIfNeeded(Array.get(originalArray, i), originalToCloneMap,
unprocessedQueue, reuseHelper);
Array.set(cloneArray, i, cloneElement);
}
return cloneArray;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private <E> Collection<E> cloneCollection(Class<?> expectedType, Collection<E> originalCollection,
Map<Object, Object> originalToCloneMap, Queue<Unprocessed> unprocessedQueue) {
if (originalCollection instanceof EnumSet enumSet) {
return EnumSet.copyOf(enumSet);
}
var cloneCollection = constructCloneCollection(originalCollection);
if (!expectedType.isInstance(cloneCollection)) {
throw new IllegalStateException(
"""
The cloneCollectionClass (%s) created for originalCollectionClass (%s) is not assignable to the field's type (%s).
Maybe consider replacing the default %s."""
.formatted(cloneCollection.getClass(), originalCollection.getClass(), expectedType,
SolutionCloner.class.getSimpleName()));
}
if (originalCollection.isEmpty()) {
return cloneCollection; // No need to clone any elements.
}
var reuseHelper = new ClassMetadataReuseHelper(this::retrieveClassMetadata);
for (var originalElement : originalCollection) {
var cloneElement =
cloneCollectionsElementIfNeeded(originalElement, originalToCloneMap, unprocessedQueue, reuseHelper);
cloneCollection.add(cloneElement);
}
return cloneCollection;
}
@SuppressWarnings("unchecked")
private static <E> Collection<E> constructCloneCollection(Collection<E> originalCollection) {
// TODO Don't hardcode all standard collections
if (originalCollection instanceof PlanningCloneable<?> planningCloneable) {
return (Collection<E>) planningCloneable.createNewInstance();
}
if (originalCollection instanceof LinkedList) {
return new LinkedList<>();
}
var size = originalCollection.size();
if (originalCollection instanceof Set) {
if (originalCollection instanceof SortedSet<E> set) {
var setComparator = set.comparator();
return new TreeSet<>(setComparator);
} else if (!(originalCollection instanceof LinkedHashSet)) {
// Set is explicitly not ordered, so we can use a HashSet.
// Can be replaced by checking for SequencedSet, but that is Java 21+.
return CollectionUtils.newHashSet(size);
} else { // Default to a LinkedHashSet to respect order.
return CollectionUtils.newLinkedHashSet(size);
}
} else if (originalCollection instanceof Deque) {
return new ArrayDeque<>(size);
}
// Default collection
return new ArrayList<>(size);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private <K, V> Map<K, V> cloneMap(Class<?> expectedType, Map<K, V> originalMap, Map<Object, Object> originalToCloneMap,
Queue<Unprocessed> unprocessedQueue) {
if (originalMap instanceof EnumMap<?, ?> enumMap) {
var cloneMap = new EnumMap(enumMap);
if (cloneMap.isEmpty()) {
return (Map<K, V>) cloneMap;
}
var reuseHelper = new ClassMetadataReuseHelper(this::retrieveClassMetadata);
for (var originalEntry : enumMap.entrySet()) {
var originalValue = originalEntry.getValue();
var cloneValue = cloneCollectionsElementIfNeeded(originalValue, originalToCloneMap, unprocessedQueue,
reuseHelper);
if (originalValue != cloneValue) { // Already exists in the map.
cloneMap.put(originalEntry.getKey(), cloneValue);
}
}
return cloneMap;
}
var cloneMap = constructCloneMap(originalMap);
if (!expectedType.isInstance(cloneMap)) {
throw new IllegalStateException("""
The cloneMapClass (%s) created for originalMapClass (%s) is not assignable to the field's type (%s).
Maybe consider replacing the default %s."""
.formatted(cloneMap.getClass(), originalMap.getClass(), expectedType,
SolutionCloner.class.getSimpleName()));
}
if (originalMap.isEmpty()) {
return cloneMap; // No need to clone any entries.
}
var keyReuseHelper = new ClassMetadataReuseHelper(this::retrieveClassMetadata);
var valueReuseHelper = new ClassMetadataReuseHelper(this::retrieveClassMetadata);
for (var originalEntry : originalMap.entrySet()) {
var cloneKey = cloneCollectionsElementIfNeeded(originalEntry.getKey(), originalToCloneMap, unprocessedQueue,
keyReuseHelper);
var cloneValue = cloneCollectionsElementIfNeeded(originalEntry.getValue(), originalToCloneMap, unprocessedQueue,
valueReuseHelper);
cloneMap.put(cloneKey, cloneValue);
}
return cloneMap;
}
@SuppressWarnings("unchecked")
private static <K, V> Map<K, V> constructCloneMap(Map<K, V> originalMap) {
if (originalMap instanceof PlanningCloneable<?> planningCloneable) {
return (Map<K, V>) planningCloneable.createNewInstance();
}
// Normally, a Map will never be selected for cloning, but extending implementations might anyway.
if (originalMap instanceof SortedMap<K, V> map) {
var setComparator = map.comparator();
return new TreeMap<>(setComparator);
}
var originalMapSize = originalMap.size();
if (!(originalMap instanceof LinkedHashMap<?, ?>)) {
// Map is explicitly not ordered, so we can use a HashMap.
// Can be replaced by checking for SequencedMap, but that is Java 21+.
return CollectionUtils.newHashMap(originalMapSize);
} else { // Default to a LinkedHashMap to respect order.
return CollectionUtils.newLinkedHashMap(originalMapSize);
}
}
private ClassMetadata retrieveClassMetadata(Class<?> declaringClass) {
return classMetadataMemoization.computeIfAbsent(declaringClass, classMetadataConstructor);
}
@SuppressWarnings("unchecked")
private <C> C cloneCollectionsElementIfNeeded(C original, Map<Object, Object> originalToCloneMap,
Queue<Unprocessed> unprocessedQueue, ClassMetadataReuseHelper classMetadataReuseHelper) {
if (original == null) {
return null;
}
/*
* Because an element which is itself a Collection or Map might hold an entity,
* we clone it too.
* The List<Long> in Map<String, List<Long>> needs to be cloned if the List<Long> is a shadow,
* despite that Long never needs to be cloned (because it's immutable).
*/
if (original instanceof Collection<?> collection) {
return (C) cloneCollection(Collection.class, collection, originalToCloneMap, unprocessedQueue);
} else if (original instanceof Map<?, ?> map) {
return (C) cloneMap(Map.class, map, originalToCloneMap, unprocessedQueue);
} else if (original.getClass().isArray()) {
return (C) cloneArray(original.getClass(), original, originalToCloneMap, unprocessedQueue);
}
var classMetadata = classMetadataReuseHelper.getClassMetadata(original);
if (classMetadata.isDeepCloned) {
return clone(original, originalToCloneMap, unprocessedQueue, classMetadata);
} else {
return original;
}
}
/**
* Fails fast if {@link DeepCloningUtils#isFieldAnEntityPropertyOnSolution} assumptions were wrong.
*
* @param originalSolution never null
* @param cloneSolution never null
*/
private void validateCloneSolution(Solution_ originalSolution, Solution_ cloneSolution) {
for (var memberAccessor : solutionDescriptor.getEntityMemberAccessorMap().values()) {
validateCloneProperty(originalSolution, cloneSolution, memberAccessor);
}
for (var memberAccessor : solutionDescriptor.getEntityCollectionMemberAccessorMap().values()) {
validateCloneProperty(originalSolution, cloneSolution, memberAccessor);
}
}
private static <Solution_> void validateCloneProperty(Solution_ originalSolution, Solution_ cloneSolution,
MemberAccessor memberAccessor) {
var originalProperty = memberAccessor.executeGetter(originalSolution);
if (originalProperty != null) {
var cloneProperty = memberAccessor.executeGetter(cloneSolution);
if (originalProperty == cloneProperty) {
throw new IllegalStateException("""
The solutionProperty (%s) was not cloned as expected.
The %s failed to recognize that property's field, probably because its field name is different."""
.formatted(memberAccessor.getName(), FieldAccessingSolutionCloner.class.getSimpleName()));
}
}
}
private static final class ClassMetadata {
private final SolutionDescriptor<?> solutionDescriptor;
private final Class<?> declaringClass;
private final boolean isDeepCloned;
/**
* Contains the MethodHandle for the no-arg constructor of the class.
* Lazily initialized to avoid unnecessary reflection overhead when the constructor is not called.
*/
private volatile MethodHandle constructor = null;
/**
* Contains one cloner for every field that needs to be shallow cloned (= copied).
* Lazy initialized; some types (such as String) will never get here.
*/
private volatile ShallowCloningFieldCloner[] copiedFieldArray;
/**
* Contains one cloner for every field that needs to be deep-cloned.
* Lazy initialized; some types (such as String) will never get here.
*/
private volatile DeepCloningFieldCloner[] clonedFieldArray;
public ClassMetadata(SolutionDescriptor<?> solutionDescriptor, Class<?> declaringClass) {
this.solutionDescriptor = solutionDescriptor;
this.declaringClass = declaringClass;
this.isDeepCloned = DeepCloningUtils.isClassDeepCloned(solutionDescriptor, declaringClass);
}
public MethodHandle getConstructor() {
if (constructor == null) {
synchronized (this) {
if (constructor == null) { // Double-checked locking
try {
var ctor = declaringClass.getDeclaredConstructor();
ctor.setAccessible(true);
constructor = MethodHandles.lookup()
.unreflectConstructor(ctor);
} catch (ReflectiveOperationException e) {
throw new IllegalStateException(
"To create a planning clone, the class (%s) must have a no-arg constructor."
.formatted(declaringClass.getCanonicalName()),
e);
}
}
}
}
return constructor;
}
public ShallowCloningFieldCloner[] getCopiedFieldArray() {
if (copiedFieldArray == null) {
synchronized (this) {
if (copiedFieldArray == null) { // Double-checked locking
copiedFieldArray = Arrays.stream(declaringClass.getDeclaredFields())
.filter(f -> !Modifier.isStatic(f.getModifiers()))
.filter(field -> DeepCloningUtils.isImmutable(field.getType()))
.peek(f -> {
if (DeepCloningUtils.needsDeepClone(solutionDescriptor, f, declaringClass)) {
throw new IllegalStateException("""
The field (%s) of class (%s) needs to be deep-cloned,
but its type (%s) is immutable and can not be deep-cloned.
Maybe remove the @%s annotation from the field?
Maybe do not reference planning entities inside Java records?"""
.formatted(f.getName(), declaringClass.getCanonicalName(),
f.getType().getCanonicalName(),
DeepPlanningClone.class.getSimpleName()));
}
})
.map(ShallowCloningFieldCloner::of)
.toArray(ShallowCloningFieldCloner[]::new);
}
}
}
return copiedFieldArray;
}
public DeepCloningFieldCloner[] getClonedFieldArray() {
if (clonedFieldArray == null) {
synchronized (this) {
if (clonedFieldArray == null) { // Double-checked locking
clonedFieldArray = Arrays.stream(declaringClass.getDeclaredFields())
.filter(f -> !Modifier.isStatic(f.getModifiers()))
.filter(field -> !DeepCloningUtils.isImmutable(field.getType()))
.map(DeepCloningFieldCloner::new)
.toArray(DeepCloningFieldCloner[]::new);
}
}
}
return clonedFieldArray;
}
}
private record Unprocessed(Object bean, DeepCloningFieldCloner cloner, Object originalValue) {
}
/**
* Helper class to reuse ClassMetadata for the same class.
* Use when cloning multiple objects of the same class,
* such as when cloning a collection of objects,
* where it's likely that they will be of the same class.
* This is useful for performance,
* as it avoids repeated calls to the function that retrieves {@link ClassMetadata}.
*/
private static final class ClassMetadataReuseHelper {
private final Function<Class<?>, ClassMetadata> classMetadataFunction;
private Object previousClass;
private ClassMetadata previousClassMetadata;
public ClassMetadataReuseHelper(Function<Class<?>, ClassMetadata> classMetadataFunction) {
this.classMetadataFunction = classMetadataFunction;
}
public @NonNull ClassMetadata getClassMetadata(@NonNull Object object) {
var clazz = object.getClass();
if (clazz != previousClass) {
// Class of the element has changed, so we need to retrieve the metadata again.
previousClass = clazz;
previousClassMetadata = classMetadataFunction.apply(clazz);
}
return previousClassMetadata;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner/FieldCloningUtils.java | package ai.timefold.solver.core.impl.domain.solution.cloner;
import java.lang.reflect.Field;
import ai.timefold.solver.core.impl.domain.common.accessor.FieldHandle;
final class FieldCloningUtils {
static void copyBoolean(Field field, Object original, Object clone) {
boolean originalValue = getBooleanFieldValue(original, field);
setFieldValue(clone, field, originalValue);
}
private static boolean getBooleanFieldValue(Object bean, Field field) {
try {
return field.getBoolean(bean);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnRead(bean, field, e);
}
}
private static void setFieldValue(Object bean, Field field, boolean value) {
try {
field.setBoolean(bean, value);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnWrite(bean, field, value, e);
}
}
static void copyByte(Field field, Object original, Object clone) {
byte originalValue = getByteFieldValue(original, field);
setFieldValue(clone, field, originalValue);
}
private static byte getByteFieldValue(Object bean, Field field) {
try {
return field.getByte(bean);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnRead(bean, field, e);
}
}
private static void setFieldValue(Object bean, Field field, byte value) {
try {
field.setByte(bean, value);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnWrite(bean, field, value, e);
}
}
static void copyChar(Field field, Object original, Object clone) {
char originalValue = getCharFieldValue(original, field);
setFieldValue(clone, field, originalValue);
}
private static char getCharFieldValue(Object bean, Field field) {
try {
return field.getChar(bean);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnRead(bean, field, e);
}
}
private static void setFieldValue(Object bean, Field field, char value) {
try {
field.setChar(bean, value);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnWrite(bean, field, value, e);
}
}
static void copyShort(Field field, Object original, Object clone) {
short originalValue = getShortFieldValue(original, field);
setFieldValue(clone, field, originalValue);
}
private static short getShortFieldValue(Object bean, Field field) {
try {
return field.getShort(bean);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnRead(bean, field, e);
}
}
private static void setFieldValue(Object bean, Field field, short value) {
try {
field.setShort(bean, value);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnWrite(bean, field, value, e);
}
}
static void copyInt(Field field, Object original, Object clone) {
int originalValue = getIntFieldValue(original, field);
setFieldValue(clone, field, originalValue);
}
private static int getIntFieldValue(Object bean, Field field) {
try {
return field.getInt(bean);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnRead(bean, field, e);
}
}
private static void setFieldValue(Object bean, Field field, int value) {
try {
field.setInt(bean, value);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnWrite(bean, field, value, e);
}
}
static void copyLong(Field field, Object original, Object clone) {
long originalValue = getLongFieldValue(original, field);
setFieldValue(clone, field, originalValue);
}
private static long getLongFieldValue(Object bean, Field field) {
try {
return field.getLong(bean);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnRead(bean, field, e);
}
}
private static void setFieldValue(Object bean, Field field, long value) {
try {
field.setLong(bean, value);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnWrite(bean, field, value, e);
}
}
static void copyFloat(Field field, Object original, Object clone) {
float originalValue = getFloatFieldValue(original, field);
setFieldValue(clone, field, originalValue);
}
private static float getFloatFieldValue(Object bean, Field field) {
try {
return field.getFloat(bean);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnRead(bean, field, e);
}
}
private static void setFieldValue(Object bean, Field field, float value) {
try {
field.setFloat(bean, value);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnWrite(bean, field, value, e);
}
}
static void copyDouble(Field field, Object original, Object clone) {
double originalValue = getDoubleFieldValue(original, field);
setFieldValue(clone, field, originalValue);
}
private static double getDoubleFieldValue(Object bean, Field field) {
try {
return field.getDouble(bean);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnRead(bean, field, e);
}
}
private static void setFieldValue(Object bean, Field field, double value) {
try {
field.setDouble(bean, value);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnWrite(bean, field, value, e);
}
}
static void copyObject(FieldHandle handles, Object original, Object clone) {
Object originalValue = FieldCloningUtils.getObjectFieldValue(original, handles);
FieldCloningUtils.setObjectFieldValue(clone, handles, originalValue);
}
static Object getObjectFieldValue(Object bean, FieldHandle handle) {
return handle.get(bean);
}
private static RuntimeException createExceptionOnRead(Object bean, Field field, Throwable rootCause) {
return new IllegalStateException("The class (" + bean.getClass() + ") has a field (" + field
+ ") which cannot be read to create a planning clone.", rootCause);
}
static void setObjectFieldValue(Object bean, FieldHandle handle, Object value) {
try {
handle.set(bean, value);
} catch (Throwable e) {
throw createExceptionOnWrite(bean, handle.field(), value, e);
}
}
private static RuntimeException createExceptionOnWrite(Object bean, Field field, Object value, Throwable rootCause) {
return new IllegalStateException("The class (" + bean.getClass() + ") has a field (" + field
+ ") which cannot be written with the value (" + value + ") to create a planning clone.", rootCause);
}
private FieldCloningUtils() {
// No external instances.
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner/PlanningCloneable.java | package ai.timefold.solver.core.impl.domain.solution.cloner;
import java.util.Collection;
import java.util.Map;
/**
* Used to construct new instances of an object when there is no suitable constructor.
* Used during planning cloning to create an "empty"/"blank" instance
* whose fields/items will be set to the planning clone of the original's fields/items.
* <p>
* This interface is internal.
* Do not use it in user code.
*
* @param <T> The type of object being cloned.
*/
public interface PlanningCloneable<T> {
/**
* Creates a new "empty"/"blank" instance.
* If the {@link PlanningCloneable} is a {@link Collection} or {@link Map},
* the returned instance should be empty and modifiable.
*
* @return never null, a new instance with the same type as the object being cloned.
*/
T createNewInstance();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner/PlanningImmutable.java | package ai.timefold.solver.core.impl.domain.solution.cloner;
/**
* This interface is used to mark an object as immutable.
* It will never be cloned, and multi-threaded solving will assume that it does not change.
* Using this interface together with @{@link PlanningCloneable} is not allowed and will throw exceptions;
* these two interfaces are polar opposites.
* <p>
* This interface is internal.
* Do not use it in user code.
*/
public interface PlanningImmutable {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner/ShallowCloningFieldCloner.java | package ai.timefold.solver.core.impl.domain.solution.cloner;
import java.lang.reflect.Field;
sealed interface ShallowCloningFieldCloner
permits ShallowCloningPrimitiveFieldCloner, ShallowCloningReferenceFieldCloner {
static ShallowCloningFieldCloner of(Field field) {
Class<?> fieldType = field.getType();
if (fieldType == boolean.class) {
return new ShallowCloningPrimitiveFieldCloner(field, FieldCloningUtils::copyBoolean);
} else if (fieldType == byte.class) {
return new ShallowCloningPrimitiveFieldCloner(field, FieldCloningUtils::copyByte);
} else if (fieldType == char.class) {
return new ShallowCloningPrimitiveFieldCloner(field, FieldCloningUtils::copyChar);
} else if (fieldType == short.class) {
return new ShallowCloningPrimitiveFieldCloner(field, FieldCloningUtils::copyShort);
} else if (fieldType == int.class) {
return new ShallowCloningPrimitiveFieldCloner(field, FieldCloningUtils::copyInt);
} else if (fieldType == long.class) {
return new ShallowCloningPrimitiveFieldCloner(field, FieldCloningUtils::copyLong);
} else if (fieldType == float.class) {
return new ShallowCloningPrimitiveFieldCloner(field, FieldCloningUtils::copyFloat);
} else if (fieldType == double.class) {
return new ShallowCloningPrimitiveFieldCloner(field, FieldCloningUtils::copyDouble);
} else {
return new ShallowCloningReferenceFieldCloner(field, FieldCloningUtils::copyObject);
}
}
<C> void clone(C original, C clone);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner/ShallowCloningPrimitiveFieldCloner.java | package ai.timefold.solver.core.impl.domain.solution.cloner;
import java.lang.reflect.Field;
import java.util.Objects;
import ai.timefold.solver.core.api.function.TriConsumer;
/**
* Copies values of primitive fields from one object to another.
* Unlike {@link ShallowCloningReferenceFieldCloner}, this does not use method handles,
* as we prefer to avoid boxing and unboxing of primitive types.
*/
final class ShallowCloningPrimitiveFieldCloner implements ShallowCloningFieldCloner {
private final Field field;
private final TriConsumer<Field, Object, Object> copyOperation;
ShallowCloningPrimitiveFieldCloner(Field field, TriConsumer<Field, Object, Object> copyOperation) {
field.setAccessible(true);
this.field = Objects.requireNonNull(field);
this.copyOperation = Objects.requireNonNull(copyOperation);
}
public <C> void clone(C original, C clone) {
copyOperation.accept(field, original, clone);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner/ShallowCloningReferenceFieldCloner.java | package ai.timefold.solver.core.impl.domain.solution.cloner;
import java.lang.reflect.Field;
import java.util.Objects;
import ai.timefold.solver.core.api.function.TriConsumer;
import ai.timefold.solver.core.impl.domain.common.accessor.FieldHandle;
/**
* Copies the reference value from a field of one object to another.
* Unlike {@link ShallowCloningPrimitiveFieldCloner},
* this uses method handles for improved performance of field access.
*/
final class ShallowCloningReferenceFieldCloner implements ShallowCloningFieldCloner {
private final FieldHandle fieldHandle;
private final TriConsumer<FieldHandle, Object, Object> copyOperation;
ShallowCloningReferenceFieldCloner(Field field, TriConsumer<FieldHandle, Object, Object> copyOperation) {
this.fieldHandle = FieldHandle.of(field);
this.copyOperation = Objects.requireNonNull(copyOperation);
}
public <C> void clone(C original, C clone) {
copyOperation.accept(fieldHandle, original, clone);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner/gizmo/GizmoCloningUtils.java | package ai.timefold.solver.core.impl.domain.solution.cloner.gizmo;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import ai.timefold.solver.core.impl.domain.solution.cloner.DeepCloningUtils;
import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningCloneable;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
public final class GizmoCloningUtils {
public static Set<Class<?>> getDeepClonedClasses(SolutionDescriptor<?> solutionDescriptor,
Collection<Class<?>> entitySubclasses) {
Set<Class<?>> deepClonedClassSet = new HashSet<>();
Set<Class<?>> classesToProcess = new LinkedHashSet<>(solutionDescriptor.getEntityClassSet());
classesToProcess.add(solutionDescriptor.getSolutionClass());
classesToProcess.addAll(entitySubclasses);
// deepClonedClassSet contains all processed classes so far,
// so we can use it to determine if we need to add a class
// to the classesToProcess set.
//
// This is important, since SolverConfig does not contain
// info on @DeepPlanningCloned classes, so we need to discover
// them from the domain classes, possibly recursively
// (when a @DeepPlanningCloned class reference another @DeepPlanningCloned
// that is not referenced by any entity).
while (!classesToProcess.isEmpty()) {
var clazz = classesToProcess.iterator().next();
classesToProcess.remove(clazz);
deepClonedClassSet.add(clazz);
for (Field field : getAllFields(clazz)) {
var deepClonedTypeArguments = getDeepClonedTypeArguments(solutionDescriptor, field.getGenericType());
for (var deepClonedTypeArgument : deepClonedTypeArguments) {
if (!deepClonedClassSet.contains(deepClonedTypeArgument)) {
classesToProcess.add(deepClonedTypeArgument);
deepClonedClassSet.add(deepClonedTypeArgument);
}
}
if (DeepCloningUtils.isFieldDeepCloned(solutionDescriptor, field, clazz)
&& !PlanningCloneable.class.isAssignableFrom(field.getType())
&& !deepClonedClassSet.contains(field.getType())) {
classesToProcess.add(field.getType());
deepClonedClassSet.add(field.getType());
}
}
}
return deepClonedClassSet;
}
/**
* @return never null
*/
private static Set<Class<?>> getDeepClonedTypeArguments(SolutionDescriptor<?> solutionDescriptor, Type genericType) {
// Check the generic type arguments of the field.
// It is possible for fields and methods, but not instances.
if (!(genericType instanceof ParameterizedType)) {
return Collections.emptySet();
}
Set<Class<?>> deepClonedTypeArguments = new HashSet<>();
ParameterizedType parameterizedType = (ParameterizedType) genericType;
for (Type actualTypeArgument : parameterizedType.getActualTypeArguments()) {
if (actualTypeArgument instanceof Class class1
&& DeepCloningUtils.isClassDeepCloned(solutionDescriptor, class1)) {
deepClonedTypeArguments.add(class1);
}
deepClonedTypeArguments.addAll(getDeepClonedTypeArguments(solutionDescriptor, actualTypeArgument));
}
return deepClonedTypeArguments;
}
private static List<Field> getAllFields(Class<?> baseClass) {
Class<?> clazz = baseClass;
Stream<Field> memberStream = Stream.empty();
while (clazz != null) {
Stream<Field> fieldStream = Stream.of(clazz.getDeclaredFields());
memberStream = Stream.concat(memberStream, fieldStream);
clazz = clazz.getSuperclass();
}
return memberStream.collect(Collectors.toList());
}
private GizmoCloningUtils() {
// No external instances.
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner/gizmo/GizmoSolutionCloner.java | package ai.timefold.solver.core.impl.domain.solution.cloner.gizmo;
import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
public interface GizmoSolutionCloner<Solution_> extends SolutionCloner<Solution_> {
void setSolutionDescriptor(SolutionDescriptor<Solution_> descriptor);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner/gizmo/GizmoSolutionClonerFactory.java | package ai.timefold.solver.core.impl.domain.solution.cloner.gizmo;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner;
import ai.timefold.solver.core.impl.domain.common.accessor.gizmo.GizmoClassLoader;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
public final class GizmoSolutionClonerFactory {
/**
* Returns the generated class name for a given solutionDescriptor.
* (Here as accessing any method of GizmoMemberAccessorImplementor
* will try to load Gizmo code)
*
* @param solutionDescriptor The solutionDescriptor to get the generated class name for
* @return The generated class name for solutionDescriptor
*/
public static String getGeneratedClassName(SolutionDescriptor<?> solutionDescriptor) {
return solutionDescriptor.getSolutionClass().getName() + "$Timefold$SolutionCloner";
}
public static <T> SolutionCloner<T> build(SolutionDescriptor<T> solutionDescriptor, GizmoClassLoader gizmoClassLoader) {
try {
// Check if Gizmo on the classpath by verifying we can access one of its classes
Class.forName("io.quarkus.gizmo.ClassCreator", false, Thread.currentThread().getContextClassLoader());
} catch (ClassNotFoundException e) {
throw new IllegalStateException("When using the domainAccessType (" +
DomainAccessType.GIZMO +
") the classpath or modulepath must contain io.quarkus.gizmo:gizmo.\n" +
"Maybe add a dependency to io.quarkus.gizmo:gizmo.");
}
return new GizmoSolutionClonerImplementor().createClonerFor(solutionDescriptor,
gizmoClassLoader);
}
// ************************************************************************
// Private constructor
// ************************************************************************
private GizmoSolutionClonerFactory() {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner/gizmo/GizmoSolutionClonerImplementor.java | package ai.timefold.solver.core.impl.domain.solution.cloner.gizmo;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner;
import ai.timefold.solver.core.impl.domain.common.accessor.gizmo.GizmoClassLoader;
import ai.timefold.solver.core.impl.domain.common.accessor.gizmo.GizmoMemberDescriptor;
import ai.timefold.solver.core.impl.domain.solution.cloner.DeepCloningUtils;
import ai.timefold.solver.core.impl.domain.solution.cloner.FieldAccessingSolutionCloner;
import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningCloneable;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.util.MutableReference;
import io.quarkus.gizmo.AssignableResultHandle;
import io.quarkus.gizmo.BranchResult;
import io.quarkus.gizmo.BytecodeCreator;
import io.quarkus.gizmo.ClassCreator;
import io.quarkus.gizmo.ClassOutput;
import io.quarkus.gizmo.FieldDescriptor;
import io.quarkus.gizmo.MethodCreator;
import io.quarkus.gizmo.MethodDescriptor;
import io.quarkus.gizmo.ResultHandle;
public class GizmoSolutionClonerImplementor {
private static final MethodDescriptor EQUALS_METHOD = MethodDescriptor.ofMethod(Object.class, "equals", boolean.class,
Object.class);
protected static final MethodDescriptor GET_METHOD = MethodDescriptor.ofMethod(Map.class, "get", Object.class,
Object.class);
private static final MethodDescriptor PUT_METHOD = MethodDescriptor.ofMethod(Map.class, "put", Object.class,
Object.class, Object.class);
private static final String FALLBACK_CLONER = "fallbackCloner";
public static final boolean DEBUG = false;
/**
* Return a comparator that sorts classes into instanceof check order.
* In particular, if x is a subclass of y, then x will appear earlier
* than y in the list.
*
* @param deepClonedClassSet The set of classes to generate a comparator for
* @return A comparator that sorts classes from deepClonedClassSet such that
* x < y if x is assignable from y.
*/
public static Comparator<Class<?>> getInstanceOfComparator(Set<Class<?>> deepClonedClassSet) {
Map<Class<?>, Integer> classToSubclassLevel = new HashMap<>();
deepClonedClassSet
.forEach(clazz -> {
if (deepClonedClassSet.stream()
.allMatch(
otherClazz -> clazz.isAssignableFrom(otherClazz) || !otherClazz.isAssignableFrom(clazz))) {
classToSubclassLevel.put(clazz, 0);
}
});
boolean isChanged = true;
while (isChanged) {
// Need to iterate over all classes
// since maxSubclassLevel can change
// (for instance, Tiger extends Cat (1) implements Animal (0))
isChanged = false;
for (Class<?> clazz : deepClonedClassSet) {
Optional<Integer> maxParentSubclassLevel = classToSubclassLevel.keySet().stream()
.filter(otherClazz -> otherClazz != clazz && otherClazz.isAssignableFrom(clazz))
.map(classToSubclassLevel::get)
.max(Integer::compare);
if (maxParentSubclassLevel.isPresent()) {
Integer oldVal = classToSubclassLevel.getOrDefault(clazz, -1);
Integer newVal = maxParentSubclassLevel.get() + 1;
if (newVal.compareTo(oldVal) > 0) {
isChanged = true;
classToSubclassLevel.put(clazz, newVal);
}
}
}
}
return Comparator.<Class<?>, Integer> comparing(classToSubclassLevel::get)
.thenComparing(Class::getName).reversed();
}
protected void createFields(ClassCreator classCreator) {
classCreator.getFieldCreator(FALLBACK_CLONER, FieldAccessingSolutionCloner.class)
.setModifiers(Modifier.PRIVATE | Modifier.STATIC);
}
/**
* Generates the constructor and implementations of SolutionCloner methods for the given SolutionDescriptor using the given
* ClassCreator
*/
public static void defineClonerFor(ClassCreator classCreator,
SolutionDescriptor<?> solutionDescriptor,
Set<Class<?>> solutionClassSet,
Map<Class<?>, GizmoSolutionOrEntityDescriptor> memoizedSolutionOrEntityDescriptorMap,
Set<Class<?>> deepClonedClassSet) {
defineClonerFor(GizmoSolutionClonerImplementor::new, classCreator, solutionDescriptor, solutionClassSet,
memoizedSolutionOrEntityDescriptorMap, deepClonedClassSet);
}
public static boolean isCloneableClass(Class<?> clazz) {
return !clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers());
}
/**
* Generates the constructor and implementations of SolutionCloner
* methods for the given SolutionDescriptor using the given ClassCreator
*/
public static void defineClonerFor(Supplier<GizmoSolutionClonerImplementor> implementorSupplier,
ClassCreator classCreator,
SolutionDescriptor<?> solutionDescriptor,
Set<Class<?>> solutionClassSet,
Map<Class<?>, GizmoSolutionOrEntityDescriptor> memoizedSolutionOrEntityDescriptorMap,
Set<Class<?>> deepClonedClassSet) {
GizmoSolutionClonerImplementor implementor = implementorSupplier.get();
// Classes that are not instances of any other class in the collection
// have a subclass level of 0.
// Other classes subclass level is the maximum of the subclass level
// of the classes it is a subclass of + 1
Set<Class<?>> deepCloneClassesThatAreNotSolutionSet =
deepClonedClassSet.stream()
.filter(clazz -> !solutionClassSet.contains(clazz) && !clazz.isArray())
.filter(GizmoSolutionClonerImplementor::isCloneableClass)
.collect(Collectors.toSet());
Comparator<Class<?>> instanceOfComparator = getInstanceOfComparator(deepClonedClassSet);
SortedSet<Class<?>> deepCloneClassesThatAreNotSolutionSortedSet = new TreeSet<>(instanceOfComparator);
deepCloneClassesThatAreNotSolutionSortedSet.addAll(deepCloneClassesThatAreNotSolutionSet);
implementor.createFields(classCreator);
implementor.createConstructor(classCreator);
implementor.createSetSolutionDescriptor(classCreator, solutionDescriptor);
implementor.createCloneSolution(classCreator, solutionDescriptor);
implementor.createCloneSolutionRun(classCreator, solutionDescriptor, solutionClassSet,
memoizedSolutionOrEntityDescriptorMap,
deepCloneClassesThatAreNotSolutionSortedSet, instanceOfComparator);
for (Class<?> deepClonedClass : deepCloneClassesThatAreNotSolutionSortedSet) {
implementor.createDeepCloneHelperMethod(classCreator, deepClonedClass, solutionDescriptor,
memoizedSolutionOrEntityDescriptorMap,
deepCloneClassesThatAreNotSolutionSortedSet);
}
Set<Class<?>> abstractDeepCloneClassSet =
deepClonedClassSet.stream()
.filter(clazz -> !solutionClassSet.contains(clazz) && !clazz.isArray())
.filter(Predicate.not(GizmoSolutionClonerImplementor::isCloneableClass))
.collect(Collectors.toSet());
for (Class<?> abstractDeepClonedClass : abstractDeepCloneClassSet) {
implementor.createAbstractDeepCloneHelperMethod(classCreator, abstractDeepClonedClass, solutionDescriptor,
memoizedSolutionOrEntityDescriptorMap,
deepCloneClassesThatAreNotSolutionSortedSet);
}
}
public static ClassOutput createClassOutputWithDebuggingCapability(MutableReference<byte[]> classBytecodeHolder) {
return (path, byteCode) -> {
classBytecodeHolder.setValue(byteCode);
if (DEBUG) {
Path debugRoot = Paths.get("target/timefold-solver-generated-classes");
Path rest = Paths.get(path + ".class");
Path destination = debugRoot.resolve(rest);
try {
Files.createDirectories(destination.getParent());
Files.write(destination, byteCode);
} catch (IOException e) {
throw new IllegalStateException("Fail to write debug class file " + destination + ".", e);
}
}
};
}
static <T> SolutionCloner<T> createClonerFor(SolutionDescriptor<T> solutionDescriptor,
GizmoClassLoader gizmoClassLoader) {
GizmoSolutionClonerImplementor implementor = new GizmoSolutionClonerImplementor();
String className = GizmoSolutionClonerFactory.getGeneratedClassName(solutionDescriptor);
if (gizmoClassLoader.hasBytecodeFor(className)) {
return implementor.createInstance(className, gizmoClassLoader, solutionDescriptor);
}
MutableReference<byte[]> classBytecodeHolder = new MutableReference<>(null);
ClassCreator classCreator = ClassCreator.builder()
.className(className)
.interfaces(GizmoSolutionCloner.class)
.superClass(Object.class)
.classOutput(createClassOutputWithDebuggingCapability(classBytecodeHolder))
.setFinal(true)
.build();
Set<Class<?>> deepClonedClassSet = GizmoCloningUtils.getDeepClonedClasses(solutionDescriptor, Collections.emptyList());
defineClonerFor(() -> implementor, classCreator, solutionDescriptor,
Collections.singleton(solutionDescriptor.getSolutionClass()),
new HashMap<>(), deepClonedClassSet);
classCreator.close();
byte[] classBytecode = classBytecodeHolder.getValue();
gizmoClassLoader.storeBytecode(className, classBytecode);
return implementor.createInstance(className, gizmoClassLoader, solutionDescriptor);
}
private <T> SolutionCloner<T> createInstance(String className, ClassLoader gizmoClassLoader,
SolutionDescriptor<T> solutionDescriptor) {
try {
@SuppressWarnings("unchecked")
Class<? extends GizmoSolutionCloner<T>> outClass =
(Class<? extends GizmoSolutionCloner<T>>) gizmoClassLoader.loadClass(className);
GizmoSolutionCloner<T> out = outClass.getConstructor().newInstance();
out.setSolutionDescriptor(solutionDescriptor);
return out;
} catch (InvocationTargetException | InstantiationException | IllegalAccessException | ClassNotFoundException
| NoSuchMethodException e) {
throw new IllegalStateException(e);
}
}
private void createConstructor(ClassCreator classCreator) {
MethodCreator methodCreator = classCreator.getMethodCreator(
MethodDescriptor.ofConstructor(classCreator.getClassName()));
ResultHandle thisObj = methodCreator.getThis();
// Invoke Object's constructor
methodCreator.invokeSpecialMethod(MethodDescriptor.ofConstructor(Object.class), thisObj);
// Return this (it a constructor)
methodCreator.returnValue(thisObj);
}
protected void createSetSolutionDescriptor(ClassCreator classCreator, SolutionDescriptor<?> solutionDescriptor) {
MethodCreator methodCreator = classCreator.getMethodCreator(
MethodDescriptor.ofMethod(GizmoSolutionCloner.class, "setSolutionDescriptor", void.class,
SolutionDescriptor.class));
methodCreator.writeStaticField(FieldDescriptor.of(
GizmoSolutionClonerFactory.getGeneratedClassName(solutionDescriptor),
FALLBACK_CLONER, FieldAccessingSolutionCloner.class),
methodCreator.newInstance(
MethodDescriptor.ofConstructor(FieldAccessingSolutionCloner.class, SolutionDescriptor.class),
methodCreator.getMethodParam(0)));
methodCreator.returnValue(null);
}
private void createCloneSolution(ClassCreator classCreator, SolutionDescriptor<?> solutionDescriptor) {
Class<?> solutionClass = solutionDescriptor.getSolutionClass();
MethodCreator methodCreator =
classCreator.getMethodCreator(MethodDescriptor.ofMethod(SolutionCloner.class,
"cloneSolution",
Object.class,
Object.class));
ResultHandle thisObj = methodCreator.getMethodParam(0);
ResultHandle clone = methodCreator.invokeStaticMethod(
MethodDescriptor.ofMethod(
GizmoSolutionClonerFactory.getGeneratedClassName(solutionDescriptor),
"cloneSolutionRun", solutionClass, solutionClass, Map.class),
thisObj,
methodCreator.newInstance(MethodDescriptor.ofConstructor(IdentityHashMap.class)));
methodCreator.returnValue(clone);
}
private void createCloneSolutionRun(ClassCreator classCreator, SolutionDescriptor<?> solutionDescriptor,
Set<Class<?>> solutionClassSet,
Map<Class<?>, GizmoSolutionOrEntityDescriptor> memoizedSolutionOrEntityDescriptorMap,
SortedSet<Class<?>> deepClonedClassesSortedSet, Comparator<Class<?>> instanceOfComparator) {
Class<?> solutionClass = solutionDescriptor.getSolutionClass();
MethodCreator methodCreator =
classCreator.getMethodCreator("cloneSolutionRun", solutionClass, solutionClass, Map.class);
methodCreator.setModifiers(Modifier.STATIC | Modifier.PRIVATE);
ResultHandle thisObj = methodCreator.getMethodParam(0);
BranchResult solutionNullBranchResult = methodCreator.ifNull(thisObj);
BytecodeCreator solutionIsNullBranch = solutionNullBranchResult.trueBranch();
solutionIsNullBranch.returnValue(thisObj); // thisObj is null
BytecodeCreator solutionIsNotNullBranch = solutionNullBranchResult.falseBranch();
ResultHandle createdCloneMap = methodCreator.getMethodParam(1);
ResultHandle maybeClone = solutionIsNotNullBranch.invokeInterfaceMethod(
GET_METHOD, createdCloneMap, thisObj);
BranchResult hasCloneBranchResult = solutionIsNotNullBranch.ifNotNull(maybeClone);
BytecodeCreator hasCloneBranch = hasCloneBranchResult.trueBranch();
hasCloneBranch.returnValue(maybeClone);
BytecodeCreator noCloneBranch = hasCloneBranchResult.falseBranch();
List<Class<?>> sortedSolutionClassList = new ArrayList<>(solutionClassSet);
sortedSolutionClassList.sort(instanceOfComparator);
BytecodeCreator currentBranch = noCloneBranch;
ResultHandle thisObjClass =
currentBranch.invokeVirtualMethod(MethodDescriptor.ofMethod(Object.class, "getClass", Class.class), thisObj);
for (Class<?> solutionSubclass : sortedSolutionClassList) {
ResultHandle solutionSubclassResultHandle = currentBranch.loadClass(solutionSubclass);
ResultHandle isSubclass =
currentBranch.invokeVirtualMethod(EQUALS_METHOD, solutionSubclassResultHandle, thisObjClass);
BranchResult isSubclassBranchResult = currentBranch.ifTrue(isSubclass);
BytecodeCreator isSubclassBranch = isSubclassBranchResult.trueBranch();
GizmoSolutionOrEntityDescriptor solutionSubclassDescriptor =
memoizedSolutionOrEntityDescriptorMap.computeIfAbsent(solutionSubclass,
key -> new GizmoSolutionOrEntityDescriptor(solutionDescriptor, solutionSubclass));
ResultHandle clone;
if (PlanningCloneable.class.isAssignableFrom(solutionSubclass)) {
clone = isSubclassBranch.invokeInterfaceMethod(
MethodDescriptor.ofMethod(PlanningCloneable.class, "createNewInstance", Object.class),
thisObj);
clone = isSubclassBranch.checkCast(clone, solutionSubclass);
} else {
clone = isSubclassBranch.newInstance(MethodDescriptor.ofConstructor(solutionSubclass));
}
isSubclassBranch.invokeInterfaceMethod(
MethodDescriptor.ofMethod(Map.class, "put", Object.class, Object.class, Object.class),
createdCloneMap, thisObj, clone);
for (GizmoMemberDescriptor shallowlyClonedField : solutionSubclassDescriptor.getShallowClonedMemberDescriptors()) {
writeShallowCloneInstructions(solutionSubclassDescriptor, isSubclassBranch, shallowlyClonedField, thisObj,
clone, createdCloneMap, deepClonedClassesSortedSet);
}
for (Field deeplyClonedField : solutionSubclassDescriptor.getDeepClonedFields()) {
GizmoMemberDescriptor gizmoMemberDescriptor =
solutionSubclassDescriptor.getMemberDescriptorForField(deeplyClonedField);
ResultHandle fieldValue = gizmoMemberDescriptor.readMemberValue(isSubclassBranch, thisObj);
AssignableResultHandle cloneValue = isSubclassBranch.createVariable(deeplyClonedField.getType());
writeDeepCloneInstructions(isSubclassBranch, solutionSubclassDescriptor, deeplyClonedField,
gizmoMemberDescriptor, fieldValue, cloneValue, createdCloneMap, deepClonedClassesSortedSet);
if (!gizmoMemberDescriptor.writeMemberValue(isSubclassBranch, clone, cloneValue)) {
throw new IllegalStateException("The member (" + gizmoMemberDescriptor.getName() + ") of class (" +
gizmoMemberDescriptor.getDeclaringClassName() +
") does not have a setter.");
}
}
isSubclassBranch.returnValue(clone);
currentBranch = isSubclassBranchResult.falseBranch();
}
ResultHandle errorBuilder = currentBranch.newInstance(MethodDescriptor.ofConstructor(StringBuilder.class, String.class),
currentBranch.load("Failed to create clone: encountered ("));
final MethodDescriptor APPEND =
MethodDescriptor.ofMethod(StringBuilder.class, "append", StringBuilder.class, Object.class);
currentBranch.invokeVirtualMethod(APPEND, errorBuilder, thisObjClass);
currentBranch.invokeVirtualMethod(APPEND, errorBuilder, currentBranch.load(") which is not a known subclass of " +
"the solution class (" + solutionDescriptor.getSolutionClass() + "). The known subclasses are " +
solutionClassSet.stream().map(Class::getName).collect(Collectors.joining(", ", "[", "]")) + "." +
"\nMaybe use DomainAccessType.REFLECTION?"));
ResultHandle errorMsg = currentBranch
.invokeVirtualMethod(MethodDescriptor.ofMethod(Object.class, "toString", String.class), errorBuilder);
ResultHandle error = currentBranch
.newInstance(MethodDescriptor.ofConstructor(IllegalArgumentException.class, String.class), errorMsg);
currentBranch.throwException(error);
}
/**
* Writes the following code:
*
* <pre>
* // If getter a field
* clone.member = original.member
* // If getter a method (i.e. Quarkus)
* clone.setMember(original.getMember());
* </pre>
*
* @param methodCreator
* @param shallowlyClonedField
* @param thisObj
* @param clone
*/
private void writeShallowCloneInstructions(GizmoSolutionOrEntityDescriptor solutionInfo,
BytecodeCreator methodCreator, GizmoMemberDescriptor shallowlyClonedField,
ResultHandle thisObj, ResultHandle clone, ResultHandle createdCloneMap,
SortedSet<Class<?>> deepClonedClassesSortedSet) {
try {
boolean isArray = shallowlyClonedField.getTypeName().endsWith("[]");
Class<?> type = null;
if (shallowlyClonedField.getType() instanceof Class) {
type = (Class<?>) shallowlyClonedField.getType();
}
List<Class<?>> entitySubclasses = Collections.emptyList();
if (type == null && !isArray) {
type = Class.forName(shallowlyClonedField.getTypeName().replace('/', '.'), false,
Thread.currentThread().getContextClassLoader());
}
if (type != null && !isArray) {
entitySubclasses =
deepClonedClassesSortedSet.stream().filter(type::isAssignableFrom).toList();
}
ResultHandle fieldValue = shallowlyClonedField.readMemberValue(methodCreator, thisObj);
if (!entitySubclasses.isEmpty()) {
AssignableResultHandle cloneResultHolder = methodCreator.createVariable(type);
writeDeepCloneEntityOrFactInstructions(methodCreator, solutionInfo, type,
fieldValue, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet,
UnhandledCloneType.SHALLOW);
fieldValue = cloneResultHolder;
}
if (!shallowlyClonedField.writeMemberValue(methodCreator, clone, fieldValue)) {
throw new IllegalStateException("Field (" + shallowlyClonedField.getName() + ") of class (" +
shallowlyClonedField.getDeclaringClassName() +
") does not have a setter.");
}
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Error creating Gizmo Solution Cloner", e);
}
}
/**
* @see #writeDeepCloneInstructions(BytecodeCreator, GizmoSolutionOrEntityDescriptor, Class, Type, ResultHandle,
* AssignableResultHandle, ResultHandle, SortedSet)
*/
private void writeDeepCloneInstructions(BytecodeCreator bytecodeCreator,
GizmoSolutionOrEntityDescriptor solutionDescriptor, Field deeplyClonedField,
GizmoMemberDescriptor gizmoMemberDescriptor, ResultHandle toClone, AssignableResultHandle cloneResultHolder,
ResultHandle createdCloneMap, SortedSet<Class<?>> deepClonedClassesSortedSet) {
BranchResult isNull = bytecodeCreator.ifNull(toClone);
BytecodeCreator isNullBranch = isNull.trueBranch();
isNullBranch.assign(cloneResultHolder, isNullBranch.loadNull());
BytecodeCreator isNotNullBranch = isNull.falseBranch();
Class<?> deeplyClonedFieldClass = deeplyClonedField.getType();
Type type = gizmoMemberDescriptor.getType();
if (solutionDescriptor.getSolutionDescriptor().getSolutionClass().isAssignableFrom(deeplyClonedFieldClass)) {
writeDeepCloneSolutionInstructions(bytecodeCreator, solutionDescriptor, toClone, cloneResultHolder,
createdCloneMap);
} else if (Collection.class.isAssignableFrom(deeplyClonedFieldClass)) {
writeDeepCloneCollectionInstructions(isNotNullBranch, solutionDescriptor, deeplyClonedFieldClass, type,
toClone, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet);
} else if (Map.class.isAssignableFrom(deeplyClonedFieldClass)) {
writeDeepCloneMapInstructions(isNotNullBranch, solutionDescriptor, deeplyClonedFieldClass, type,
toClone, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet);
} else if (deeplyClonedFieldClass.isArray()) {
writeDeepCloneArrayInstructions(isNotNullBranch, solutionDescriptor, deeplyClonedFieldClass,
toClone, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet);
} else {
UnhandledCloneType unknownClassCloneType =
(DeepCloningUtils.isFieldDeepCloned(solutionDescriptor.solutionDescriptor,
deeplyClonedField, deeplyClonedField.getDeclaringClass()))
? UnhandledCloneType.DEEP
: UnhandledCloneType.SHALLOW;
writeDeepCloneEntityOrFactInstructions(isNotNullBranch, solutionDescriptor, deeplyClonedFieldClass,
toClone, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet, unknownClassCloneType);
}
}
/**
* Writes the following code:
*
* <pre>
* // For a Collection
* Collection original = field;
* Collection clone = new ActualCollectionType();
* Iterator iterator = original.iterator();
* while (iterator.hasNext()) {
* Object nextClone = (result from recursion on iterator.next());
* clone.add(nextClone);
* }
*
* // For a Map
* Map original = field;
* Map clone = new ActualMapType();
* Iterator iterator = original.entrySet().iterator();
* while (iterator.hasNext()) {
* Entry next = iterator.next();
* nextClone = (result from recursion on next.getValue());
* clone.put(next.getKey(), nextClone);
* }
*
* // For an array
* Object[] original = field;
* Object[] clone = new Object[original.length];
*
* for (int i = 0; i < original.length; i++) {
* clone[i] = (result from recursion on original[i]);
* }
*
* // For an entity
* if (original instanceof SubclassOfEntity1) {
* SubclassOfEntity1 original = field;
* SubclassOfEntity1 clone = new SubclassOfEntity1();
*
* // shallowly clone fields using writeShallowCloneInstructions()
* // for any deeply cloned field, do recursion on it
* } else if (original instanceof SubclassOfEntity2) {
* // ...
* }
* </pre>
*
* @param bytecodeCreator
* @param solutionDescriptor
* @param deeplyClonedFieldClass
* @param type
* @param toClone
* @param cloneResultHolder
*/
private void writeDeepCloneInstructions(BytecodeCreator bytecodeCreator,
GizmoSolutionOrEntityDescriptor solutionDescriptor,
Class<?> deeplyClonedFieldClass, java.lang.reflect.Type type, ResultHandle toClone,
AssignableResultHandle cloneResultHolder, ResultHandle createdCloneMap,
SortedSet<Class<?>> deepClonedClassesSortedSet) {
BranchResult isNull = bytecodeCreator.ifNull(toClone);
BytecodeCreator isNullBranch = isNull.trueBranch();
isNullBranch.assign(cloneResultHolder, isNullBranch.loadNull());
BytecodeCreator isNotNullBranch = isNull.falseBranch();
if (solutionDescriptor.getSolutionDescriptor().getSolutionClass().isAssignableFrom(deeplyClonedFieldClass)) {
writeDeepCloneSolutionInstructions(bytecodeCreator, solutionDescriptor, toClone, cloneResultHolder,
createdCloneMap);
} else if (Collection.class.isAssignableFrom(deeplyClonedFieldClass)) {
// Clone collection
writeDeepCloneCollectionInstructions(isNotNullBranch, solutionDescriptor, deeplyClonedFieldClass, type,
toClone, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet);
} else if (Map.class.isAssignableFrom(deeplyClonedFieldClass)) {
// Clone map
writeDeepCloneMapInstructions(isNotNullBranch, solutionDescriptor, deeplyClonedFieldClass, type,
toClone, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet);
} else if (deeplyClonedFieldClass.isArray()) {
// Clone array
writeDeepCloneArrayInstructions(isNotNullBranch, solutionDescriptor, deeplyClonedFieldClass,
toClone, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet);
} else {
// Clone entity
UnhandledCloneType unknownClassCloneType =
(DeepCloningUtils.isClassDeepCloned(solutionDescriptor.solutionDescriptor, deeplyClonedFieldClass))
? UnhandledCloneType.DEEP
: UnhandledCloneType.SHALLOW;
writeDeepCloneEntityOrFactInstructions(isNotNullBranch, solutionDescriptor, deeplyClonedFieldClass,
toClone, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet, unknownClassCloneType);
}
}
private void writeDeepCloneSolutionInstructions(BytecodeCreator bytecodeCreator,
GizmoSolutionOrEntityDescriptor solutionDescriptor, ResultHandle toClone, AssignableResultHandle cloneResultHolder,
ResultHandle createdCloneMap) {
BranchResult isNull = bytecodeCreator.ifNull(toClone);
BytecodeCreator isNullBranch = isNull.trueBranch();
isNullBranch.assign(cloneResultHolder, isNullBranch.loadNull());
BytecodeCreator isNotNullBranch = isNull.falseBranch();
ResultHandle clone = isNotNullBranch.invokeStaticMethod(
MethodDescriptor.ofMethod(
GizmoSolutionClonerFactory.getGeneratedClassName(solutionDescriptor.getSolutionDescriptor()),
"cloneSolutionRun", solutionDescriptor.getSolutionDescriptor().getSolutionClass(),
solutionDescriptor.getSolutionDescriptor().getSolutionClass(), Map.class),
toClone,
createdCloneMap);
isNotNullBranch.assign(cloneResultHolder, clone);
}
/**
* Writes the following code:
*
* <pre>
* // For a Collection
* Collection clone = new ActualCollectionType();
* Iterator iterator = toClone.iterator();
* while (iterator.hasNext()) {
* Object toCloneElement = iterator.next();
* Object nextClone = (result from recursion on toCloneElement);
* clone.add(nextClone);
* }
* cloneResultHolder = clone;
* </pre>
**/
private void writeDeepCloneCollectionInstructions(BytecodeCreator bytecodeCreator,
GizmoSolutionOrEntityDescriptor solutionDescriptor,
Class<?> deeplyClonedFieldClass, java.lang.reflect.Type type, ResultHandle toClone,
AssignableResultHandle cloneResultHolder, ResultHandle createdCloneMap,
SortedSet<Class<?>> deepClonedClassesSortedSet) {
// Clone collection
AssignableResultHandle cloneCollection = bytecodeCreator.createVariable(deeplyClonedFieldClass);
ResultHandle size = bytecodeCreator
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Collection.class, "size", int.class), toClone);
if (PlanningCloneable.class.isAssignableFrom(deeplyClonedFieldClass)) {
var emptyInstance = bytecodeCreator
.invokeInterfaceMethod(MethodDescriptor.ofMethod(PlanningCloneable.class, "createNewInstance",
Object.class), bytecodeCreator.checkCast(toClone, PlanningCloneable.class));
bytecodeCreator.assign(cloneCollection,
bytecodeCreator.checkCast(emptyInstance,
Collection.class));
} else if (List.class.isAssignableFrom(deeplyClonedFieldClass)) {
bytecodeCreator.assign(cloneCollection,
bytecodeCreator.newInstance(MethodDescriptor.ofConstructor(ArrayList.class, int.class), size));
} else if (Set.class.isAssignableFrom(deeplyClonedFieldClass)) {
ResultHandle isSortedSet = bytecodeCreator.instanceOf(toClone, SortedSet.class);
BranchResult isSortedSetBranchResult = bytecodeCreator.ifTrue(isSortedSet);
BytecodeCreator isSortedSetBranch = isSortedSetBranchResult.trueBranch();
ResultHandle setComparator = isSortedSetBranch
.invokeInterfaceMethod(MethodDescriptor.ofMethod(SortedSet.class,
"comparator", Comparator.class), toClone);
isSortedSetBranch.assign(cloneCollection,
isSortedSetBranch.newInstance(MethodDescriptor.ofConstructor(TreeSet.class, Comparator.class),
setComparator));
BytecodeCreator isNotSortedSetBranch = isSortedSetBranchResult.falseBranch();
isNotSortedSetBranch.assign(cloneCollection,
isNotSortedSetBranch.newInstance(MethodDescriptor.ofConstructor(LinkedHashSet.class, int.class), size));
} else {
// field is probably of type collection
ResultHandle isSet = bytecodeCreator.instanceOf(toClone, Set.class);
BranchResult isSetBranchResult = bytecodeCreator.ifTrue(isSet);
BytecodeCreator isSetBranch = isSetBranchResult.trueBranch();
ResultHandle isSortedSet = isSetBranch.instanceOf(toClone, SortedSet.class);
BranchResult isSortedSetBranchResult = isSetBranch.ifTrue(isSortedSet);
BytecodeCreator isSortedSetBranch = isSortedSetBranchResult.trueBranch();
ResultHandle setComparator = isSortedSetBranch
.invokeInterfaceMethod(MethodDescriptor.ofMethod(SortedSet.class,
"comparator", Comparator.class), toClone);
isSortedSetBranch.assign(cloneCollection,
isSortedSetBranch.newInstance(MethodDescriptor.ofConstructor(TreeSet.class, Comparator.class),
setComparator));
BytecodeCreator isNotSortedSetBranch = isSortedSetBranchResult.falseBranch();
isNotSortedSetBranch.assign(cloneCollection,
isNotSortedSetBranch.newInstance(MethodDescriptor.ofConstructor(LinkedHashSet.class, int.class), size));
// Default to ArrayList
BytecodeCreator isNotSetBranch = isSetBranchResult.falseBranch();
isNotSetBranch.assign(cloneCollection,
isNotSetBranch.newInstance(MethodDescriptor.ofConstructor(ArrayList.class, int.class), size));
}
ResultHandle iterator = bytecodeCreator
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Iterable.class, "iterator", Iterator.class), toClone);
BytecodeCreator whileLoopBlock = bytecodeCreator.whileLoop(conditionBytecode -> {
ResultHandle hasNext = conditionBytecode
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Iterator.class, "hasNext", boolean.class), iterator);
return conditionBytecode.ifTrue(hasNext);
}).block();
Class<?> elementClass;
java.lang.reflect.Type elementClassType;
if (type instanceof ParameterizedType parameterizedType) {
// Assume Collection follow Collection<T> convention of first type argument = element class
elementClassType = parameterizedType.getActualTypeArguments()[0];
if (elementClassType instanceof Class<?> class1) {
elementClass = class1;
} else if (elementClassType instanceof ParameterizedType parameterizedElementClassType) {
elementClass = (Class<?>) parameterizedElementClassType.getRawType();
} else if (elementClassType instanceof WildcardType wildcardType) {
elementClass = (Class<?>) wildcardType.getUpperBounds()[0];
} else {
throw new IllegalStateException("Unhandled type " + elementClassType + ".");
}
} else {
throw new IllegalStateException("Cannot infer element type for Collection type (" + type + ").");
}
// Odd case of member get and set being on different classes; will work as we only
// use get on the original and set on the clone.
ResultHandle next =
whileLoopBlock.invokeInterfaceMethod(MethodDescriptor.ofMethod(Iterator.class, "next", Object.class), iterator);
final AssignableResultHandle clonedElement = whileLoopBlock.createVariable(elementClass);
writeDeepCloneInstructions(whileLoopBlock, solutionDescriptor,
elementClass, elementClassType, next, clonedElement, createdCloneMap, deepClonedClassesSortedSet);
whileLoopBlock.invokeInterfaceMethod(MethodDescriptor.ofMethod(Collection.class, "add", boolean.class, Object.class),
cloneCollection,
clonedElement);
bytecodeCreator.assign(cloneResultHolder, cloneCollection);
}
/**
* Writes the following code:
*
* <pre>
* // For a Map
* Map clone = new ActualMapType();
* Iterator iterator = toClone.entrySet().iterator();
* while (iterator.hasNext()) {
* Entry next = iterator.next();
* Object toCloneValue = next.getValue();
* nextClone = (result from recursion on toCloneValue);
* clone.put(next.getKey(), nextClone);
* }
* cloneResultHolder = clone;
* </pre>
**/
private void writeDeepCloneMapInstructions(BytecodeCreator bytecodeCreator,
GizmoSolutionOrEntityDescriptor solutionDescriptor,
Class<?> deeplyClonedFieldClass, java.lang.reflect.Type type, ResultHandle toClone,
AssignableResultHandle cloneResultHolder, ResultHandle createdCloneMap,
SortedSet<Class<?>> deepClonedClassesSortedSet) {
ResultHandle cloneMap;
if (PlanningCloneable.class.isAssignableFrom(deeplyClonedFieldClass)) {
var emptyInstance = bytecodeCreator
.invokeInterfaceMethod(MethodDescriptor.ofMethod(PlanningCloneable.class, "createNewInstance",
Object.class), bytecodeCreator.checkCast(toClone, PlanningCloneable.class));
cloneMap = bytecodeCreator.checkCast(emptyInstance, Map.class);
} else {
Class<?> holderClass = deeplyClonedFieldClass;
try {
holderClass.getConstructor();
} catch (NoSuchMethodException e) {
if (LinkedHashMap.class.isAssignableFrom(holderClass)) {
holderClass = LinkedHashMap.class;
} else if (ConcurrentHashMap.class.isAssignableFrom(holderClass)) {
holderClass = ConcurrentHashMap.class;
} else {
// Default to LinkedHashMap
holderClass = LinkedHashMap.class;
}
}
ResultHandle size =
bytecodeCreator.invokeInterfaceMethod(MethodDescriptor.ofMethod(Map.class, "size", int.class), toClone);
try {
holderClass.getConstructor(int.class);
cloneMap = bytecodeCreator.newInstance(MethodDescriptor.ofConstructor(holderClass, int.class), size);
} catch (NoSuchMethodException e) {
cloneMap = bytecodeCreator.newInstance(MethodDescriptor.ofConstructor(holderClass));
}
}
ResultHandle entrySet = bytecodeCreator
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Map.class, "entrySet", Set.class), toClone);
ResultHandle iterator = bytecodeCreator
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Iterable.class, "iterator", Iterator.class), entrySet);
BytecodeCreator whileLoopBlock = bytecodeCreator.whileLoop(conditionBytecode -> {
ResultHandle hasNext = conditionBytecode
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Iterator.class, "hasNext", boolean.class), iterator);
return conditionBytecode.ifTrue(hasNext);
}).block();
Class<?> keyClass;
Class<?> elementClass;
java.lang.reflect.Type keyType;
java.lang.reflect.Type elementClassType;
if (type instanceof ParameterizedType parameterizedType) {
// Assume Map follow Map<K,V> convention of second type argument = value class
keyType = parameterizedType.getActualTypeArguments()[0];
elementClassType = parameterizedType.getActualTypeArguments()[1];
if (elementClassType instanceof Class<?> class1) {
elementClass = class1;
} else if (elementClassType instanceof ParameterizedType parameterizedElementClassType) {
elementClass = (Class<?>) parameterizedElementClassType.getRawType();
} else {
throw new IllegalStateException("Unhandled type " + elementClassType + ".");
}
if (keyType instanceof Class<?> class1) {
keyClass = class1;
} else if (keyType instanceof ParameterizedType parameterizedElementClassType) {
keyClass = (Class<?>) parameterizedElementClassType.getRawType();
} else {
throw new IllegalStateException("Unhandled type " + keyType + ".");
}
} else {
throw new IllegalStateException("Cannot infer element type for Map type (" + type + ").");
}
List<Class<?>> entitySubclasses = deepClonedClassesSortedSet.stream()
.filter(keyClass::isAssignableFrom).toList();
ResultHandle entry = whileLoopBlock
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Iterator.class, "next", Object.class), iterator);
ResultHandle toCloneValue = whileLoopBlock
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Map.Entry.class, "getValue", Object.class), entry);
final AssignableResultHandle clonedElement = whileLoopBlock.createVariable(elementClass);
writeDeepCloneInstructions(whileLoopBlock, solutionDescriptor,
elementClass, elementClassType, toCloneValue, clonedElement, createdCloneMap, deepClonedClassesSortedSet);
ResultHandle key = whileLoopBlock
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Map.Entry.class, "getKey", Object.class), entry);
if (!entitySubclasses.isEmpty()) {
AssignableResultHandle keyCloneResultHolder = whileLoopBlock.createVariable(keyClass);
writeDeepCloneEntityOrFactInstructions(whileLoopBlock, solutionDescriptor, keyClass,
key, keyCloneResultHolder, createdCloneMap, deepClonedClassesSortedSet, UnhandledCloneType.DEEP);
whileLoopBlock.invokeInterfaceMethod(
PUT_METHOD,
cloneMap, keyCloneResultHolder, clonedElement);
} else {
whileLoopBlock.invokeInterfaceMethod(
PUT_METHOD,
cloneMap, key, clonedElement);
}
bytecodeCreator.assign(cloneResultHolder, cloneMap);
}
/**
* Writes the following code:
*
* <pre>
* // For an array
* Object[] clone = new Object[toClone.length];
*
* for (int i = 0; i < original.length; i++) {
* clone[i] = (result from recursion on toClone[i]);
* }
* cloneResultHolder = clone;
* </pre>
**/
private void writeDeepCloneArrayInstructions(BytecodeCreator bytecodeCreator,
GizmoSolutionOrEntityDescriptor solutionDescriptor,
Class<?> deeplyClonedFieldClass, ResultHandle toClone, AssignableResultHandle cloneResultHolder,
ResultHandle createdCloneMap, SortedSet<Class<?>> deepClonedClassesSortedSet) {
// Clone array
Class<?> arrayComponent = deeplyClonedFieldClass.getComponentType();
ResultHandle arrayLength = bytecodeCreator.arrayLength(toClone);
ResultHandle arrayClone = bytecodeCreator.newArray(arrayComponent, arrayLength);
AssignableResultHandle iterations = bytecodeCreator.createVariable(int.class);
bytecodeCreator.assign(iterations, bytecodeCreator.load(0));
BytecodeCreator whileLoopBlock = bytecodeCreator
.whileLoop(conditionBytecode -> conditionBytecode.ifIntegerLessThan(iterations, arrayLength))
.block();
ResultHandle toCloneElement = whileLoopBlock.readArrayValue(toClone, iterations);
AssignableResultHandle clonedElement = whileLoopBlock.createVariable(arrayComponent);
writeDeepCloneInstructions(whileLoopBlock, solutionDescriptor, arrayComponent,
arrayComponent, toCloneElement, clonedElement, createdCloneMap, deepClonedClassesSortedSet);
whileLoopBlock.writeArrayValue(arrayClone, iterations, clonedElement);
whileLoopBlock.assign(iterations, whileLoopBlock.increment(iterations));
bytecodeCreator.assign(cloneResultHolder, arrayClone);
}
/**
* Writes the following code:
*
* <pre>
* // For an entity
* if (toClone instanceof SubclassOfEntity1) {
* SubclassOfEntity1 clone = new SubclassOfEntity1();
*
* // shallowly clone fields using writeShallowCloneInstructions()
* // for any deeply cloned field, do recursion on it
* cloneResultHolder = clone;
* } else if (toClone instanceof SubclassOfEntity2) {
* // ...
* }
* // ...
* else if (toClone instanceof SubclassOfEntityN) {
* // ...
* } else {
* // shallow or deep clone based on whether deep cloning is forced
* }
* </pre>
**/
private void writeDeepCloneEntityOrFactInstructions(BytecodeCreator bytecodeCreator,
GizmoSolutionOrEntityDescriptor solutionDescriptor, Class<?> deeplyClonedFieldClass, ResultHandle toClone,
AssignableResultHandle cloneResultHolder, ResultHandle createdCloneMap,
SortedSet<Class<?>> deepClonedClassesSortedSet, UnhandledCloneType unhandledCloneType) {
List<Class<?>> deepClonedSubclasses = deepClonedClassesSortedSet.stream()
.filter(deeplyClonedFieldClass::isAssignableFrom)
.filter(type -> DeepCloningUtils.isClassDeepCloned(solutionDescriptor.getSolutionDescriptor(), type))
.toList();
BytecodeCreator currentBranch = bytecodeCreator;
// If the field holds an instance of one of the field's declared type's subtypes, clone the subtype instead.
for (Class<?> deepClonedSubclass : deepClonedSubclasses) {
ResultHandle isInstance = currentBranch.instanceOf(toClone, deepClonedSubclass);
BranchResult isInstanceBranchResult = currentBranch.ifTrue(isInstance);
BytecodeCreator isInstanceBranch = isInstanceBranchResult.trueBranch();
ResultHandle cloneObj = isInstanceBranch.invokeStaticMethod(
MethodDescriptor.ofMethod(
GizmoSolutionClonerFactory.getGeneratedClassName(solutionDescriptor.getSolutionDescriptor()),
getEntityHelperMethodName(deepClonedSubclass), deepClonedSubclass, deepClonedSubclass, Map.class),
toClone, createdCloneMap);
isInstanceBranch.assign(cloneResultHolder, cloneObj);
currentBranch = isInstanceBranchResult.falseBranch();
}
// We are certain that the instance is of the same type as the declared field type.
// (Or is an undeclared subclass of the planning entity)
switch (unhandledCloneType) {
case SHALLOW -> currentBranch.assign(cloneResultHolder, toClone);
case DEEP -> {
ResultHandle cloneObj = currentBranch.invokeStaticMethod(
MethodDescriptor.ofMethod(
GizmoSolutionClonerFactory.getGeneratedClassName(solutionDescriptor.getSolutionDescriptor()),
getEntityHelperMethodName(deeplyClonedFieldClass), deeplyClonedFieldClass,
deeplyClonedFieldClass, Map.class),
toClone, createdCloneMap);
currentBranch.assign(cloneResultHolder, cloneObj);
}
}
}
protected String getEntityHelperMethodName(Class<?> entityClass) {
return "$clone" + entityClass.getName().replace('.', '_');
}
/**
* Writes the following code:
* <p>
* In Quarkus: (nothing)
* <p>
* Outside Quarkus:
*
* <pre>
* if (toClone.getClass() != entityClass) {
* Cloner.fallbackCloner.gizmoFallbackDeepClone(toClone, cloneMap);
* } else {
* ...
* }
* </pre>
*
* @return The else branch {@link BytecodeCreator} outside of Quarkus, the original bytecodeCreator otherwise.
*/
protected BytecodeCreator createUnknownClassHandler(BytecodeCreator bytecodeCreator,
SolutionDescriptor<?> solutionDescriptor,
Class<?> entityClass,
ResultHandle toClone,
ResultHandle cloneMap) {
ResultHandle actualClass =
bytecodeCreator.invokeVirtualMethod(MethodDescriptor.ofMethod(Object.class, "getClass", Class.class),
toClone);
BranchResult branchResult = bytecodeCreator.ifReferencesNotEqual(actualClass,
bytecodeCreator.loadClass(entityClass));
BytecodeCreator currentBranch = branchResult.trueBranch();
ResultHandle fallbackCloner =
currentBranch.readStaticField(FieldDescriptor.of(
GizmoSolutionClonerFactory.getGeneratedClassName(solutionDescriptor),
FALLBACK_CLONER, FieldAccessingSolutionCloner.class));
ResultHandle cloneObj =
currentBranch.invokeVirtualMethod(MethodDescriptor.ofMethod(FieldAccessingSolutionCloner.class,
"gizmoFallbackDeepClone", Object.class, Object.class, Map.class),
fallbackCloner, toClone, cloneMap);
currentBranch.returnValue(cloneObj);
return branchResult.falseBranch();
}
// To prevent stack overflow on chained models
private void createDeepCloneHelperMethod(ClassCreator classCreator,
Class<?> entityClass,
SolutionDescriptor<?> solutionDescriptor,
Map<Class<?>, GizmoSolutionOrEntityDescriptor> memoizedSolutionOrEntityDescriptorMap,
SortedSet<Class<?>> deepClonedClassesSortedSet) {
MethodCreator methodCreator =
classCreator.getMethodCreator(getEntityHelperMethodName(entityClass), entityClass, entityClass, Map.class);
methodCreator.setModifiers(Modifier.STATIC | Modifier.PRIVATE);
GizmoSolutionOrEntityDescriptor entityDescriptor = memoizedSolutionOrEntityDescriptorMap.computeIfAbsent(entityClass,
key -> new GizmoSolutionOrEntityDescriptor(solutionDescriptor, entityClass));
ResultHandle toClone = methodCreator.getMethodParam(0);
ResultHandle cloneMap = methodCreator.getMethodParam(1);
ResultHandle maybeClone = methodCreator.invokeInterfaceMethod(
GET_METHOD, cloneMap, toClone);
BranchResult hasCloneBranchResult = methodCreator.ifNotNull(maybeClone);
BytecodeCreator hasCloneBranch = hasCloneBranchResult.trueBranch();
hasCloneBranch.returnValue(maybeClone);
BytecodeCreator noCloneBranch = hasCloneBranchResult.falseBranch();
noCloneBranch = createUnknownClassHandler(noCloneBranch,
solutionDescriptor,
entityClass,
toClone,
cloneMap);
ResultHandle cloneObj;
if (PlanningCloneable.class.isAssignableFrom(entityClass)) {
cloneObj = noCloneBranch.invokeInterfaceMethod(
MethodDescriptor.ofMethod(PlanningCloneable.class, "createNewInstance", Object.class),
toClone);
cloneObj = noCloneBranch.checkCast(cloneObj, entityClass);
} else {
cloneObj = noCloneBranch.newInstance(MethodDescriptor.ofConstructor(entityClass));
}
noCloneBranch.invokeInterfaceMethod(
MethodDescriptor.ofMethod(Map.class, "put", Object.class, Object.class, Object.class),
cloneMap, toClone, cloneObj);
for (GizmoMemberDescriptor shallowlyClonedField : entityDescriptor.getShallowClonedMemberDescriptors()) {
writeShallowCloneInstructions(entityDescriptor, noCloneBranch, shallowlyClonedField, toClone, cloneObj, cloneMap,
deepClonedClassesSortedSet);
}
for (Field deeplyClonedField : entityDescriptor.getDeepClonedFields()) {
GizmoMemberDescriptor gizmoMemberDescriptor =
entityDescriptor.getMemberDescriptorForField(deeplyClonedField);
ResultHandle subfieldValue = gizmoMemberDescriptor.readMemberValue(noCloneBranch, toClone);
AssignableResultHandle cloneValue = noCloneBranch.createVariable(deeplyClonedField.getType());
writeDeepCloneInstructions(noCloneBranch, entityDescriptor, deeplyClonedField, gizmoMemberDescriptor, subfieldValue,
cloneValue, cloneMap, deepClonedClassesSortedSet);
if (!gizmoMemberDescriptor.writeMemberValue(noCloneBranch, cloneObj, cloneValue)) {
throw new IllegalStateException("The member (" + gizmoMemberDescriptor.getName() + ") of class (" +
gizmoMemberDescriptor.getDeclaringClassName() + ") does not have a setter.");
}
}
noCloneBranch.returnValue(cloneObj);
}
protected void createAbstractDeepCloneHelperMethod(ClassCreator classCreator,
Class<?> entityClass,
SolutionDescriptor<?> solutionDescriptor,
Map<Class<?>, GizmoSolutionOrEntityDescriptor> memoizedSolutionOrEntityDescriptorMap,
SortedSet<Class<?>> deepClonedClassesSortedSet) {
MethodCreator methodCreator =
classCreator.getMethodCreator(getEntityHelperMethodName(entityClass), entityClass, entityClass, Map.class);
methodCreator.setModifiers(Modifier.STATIC | Modifier.PRIVATE);
ResultHandle toClone = methodCreator.getMethodParam(0);
ResultHandle cloneMap = methodCreator.getMethodParam(1);
ResultHandle maybeClone = methodCreator.invokeInterfaceMethod(
GET_METHOD, cloneMap, toClone);
BranchResult hasCloneBranchResult = methodCreator.ifNotNull(maybeClone);
BytecodeCreator hasCloneBranch = hasCloneBranchResult.trueBranch();
hasCloneBranch.returnValue(maybeClone);
BytecodeCreator noCloneBranch = hasCloneBranchResult.falseBranch();
ResultHandle fallbackCloner =
noCloneBranch.readStaticField(FieldDescriptor.of(
GizmoSolutionClonerFactory.getGeneratedClassName(solutionDescriptor),
FALLBACK_CLONER, FieldAccessingSolutionCloner.class));
ResultHandle cloneObj =
noCloneBranch.invokeVirtualMethod(MethodDescriptor.ofMethod(FieldAccessingSolutionCloner.class,
"gizmoFallbackDeepClone", Object.class, Object.class, Map.class),
fallbackCloner, toClone, cloneMap);
noCloneBranch.returnValue(cloneObj);
}
private enum UnhandledCloneType {
SHALLOW,
DEEP
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/cloner/gizmo/GizmoSolutionOrEntityDescriptor.java | package ai.timefold.solver.core.impl.domain.solution.cloner.gizmo;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import ai.timefold.solver.core.impl.domain.common.accessor.gizmo.GizmoMemberDescriptor;
import ai.timefold.solver.core.impl.domain.solution.cloner.DeepCloningUtils;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
public class GizmoSolutionOrEntityDescriptor {
SolutionDescriptor<?> solutionDescriptor;
Map<Field, GizmoMemberDescriptor> solutionFieldToMemberDescriptorMap;
Set<Field> deepClonedFields;
Set<Field> shallowlyClonedFields;
public GizmoSolutionOrEntityDescriptor(SolutionDescriptor<?> solutionDescriptor, Class<?> entityOrSolutionClass) {
this(solutionDescriptor, entityOrSolutionClass,
getFieldsToSolutionFieldToMemberDescriptorMap(entityOrSolutionClass, new HashMap<>()));
}
public GizmoSolutionOrEntityDescriptor(SolutionDescriptor<?> solutionDescriptor, Class<?> entityOrSolutionClass,
Map<Field, GizmoMemberDescriptor> solutionFieldToMemberDescriptorMap) {
this.solutionDescriptor = solutionDescriptor;
this.solutionFieldToMemberDescriptorMap = solutionFieldToMemberDescriptorMap;
deepClonedFields = new HashSet<>();
shallowlyClonedFields = new HashSet<>();
for (Field field : solutionFieldToMemberDescriptorMap.keySet()) {
if (DeepCloningUtils.isDeepCloned(solutionDescriptor, field, entityOrSolutionClass, field.getType())) {
deepClonedFields.add(field);
} else {
shallowlyClonedFields.add(field);
}
}
}
private static Map<Field, GizmoMemberDescriptor> getFieldsToSolutionFieldToMemberDescriptorMap(Class<?> clazz,
Map<Field, GizmoMemberDescriptor> solutionFieldToMemberDescriptorMap) {
for (Field field : clazz.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers())) {
solutionFieldToMemberDescriptorMap.put(field, new GizmoMemberDescriptor(field));
}
}
if (clazz.getSuperclass() != null) {
getFieldsToSolutionFieldToMemberDescriptorMap(clazz.getSuperclass(), solutionFieldToMemberDescriptorMap);
}
return solutionFieldToMemberDescriptorMap;
}
public SolutionDescriptor<?> getSolutionDescriptor() {
return solutionDescriptor;
}
public Set<GizmoMemberDescriptor> getShallowClonedMemberDescriptors() {
return solutionFieldToMemberDescriptorMap.keySet().stream()
.filter(field -> shallowlyClonedFields.contains(field))
.map(solutionFieldToMemberDescriptorMap::get).collect(Collectors.toSet());
}
public Set<Field> getDeepClonedFields() {
return deepClonedFields;
}
public GizmoMemberDescriptor getMemberDescriptorForField(Field field) {
return solutionFieldToMemberDescriptorMap.get(field);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/descriptor/DefaultPlanningEntityDiff.java | package ai.timefold.solver.core.impl.domain.solution.descriptor;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningEntityMetaModel;
import ai.timefold.solver.core.preview.api.domain.solution.diff.PlanningEntityDiff;
import ai.timefold.solver.core.preview.api.domain.solution.diff.PlanningSolutionDiff;
import ai.timefold.solver.core.preview.api.domain.solution.diff.PlanningVariableDiff;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
record DefaultPlanningEntityDiff<Solution_, Entity_>(PlanningSolutionDiff<Solution_> solutionDiff, Entity_ entity,
PlanningEntityMetaModel<Solution_, Entity_> entityMetaModel,
Map<String, PlanningVariableDiff<Solution_, Entity_, ?>> variableDiffMap)
implements
PlanningEntityDiff<Solution_, Entity_> {
@SuppressWarnings("unchecked")
DefaultPlanningEntityDiff(PlanningSolutionDiff<Solution_> solutionDiff, Entity_ entity) {
this(solutionDiff, entity,
(PlanningEntityMetaModel<Solution_, Entity_>) solutionDiff.solutionMetaModel().entity(entity.getClass()));
}
DefaultPlanningEntityDiff(PlanningSolutionDiff<Solution_> solutionDiff, Entity_ entity,
PlanningEntityMetaModel<Solution_, Entity_> entityMetaModel) {
this(solutionDiff, entity, entityMetaModel, new LinkedHashMap<>(entityMetaModel.variables().size()));
}
@SuppressWarnings("unchecked")
@Override
public <Value_> PlanningVariableDiff<Solution_, Entity_, Value_> variableDiff() {
if (variableDiffMap.size() != 1) {
throw new IllegalStateException("""
There is more than one planning variable (%s) on the planning entity (%s).
Use variableDiff(String) instead.""".formatted(variableDiffMap.keySet(), entity.getClass()));
}
return (PlanningVariableDiff<Solution_, Entity_, Value_>) variableDiffs().iterator().next();
}
void addVariableDiff(PlanningVariableDiff<Solution_, Entity_, ?> variableDiff) {
variableDiffMap.put(variableDiff.variableMetaModel().name(), variableDiff);
}
@SuppressWarnings("unchecked")
@Override
public @Nullable <Value_> PlanningVariableDiff<Solution_, Entity_, Value_> variableDiff(String variableRef) {
return (PlanningVariableDiff<Solution_, Entity_, Value_>) variableDiffMap.get(variableRef);
}
@Override
public Collection<PlanningVariableDiff<Solution_, Entity_, ?>> variableDiffs() {
return Collections.unmodifiableCollection(variableDiffMap.values());
}
@Override
public String toString() {
return """
Difference between two solutions in variable(s) of planning entity (%s) of type (%s):
%s
""".formatted(entity, entityMetaModel().type(), entityDiffToString(this));
}
private static String entityDiffToString(PlanningEntityDiff<?, ?> entityDiff) {
var variableDiffs = entityDiff.variableDiffs();
if (variableDiffs.size() == 1) {
var diff = variableDiffs.iterator().next();
return " %s: %s -> %s".formatted(diff.variableMetaModel().name(), diff.oldValue(), diff.newValue());
}
return variableDiffs.stream()
.map(diff -> " %s (%s): %s -> %s".formatted(diff.variableMetaModel().name(),
diff.variableMetaModel().isGenuine() ? "genuine" : "shadow", diff.oldValue(), diff.newValue()))
.collect(Collectors.joining(System.lineSeparator()));
}
@Override
public boolean equals(@Nullable Object o) {
if (!(o instanceof DefaultPlanningEntityDiff<?, ?> that)) {
return false;
}
return Objects.equals(entityMetaModel, that.entityMetaModel)
&& Objects.equals(solutionDiff, that.solutionDiff)
&& Objects.equals(entity, that.entity);
}
@Override
public int hashCode() {
return Objects.hash(entityMetaModel, solutionDiff, entity);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/descriptor/DefaultPlanningEntityMetaModel.java | package ai.timefold.solver.core.impl.domain.solution.descriptor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningEntityMetaModel;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningSolutionMetaModel;
import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel;
import org.jspecify.annotations.NullMarked;
@NullMarked
public final class DefaultPlanningEntityMetaModel<Solution_, Entity_>
implements PlanningEntityMetaModel<Solution_, Entity_> {
private final EntityDescriptor<Solution_> entityDescriptor;
private final PlanningSolutionMetaModel<Solution_> solution;
private final Class<Entity_> type;
private final List<VariableMetaModel<Solution_, Entity_, ?>> variables = new ArrayList<>();
@SuppressWarnings("unchecked")
DefaultPlanningEntityMetaModel(PlanningSolutionMetaModel<Solution_> solution,
EntityDescriptor<Solution_> entityDescriptor) {
this.solution = Objects.requireNonNull(solution);
this.entityDescriptor = Objects.requireNonNull(entityDescriptor);
this.type = (Class<Entity_>) entityDescriptor.getEntityClass();
}
public EntityDescriptor<Solution_> entityDescriptor() {
return entityDescriptor;
}
@Override
public PlanningSolutionMetaModel<Solution_> solution() {
return solution;
}
@Override
public Class<Entity_> type() {
return type;
}
@Override
public List<VariableMetaModel<Solution_, Entity_, ?>> variables() {
return Collections.unmodifiableList(variables);
}
void addVariable(VariableMetaModel<Solution_, Entity_, ?> variable) {
if (variable.entity() != this) {
throw new IllegalArgumentException("The variable (%s) is not part of this entity (%s)."
.formatted(variable.name(), type.getSimpleName()));
}
variables.add(variable);
}
@Override
public String toString() {
return "%s Entity (%s) with variables (%s)"
.formatted(isGenuine() ? "Genuine" : "Shadow", type,
variables().stream()
.map(VariableMetaModel::name)
.toList());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/descriptor/DefaultPlanningListVariableMetaModel.java | package ai.timefold.solver.core.impl.domain.solution.descriptor;
import java.util.Objects;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningEntityMetaModel;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningListVariableMetaModel;
import org.jspecify.annotations.NullMarked;
@NullMarked
public record DefaultPlanningListVariableMetaModel<Solution_, Entity_, Value_>(
PlanningEntityMetaModel<Solution_, Entity_> entity,
ListVariableDescriptor<Solution_> variableDescriptor)
implements
PlanningListVariableMetaModel<Solution_, Entity_, Value_>,
InnerGenuineVariableMetaModel<Solution_> {
@SuppressWarnings("unchecked")
@Override
public Class<Value_> type() {
return (Class<Value_>) variableDescriptor.getElementType();
}
@Override
public String name() {
return variableDescriptor.getVariableName();
}
@Override
public boolean allowsUnassignedValues() {
return variableDescriptor.allowsUnassignedValues();
}
@Override
public boolean equals(Object o) {
// Do not use entity in equality checks;
// If an entity is subclassed, that subclass will have it
// own distinct VariableMetaModel
if (o instanceof DefaultPlanningListVariableMetaModel<?, ?, ?> that) {
return Objects.equals(variableDescriptor, that.variableDescriptor);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor);
}
@Override
public String toString() {
return "Genuine List Variable '%s %s.%s' (allowsUnassignedValues: %b)"
.formatted(type(), entity.getClass().getSimpleName(), name(), allowsUnassignedValues());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/descriptor/DefaultPlanningSolutionDiff.java | package ai.timefold.solver.core.impl.domain.solution.descriptor;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningSolutionMetaModel;
import ai.timefold.solver.core.preview.api.domain.solution.diff.PlanningEntityDiff;
import ai.timefold.solver.core.preview.api.domain.solution.diff.PlanningSolutionDiff;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
final class DefaultPlanningSolutionDiff<Solution_> implements PlanningSolutionDiff<Solution_> {
private static final int TO_STRING_ITEM_LIMIT = 5;
private final PlanningSolutionMetaModel<Solution_> solutionMetaModel;
private final Solution_ oldSolution;
private final Solution_ newSolution;
private final Set<Object> removedEntities;
private final Set<Object> addedEntities;
private final Map<Class<?>, Set<PlanningEntityDiff<Solution_, ?>>> entityDiffMap = new LinkedHashMap<>();
DefaultPlanningSolutionDiff(PlanningSolutionMetaModel<Solution_> solutionMetaModel, Solution_ oldSolution,
Solution_ newSolution, Set<?> removedEntities, Set<?> addedEntities) {
this.solutionMetaModel = Objects.requireNonNull(solutionMetaModel);
this.oldSolution = Objects.requireNonNull(oldSolution);
this.newSolution = Objects.requireNonNull(newSolution);
this.removedEntities = Collections.unmodifiableSet(Objects.requireNonNull(removedEntities));
this.addedEntities = Collections.unmodifiableSet(Objects.requireNonNull(addedEntities));
}
@Override
public PlanningSolutionMetaModel<Solution_> solutionMetaModel() {
return solutionMetaModel;
}
@SuppressWarnings("unchecked")
@Override
public @Nullable <Entity_> PlanningEntityDiff<Solution_, Entity_> entityDiff(Entity_ entity) {
return entityDiffs((Class<Entity_>) entity.getClass()).stream()
.filter(entityDiff -> entityDiff.entity().equals(entity))
.findFirst()
.orElse(null);
}
@Override
public Set<PlanningEntityDiff<Solution_, ?>> entityDiffs() {
if (entityDiffMap.isEmpty()) {
return Collections.emptySet();
}
return entityDiffMap.values().stream()
.flatMap(Set::stream)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public <Entity_> Set<PlanningEntityDiff<Solution_, Entity_>> entityDiffs(Class<Entity_> entityClass) {
var entityDiffSet = (Set) entityDiffMap.get(entityClass);
if (entityDiffSet == null) {
return Collections.emptySet();
}
return Collections.unmodifiableSet(entityDiffSet);
}
void addEntityDiff(PlanningEntityDiff<Solution_, ?> entityDiff) {
entityDiffMap.computeIfAbsent(entityDiff.entityMetaModel().type(), k -> new LinkedHashSet<>())
.add(entityDiff);
}
@Override
public Solution_ oldSolution() {
return oldSolution;
}
@Override
public Solution_ newSolution() {
return newSolution;
}
@Override
public Set<Object> removedEntities() {
return removedEntities;
}
@Override
public Set<Object> addedEntities() {
return addedEntities;
}
@Override
public String toString() {
return toString(TO_STRING_ITEM_LIMIT);
}
/**
* Like {@link #toString()}, but with a configurable limit on the number of items listed.
*
* @param limit Use Integer.MAX_VALUE to list all items.
* @return A string representation of the diff.
*/
String toString(int limit) {
var removedEntityString = collectionToString(removedEntities, limit);
var addedEntityString = collectionToString(addedEntities, limit);
var entityDiffStringList = entityDiffMap.values().stream()
.flatMap(Set::stream)
.map(DefaultPlanningSolutionDiff::entityDiffToString)
.toList();
var entityDiffString = collectionToString(entityDiffStringList, limit);
return """
Difference(s) between old planning solution (%s) and new planning solution (%s):
- Old solution entities not present in new solution:
%s
- New solution entities not present in old solution:
%s
- Entities changed between the solutions:
%s
""".formatted(oldSolution, newSolution, removedEntityString, addedEntityString, entityDiffString);
}
private static String collectionToString(Collection<?> entitySet, int limit) {
if (entitySet.isEmpty()) {
return " (None.)";
}
var addedEntityString = entitySet.stream()
.limit(limit)
.map(s -> " " + s.toString())
.collect(Collectors.joining(System.lineSeparator()));
if (entitySet.size() > limit) {
addedEntityString += System.lineSeparator() + " ...";
}
return addedEntityString;
}
static String entityDiffToString(PlanningEntityDiff<?, ?> entityDiff) {
var entity = entityDiff.entity();
var variableDiffs = entityDiff.variableDiffs();
if (entityDiff.entityMetaModel().variables().size() == 1) {
var variableDiff = variableDiffs.iterator().next();
return "%s (%s -> %s)".formatted(entity, variableDiff.oldValue(), variableDiff.newValue());
}
var variableDiffString = variableDiffs.stream()
.map(diff -> " %s (%s): %s -> %s".formatted(diff.variableMetaModel().name(),
diff.variableMetaModel().isGenuine() ? "genuine" : "shadow", diff.oldValue(), diff.newValue()))
.collect(Collectors.joining(System.lineSeparator()));
return """
%s:
%s""".formatted(entity, variableDiffString);
}
@Override
public boolean equals(@Nullable Object o) {
if (!(o instanceof DefaultPlanningSolutionDiff<?> that)) {
return false;
}
return Objects.equals(solutionMetaModel, that.solutionMetaModel) && Objects.equals(oldSolution, that.oldSolution)
&& Objects.equals(newSolution, that.newSolution);
}
@Override
public int hashCode() {
return Objects.hash(solutionMetaModel, oldSolution, newSolution);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/descriptor/DefaultPlanningSolutionMetaModel.java | package ai.timefold.solver.core.impl.domain.solution.descriptor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningEntityMetaModel;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningSolutionMetaModel;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
public final class DefaultPlanningSolutionMetaModel<Solution_> implements PlanningSolutionMetaModel<Solution_> {
private final SolutionDescriptor<Solution_> solutionDescriptor;
private final Class<Solution_> type;
private final List<PlanningEntityMetaModel<Solution_, ?>> entities = new ArrayList<>();
DefaultPlanningSolutionMetaModel(SolutionDescriptor<Solution_> solutionDescriptor) {
this.solutionDescriptor = Objects.requireNonNull(solutionDescriptor);
this.type = solutionDescriptor.getSolutionClass();
}
public SolutionDescriptor<Solution_> solutionDescriptor() {
return solutionDescriptor;
}
@Override
public Class<Solution_> type() {
return type;
}
@Override
public List<PlanningEntityMetaModel<Solution_, ?>> entities() {
return Collections.unmodifiableList(entities);
}
void addEntity(PlanningEntityMetaModel<Solution_, ?> planningEntityMetaModel) {
if (planningEntityMetaModel.solution() != this) {
throw new IllegalArgumentException("The entityMetaModel (%s) must be created by this solutionMetaModel (%s)."
.formatted(planningEntityMetaModel, this));
}
entities.add(planningEntityMetaModel);
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o)
return true;
if (!(o instanceof DefaultPlanningSolutionMetaModel<?> that))
return false;
return Objects.equals(type, that.type);
}
@Override
public int hashCode() {
return Objects.hashCode(type);
}
@Override
public String toString() {
return "Planning Solution (%s) with entities (%s)"
.formatted(type.getSimpleName(),
entities.stream()
.map(e -> e.type().getSimpleName())
.toList());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/descriptor/DefaultPlanningVariableDiff.java | package ai.timefold.solver.core.impl.domain.solution.descriptor;
import java.util.Objects;
import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel;
import ai.timefold.solver.core.preview.api.domain.solution.diff.PlanningEntityDiff;
import ai.timefold.solver.core.preview.api.domain.solution.diff.PlanningVariableDiff;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
record DefaultPlanningVariableDiff<Solution_, Entity_, Value_>(PlanningEntityDiff<Solution_, Entity_> entityDiff,
VariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Value_ oldValue, Value_ newValue)
implements
PlanningVariableDiff<Solution_, Entity_, Value_> {
DefaultPlanningVariableDiff {
Objects.requireNonNull(entityDiff);
Objects.requireNonNull(variableMetaModel);
}
@Override
public String toString() {
return """
Difference between two solutions in a %s planning variable (%s) of a planning entity (%s) of type (%s):
Old value: %s
New value: %s
"""
.formatted(variableMetaModel.isGenuine() ? "genuine" : "shadow", variableMetaModel.name(),
entityDiff.entity(), entityDiff.entityMetaModel().type(), oldValue, newValue);
}
@Override
public boolean equals(@Nullable Object o) {
if (!(o instanceof DefaultPlanningVariableDiff<?, ?, ?> that)) {
return false;
}
return Objects.equals(variableMetaModel, that.variableMetaModel)
&& Objects.equals(entityDiff, that.entityDiff);
}
@Override
public int hashCode() {
return Objects.hash(variableMetaModel, entityDiff);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/descriptor/DefaultPlanningVariableMetaModel.java | package ai.timefold.solver.core.impl.domain.solution.descriptor;
import java.util.Objects;
import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningEntityMetaModel;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningVariableMetaModel;
import org.jspecify.annotations.NullMarked;
@NullMarked
public record DefaultPlanningVariableMetaModel<Solution_, Entity_, Value_>(
PlanningEntityMetaModel<Solution_, Entity_> entity,
BasicVariableDescriptor<Solution_> variableDescriptor)
implements
PlanningVariableMetaModel<Solution_, Entity_, Value_>,
InnerGenuineVariableMetaModel<Solution_> {
@SuppressWarnings("unchecked")
@Override
public Class<Value_> type() {
return (Class<Value_>) variableDescriptor.getVariablePropertyType();
}
@Override
public String name() {
return variableDescriptor.getVariableName();
}
@Override
public boolean allowsUnassigned() {
return variableDescriptor.allowsUnassigned();
}
@Override
public boolean isChained() {
return variableDescriptor.isChained();
}
@Override
public boolean equals(Object o) {
// Do not use entity in equality checks;
// If an entity is subclassed, that subclass will have it
// own distinct VariableMetaModel
if (o instanceof DefaultPlanningVariableMetaModel<?, ?, ?> that) {
return Objects.equals(variableDescriptor, that.variableDescriptor);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(variableDescriptor);
}
@Override
public String toString() {
return "Genuine Variable '%s %s.%s' (allowsUnassigned: %b, isChained: %b)"
.formatted(type(), entity.getClass().getSimpleName(), name(), allowsUnassigned(), isChained());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/descriptor/DefaultShadowVariableMetaModel.java | package ai.timefold.solver.core.impl.domain.solution.descriptor;
import java.util.Objects;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningEntityMetaModel;
import ai.timefold.solver.core.preview.api.domain.metamodel.ShadowVariableMetaModel;
import org.jspecify.annotations.NullMarked;
@NullMarked
public record DefaultShadowVariableMetaModel<Solution_, Entity_, Value_>(
PlanningEntityMetaModel<Solution_, Entity_> entity,
ShadowVariableDescriptor<Solution_> variableDescriptor)
implements
ShadowVariableMetaModel<Solution_, Entity_, Value_>,
InnerVariableMetaModel<Solution_> {
@SuppressWarnings("unchecked")
@Override
public Class<Value_> type() {
return (Class<Value_>) variableDescriptor.getVariablePropertyType();
}
@Override
public String name() {
return variableDescriptor.getVariableName();
}
@Override
public ShadowVariableDescriptor<Solution_> variableDescriptor() {
return variableDescriptor;
}
@Override
public boolean equals(Object o) {
// Do not use entity in equality checks;
// If an entity is subclassed, that subclass will have it
// own distinct VariableMetaModel
if (o instanceof DefaultShadowVariableMetaModel<?, ?, ?> that) {
return Objects.equals(variableDescriptor, that.variableDescriptor);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(variableDescriptor);
}
@Override
public String toString() {
return "Shadow Variable '%s %s.%s'"
.formatted(type(), entity.type().getSimpleName(), name());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/descriptor/DummyMemberAccessor.java | package ai.timefold.solver.core.impl.domain.solution.descriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.function.Function;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
final class DummyMemberAccessor implements MemberAccessor {
static final MemberAccessor INSTANCE = new DummyMemberAccessor();
private DummyMemberAccessor() {
}
@Override
public Class<?> getDeclaringClass() {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public Class<?> getType() {
return null;
}
@Override
public Type getGenericType() {
return null;
}
@Override
public Object executeGetter(Object bean) {
return null;
}
@Override
public <Fact_, Result_> Function<Fact_, Result_> getGetterFunction() {
return null;
}
@Override
public boolean supportSetter() {
return false;
}
@Override
public void executeSetter(Object bean, Object value) {
}
@Override
public String getSpeedNote() {
return null;
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
return null;
}
@Override
public <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
return null;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/descriptor/InnerGenuineVariableMetaModel.java | package ai.timefold.solver.core.impl.domain.solution.descriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import org.jspecify.annotations.NullMarked;
@NullMarked
public sealed interface InnerGenuineVariableMetaModel<Solution_>
extends InnerVariableMetaModel<Solution_>
permits DefaultPlanningVariableMetaModel, DefaultPlanningListVariableMetaModel {
@Override
GenuineVariableDescriptor<Solution_> variableDescriptor();
} |
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/descriptor/InnerVariableMetaModel.java | package ai.timefold.solver.core.impl.domain.solution.descriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import org.jspecify.annotations.NullMarked;
@NullMarked
public sealed interface InnerVariableMetaModel<Solution_>
permits DefaultShadowVariableMetaModel, InnerGenuineVariableMetaModel {
VariableDescriptor<Solution_> variableDescriptor();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/descriptor/ProblemScaleTracker.java | package ai.timefold.solver.core.impl.domain.solution.descriptor;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Set;
import ai.timefold.solver.core.impl.util.MathUtils;
public class ProblemScaleTracker {
private final long logBase;
private final Set<Object> visitedAnchorSet = Collections.newSetFromMap(new IdentityHashMap<>());
private long basicProblemScaleLog = 0L;
private int listPinnedValueCount = 0;
private int listTotalEntityCount = 0;
private int listMovableEntityCount = 0;
private int listTotalValueCount = 0;
public ProblemScaleTracker(long logBase) {
this.logBase = logBase;
}
// Simple getters
public long getBasicProblemScaleLog() {
return basicProblemScaleLog;
}
public int getListPinnedValueCount() {
return listPinnedValueCount;
}
public int getListTotalEntityCount() {
return listTotalEntityCount;
}
public int getListMovableEntityCount() {
return listMovableEntityCount;
}
public int getListTotalValueCount() {
return listTotalValueCount;
}
public void setListTotalValueCount(int listTotalValueCount) {
this.listTotalValueCount = listTotalValueCount;
}
// Complex methods
public boolean isAnchorVisited(Object anchor) {
if (visitedAnchorSet.contains(anchor)) {
return true;
}
visitedAnchorSet.add(anchor);
return false;
}
public void addListValueCount(int count) {
listTotalValueCount += count;
}
public void addPinnedListValueCount(int count) {
listPinnedValueCount += count;
}
public void incrementListEntityCount(boolean isMovable) {
listTotalEntityCount++;
if (isMovable) {
listMovableEntityCount++;
}
}
public void addBasicProblemScale(long count) {
if (count == 0) {
// Log(0) = -infinity; also an invalid problem (since there are no
// valid values for the variable, including null)
return;
}
basicProblemScaleLog += MathUtils.getScaledApproximateLog(MathUtils.LOG_PRECISION, logBase, count);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/descriptor/SolutionDescriptor.java | package ai.timefold.solver.core.impl.domain.solution.descriptor;
import static ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory.MemberAccessorType.FIELD_OR_GETTER_METHOD;
import static ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory.MemberAccessorType.FIELD_OR_READ_METHOD;
import static ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor.extractInheritedClasses;
import static java.util.stream.Stream.concat;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import ai.timefold.solver.core.api.domain.autodiscover.AutoDiscoverMemberType;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.domain.constraintweight.ConstraintConfiguration;
import ai.timefold.solver.core.api.domain.constraintweight.ConstraintConfigurationProvider;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.solution.ConstraintWeightOverrides;
import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty;
import ai.timefold.solver.core.api.domain.solution.PlanningEntityProperty;
import ai.timefold.solver.core.api.domain.solution.PlanningScore;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty;
import ai.timefold.solver.core.api.domain.solution.ProblemFactProperty;
import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.config.solver.PreviewFeature;
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.common.accessor.ReflectionFieldMemberAccessor;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.lookup.LookUpStrategyResolver;
import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy;
import ai.timefold.solver.core.impl.domain.score.descriptor.ScoreDescriptor;
import ai.timefold.solver.core.impl.domain.solution.ConstraintConfigurationBasedConstraintWeightSupplier;
import ai.timefold.solver.core.impl.domain.solution.ConstraintWeightSupplier;
import ai.timefold.solver.core.impl.domain.solution.OverridesBasedConstraintWeightSupplier;
import ai.timefold.solver.core.impl.domain.solution.cloner.FieldAccessingSolutionCloner;
import ai.timefold.solver.core.impl.domain.solution.cloner.gizmo.GizmoSolutionCloner;
import ai.timefold.solver.core.impl.domain.solution.cloner.gizmo.GizmoSolutionClonerFactory;
import ai.timefold.solver.core.impl.domain.variable.declarative.DeclarativeShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.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.score.definition.ScoreDefinition;
import ai.timefold.solver.core.impl.util.MutableInt;
import ai.timefold.solver.core.impl.util.MutableLong;
import ai.timefold.solver.core.impl.util.MutablePair;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningSolutionMetaModel;
import ai.timefold.solver.core.preview.api.domain.solution.diff.PlanningSolutionDiff;
import org.jspecify.annotations.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution}
* annotation
*/
public final class SolutionDescriptor<Solution_> {
private static final Logger LOGGER = LoggerFactory.getLogger(SolutionDescriptor.class);
private static final EntityDescriptor<?> NULL_ENTITY_DESCRIPTOR = new EntityDescriptor<>(-1, null, PlanningEntity.class);
private static final Class[] ANNOTATED_MEMBERS_CLASSES = {
ProblemFactCollectionProperty.class,
ValueRangeProvider.class,
PlanningEntityCollectionProperty.class,
PlanningScore.class };
public static <Solution_> SolutionDescriptor<Solution_> buildSolutionDescriptor(Class<Solution_> solutionClass,
Class<?>... entityClasses) {
return buildSolutionDescriptor(solutionClass, Arrays.asList(entityClasses));
}
public static <Solution_> SolutionDescriptor<Solution_> buildSolutionDescriptor(
Class<Solution_> solutionClass,
List<Class<?>> entityClassList) {
return buildSolutionDescriptor(EnumSet.noneOf(PreviewFeature.class), solutionClass, entityClassList);
}
public static <Solution_> SolutionDescriptor<Solution_> buildSolutionDescriptor(
Set<PreviewFeature> enabledPreviewFeaturesSet,
Class<Solution_> solutionClass,
Class<?>... entityClasses) {
return buildSolutionDescriptor(enabledPreviewFeaturesSet, solutionClass, List.of(entityClasses));
}
public static <Solution_> SolutionDescriptor<Solution_> buildSolutionDescriptor(
Set<PreviewFeature> enabledPreviewFeaturesSet,
Class<Solution_> solutionClass,
List<Class<?>> entityClassList) {
return buildSolutionDescriptor(enabledPreviewFeaturesSet, DomainAccessType.REFLECTION, solutionClass, null,
null, entityClassList);
}
public static <Solution_> SolutionDescriptor<Solution_> buildSolutionDescriptor(
Set<PreviewFeature> enabledPreviewFeatureSet,
DomainAccessType domainAccessType,
Class<Solution_> solutionClass, Map<String, MemberAccessor> memberAccessorMap,
Map<String, SolutionCloner> solutionClonerMap, List<Class<?>> entityClassList) {
assertMutable(solutionClass, "solutionClass");
assertSingleInheritance(solutionClass);
assertValidAnnotatedMembers(solutionClass);
solutionClonerMap = Objects.requireNonNullElse(solutionClonerMap, Collections.emptyMap());
var solutionDescriptor = new SolutionDescriptor<>(solutionClass, memberAccessorMap);
var descriptorPolicy = new DescriptorPolicy();
if (enabledPreviewFeatureSet != null) {
descriptorPolicy.setEnabledPreviewFeatureSet(enabledPreviewFeatureSet);
}
descriptorPolicy.setDomainAccessType(domainAccessType);
descriptorPolicy.setGeneratedSolutionClonerMap(solutionClonerMap);
descriptorPolicy.setMemberAccessorFactory(solutionDescriptor.getMemberAccessorFactory());
solutionDescriptor.processUnannotatedFieldsAndMethods(descriptorPolicy);
solutionDescriptor.processAnnotations(descriptorPolicy, entityClassList);
// Before iterating over the entity classes, we need to read the inheritance chain,
// add all parent and child classes, and sort them.
var updatedEntityClassList = new ArrayList<>(entityClassList);
for (var entityClass : entityClassList) {
var inheritedEntityClasses = extractInheritedClasses(entityClass);
var filteredInheritedEntityClasses = inheritedEntityClasses.stream()
.filter(c -> !updatedEntityClassList.contains(c)).toList();
updatedEntityClassList.addAll(filteredInheritedEntityClasses);
}
for (var entityClass : sortEntityClassList(updatedEntityClassList)) {
var entityDescriptor = descriptorPolicy.buildEntityDescriptor(solutionDescriptor, entityClass);
entityDescriptor.processAnnotations(descriptorPolicy);
}
solutionDescriptor.afterAnnotationsProcessed(descriptorPolicy);
if (solutionDescriptor.constraintWeightSupplier != null) {
// The scoreDescriptor is definitely initialized at this point.
solutionDescriptor.constraintWeightSupplier.initialize(solutionDescriptor,
descriptorPolicy.getMemberAccessorFactory(), descriptorPolicy.getDomainAccessType());
}
return solutionDescriptor;
}
public static void assertMutable(Class<?> clz, String classType) {
if (clz.isRecord()) {
throw new IllegalArgumentException("""
The %s (%s) cannot be a record as it needs to be mutable.
Use a regular class instead."""
.formatted(classType, clz.getCanonicalName()));
} else if (clz.isEnum()) {
throw new IllegalArgumentException("""
The %s (%s) cannot be an enum as it needs to be mutable.
Use a regular class instead."""
.formatted(classType, clz.getCanonicalName()));
}
}
/**
* If a class declares any annotated member, it must be annotated as a solution,
* even if a supertype already has the annotation.
*/
private static void assertValidAnnotatedMembers(Class<?> clazz) {
// We first check the entity class
if (clazz.getAnnotation(PlanningSolution.class) == null && hasAnyAnnotatedMembers(clazz)) {
var annotatedMembers = extractAnnotatedMembers(clazz).stream()
.map(Member::getName)
.toList();
throw new IllegalStateException(
"""
The class %s is not annotated with @PlanningSolution but defines annotated members.
Maybe annotate %s with @PlanningSolution.
Maybe remove the annotated members (%s)."""
.formatted(clazz.getName(), clazz.getName(), annotatedMembers));
}
// We check the first level of the inheritance chain
var otherClazz = clazz.getSuperclass();
if (otherClazz != null && otherClazz.getAnnotation(PlanningSolution.class) == null
&& hasAnyAnnotatedMembers(otherClazz)) {
var annotatedMembers = extractAnnotatedMembers(otherClazz).stream()
.map(Member::getName)
.toList();
throw new IllegalStateException(
"""
The class %s is not annotated with @PlanningSolution but defines annotated members.
Maybe annotate %s with @PlanningSolution.
Maybe remove the annotated members (%s)."""
.formatted(otherClazz.getName(), otherClazz.getName(), annotatedMembers));
}
}
private static void assertSingleInheritance(Class<?> solutionClass) {
var inheritedClassList =
ConfigUtils.getAllAnnotatedLineageClasses(solutionClass.getSuperclass(), PlanningSolution.class);
if (inheritedClassList.size() > 1) {
throw new IllegalStateException(
"""
The class %s inherits its @%s annotation from multiple classes (%s).
Remove solution class(es) from the inheritance chain to create a single-level inheritance structure."""
.formatted(solutionClass.getName(), PlanningSolution.class.getSimpleName(), inheritedClassList));
}
}
private static List<Class<?>> sortEntityClassList(List<Class<?>> entityClassList) {
var sortedEntityClassList = new ArrayList<Class<?>>(entityClassList.size());
for (var entityClass : entityClassList) {
var added = false;
for (var i = 0; i < sortedEntityClassList.size(); i++) {
var sortedEntityClass = sortedEntityClassList.get(i);
if (entityClass.isAssignableFrom(sortedEntityClass)) {
sortedEntityClassList.add(i, entityClass);
added = true;
break;
}
}
if (!added) {
sortedEntityClassList.add(entityClass);
}
}
return sortedEntityClassList;
}
private static List<Member> extractAnnotatedMembers(Class<?> solutionClass) {
var membersList = ConfigUtils.getDeclaredMembers(solutionClass);
return membersList.stream()
.filter(member -> !ConfigUtils.extractAnnotationClasses(member, ANNOTATED_MEMBERS_CLASSES).isEmpty())
.toList();
}
private static boolean hasAnyAnnotatedMembers(Class<?> solutionClass) {
return !extractAnnotatedMembers(solutionClass).isEmpty();
}
// ************************************************************************
// Non-static members
// ************************************************************************
private final Class<Solution_> solutionClass;
private final MemberAccessorFactory memberAccessorFactory;
private DomainAccessType domainAccessType;
private AutoDiscoverMemberType autoDiscoverMemberType;
private LookUpStrategyResolver lookUpStrategyResolver;
/**
* @deprecated {@link ConstraintConfiguration} was replaced by {@link ConstraintWeightOverrides}.
*/
@Deprecated(forRemoval = true, since = "1.13.0")
private MemberAccessor constraintConfigurationMemberAccessor;
private final Map<String, MemberAccessor> problemFactMemberAccessorMap = new LinkedHashMap<>();
private final Map<String, MemberAccessor> problemFactCollectionMemberAccessorMap = new LinkedHashMap<>();
private final Map<String, MemberAccessor> entityMemberAccessorMap = new LinkedHashMap<>();
private final Map<String, MemberAccessor> entityCollectionMemberAccessorMap = new LinkedHashMap<>();
private Set<Class<?>> problemFactOrEntityClassSet;
private List<ListVariableDescriptor<Solution_>> listVariableDescriptorList;
private ScoreDescriptor<?> scoreDescriptor;
private ConstraintWeightSupplier<Solution_, ?> constraintWeightSupplier;
private final Map<Class<?>, EntityDescriptor<Solution_>> entityDescriptorMap = new LinkedHashMap<>();
private final List<Class<?>> reversedEntityClassList = new ArrayList<>();
private final ConcurrentMap<Class<?>, EntityDescriptor<Solution_>> lowestEntityDescriptorMap = new ConcurrentHashMap<>();
private final ConcurrentMap<Class<?>, MemberAccessor> planningIdMemberAccessorMap = new ConcurrentHashMap<>();
private PlanningSolutionMetaModel<Solution_> planningSolutionMetaModel;
private SolutionCloner<Solution_> solutionCloner;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
private SolutionDescriptor(Class<Solution_> solutionClass, Map<String, MemberAccessor> memberAccessorMap) {
this.solutionClass = solutionClass;
if (solutionClass.getPackage() == null) {
LOGGER.warn("The solutionClass ({}) should be in a proper java package.", solutionClass);
}
this.memberAccessorFactory = new MemberAccessorFactory(memberAccessorMap);
}
public void addEntityDescriptor(EntityDescriptor<Solution_> entityDescriptor) {
var entityClass = entityDescriptor.getEntityClass();
for (var otherEntityClass : entityDescriptorMap.keySet()) {
if (entityClass.isAssignableFrom(otherEntityClass)) {
throw new IllegalArgumentException(
"An earlier entityClass (%s) should not be a subclass of a later entityClass (%s). Switch their declaration so superclasses are defined earlier."
.formatted(otherEntityClass, entityClass));
}
}
entityDescriptorMap.put(entityClass, entityDescriptor);
reversedEntityClassList.add(0, entityClass);
lowestEntityDescriptorMap.put(entityClass, entityDescriptor);
}
public void processUnannotatedFieldsAndMethods(DescriptorPolicy descriptorPolicy) {
processConstraintWeights(descriptorPolicy);
}
private void processConstraintWeights(DescriptorPolicy descriptorPolicy) {
for (var lineageClass : ConfigUtils.getAllParents(solutionClass)) {
var memberList = ConfigUtils.getDeclaredMembers(lineageClass);
var constraintWeightFieldList = memberList.stream()
.filter(member -> member instanceof Field field
&& ConstraintWeightOverrides.class.isAssignableFrom(field.getType()))
.map(f -> ((Field) f))
.toList();
switch (constraintWeightFieldList.size()) {
case 0:
break;
case 1:
if (constraintWeightSupplier != null) {
// The bottom-most class wins, they are parsed first due to ConfigUtil.getAllParents().
throw new IllegalStateException(
"The solutionClass (%s) has a field of type (%s) which was already found on its parent class."
.formatted(lineageClass, ConstraintWeightOverrides.class));
}
constraintWeightSupplier = OverridesBasedConstraintWeightSupplier.create(this, descriptorPolicy,
constraintWeightFieldList.get(0));
break;
default:
throw new IllegalStateException("The solutionClass (%s) has more than one field (%s) of type %s."
.formatted(solutionClass, constraintWeightFieldList, ConstraintWeightOverrides.class));
}
}
}
public void processAnnotations(DescriptorPolicy descriptorPolicy, List<Class<?>> entityClassList) {
domainAccessType = descriptorPolicy.getDomainAccessType();
processSolutionAnnotations(descriptorPolicy);
var potentiallyOverwritingMethodList = new ArrayList<Method>();
// Iterate inherited members too
var lineageClassList = ConfigUtils.getAllAnnotatedLineageClasses(solutionClass, PlanningSolution.class);
if (lineageClassList.isEmpty() && solutionClass.getSuperclass().isAnnotationPresent(PlanningSolution.class)) {
lineageClassList = ConfigUtils.getAllAnnotatedLineageClasses(solutionClass.getSuperclass(), PlanningSolution.class);
}
for (var lineageClass : lineageClassList) {
var memberList = ConfigUtils.getDeclaredMembers(lineageClass);
for (var member : memberList) {
if (member instanceof Method method && potentiallyOverwritingMethodList.stream().anyMatch(
m -> member.getName().equals(m.getName()) // Shortcut to discard negatives faster
&& ReflectionHelper.isMethodOverwritten(method, m.getDeclaringClass()))) {
// Ignore member because it is an overwritten method
continue;
}
processValueRangeProviderAnnotation(descriptorPolicy, member);
processFactEntityOrScoreAnnotation(descriptorPolicy, member, entityClassList);
}
potentiallyOverwritingMethodList.ensureCapacity(potentiallyOverwritingMethodList.size() + memberList.size());
memberList.stream().filter(Method.class::isInstance)
.forEach(member -> potentiallyOverwritingMethodList.add((Method) member));
}
if (entityCollectionMemberAccessorMap.isEmpty() && entityMemberAccessorMap.isEmpty()) {
throw new IllegalStateException(
"The solutionClass (%s) must have at least 1 member with a %s annotation or a %s annotation.".formatted(
solutionClass, PlanningEntityCollectionProperty.class.getSimpleName(),
PlanningEntityProperty.class.getSimpleName()));
}
// Do not check if problemFactCollectionMemberAccessorMap and problemFactMemberAccessorMap are empty
// because they are only required for ConstraintStreams.
if (scoreDescriptor == null) {
throw new IllegalStateException(
"""
The solutionClass (%s) must have 1 member with a @%s annotation.
Maybe add a getScore() method with a @%s annotation."""
.formatted(solutionClass, PlanningScore.class.getSimpleName(),
PlanningScore.class.getSimpleName()));
}
}
private void processSolutionAnnotations(DescriptorPolicy descriptorPolicy) {
var annotation = extractMostRelevantPlanningSolutionAnnotation();
autoDiscoverMemberType = annotation.autoDiscoverMemberType();
var solutionClonerClass = annotation.solutionCloner();
if (solutionClonerClass != PlanningSolution.NullSolutionCloner.class) {
solutionCloner = ConfigUtils.newInstance(this::toString, "solutionClonerClass", solutionClonerClass);
}
var lookUpStrategyType = annotation.lookUpStrategyType();
lookUpStrategyResolver =
new LookUpStrategyResolver(descriptorPolicy, lookUpStrategyType);
}
private @NonNull PlanningSolution extractMostRelevantPlanningSolutionAnnotation() {
var solutionAnnotation = solutionClass.getAnnotation(PlanningSolution.class);
if (solutionAnnotation != null) {
return solutionAnnotation;
}
var solutionSuperclass = solutionClass.getSuperclass(); // Null if interface.
if (solutionSuperclass == null) {
throw new IllegalStateException("""
The solutionClass (%s) has been specified as a solution in the configuration, \
but does not have a @%s annotation."""
.formatted(solutionClass.getCanonicalName(), PlanningSolution.class.getSimpleName()));
}
var parentSolutionAnnotation = solutionSuperclass.getAnnotation(PlanningSolution.class);
if (parentSolutionAnnotation == null) {
throw new IllegalStateException("""
The solutionClass (%s) has been specified as a solution in the configuration, \
but neither it nor its superclass (%s) have a @%s annotation."""
.formatted(solutionClass.getCanonicalName(), solutionSuperclass.getCanonicalName(),
PlanningSolution.class.getSimpleName()));
}
return parentSolutionAnnotation;
}
private void processValueRangeProviderAnnotation(DescriptorPolicy descriptorPolicy, Member member) {
if (((AnnotatedElement) member).isAnnotationPresent(ValueRangeProvider.class)) {
var memberAccessor = descriptorPolicy.getMemberAccessorFactory().buildAndCacheMemberAccessor(member,
FIELD_OR_READ_METHOD, ValueRangeProvider.class, descriptorPolicy.getDomainAccessType());
descriptorPolicy.addFromSolutionValueRangeProvider(memberAccessor);
}
}
private void processFactEntityOrScoreAnnotation(DescriptorPolicy descriptorPolicy,
Member member, List<Class<?>> entityClassList) {
var annotationClass = extractFactEntityOrScoreAnnotationClassOrAutoDiscover(
member, entityClassList);
if (annotationClass == null) {
return;
}
if (annotationClass.equals(ConstraintConfigurationProvider.class)) {
processConstraintConfigurationProviderAnnotation(descriptorPolicy, member, annotationClass);
} else if (annotationClass.equals(ProblemFactProperty.class)
|| annotationClass.equals(ProblemFactCollectionProperty.class)) {
processProblemFactPropertyAnnotation(descriptorPolicy, member, annotationClass);
} else if (annotationClass.equals(PlanningEntityProperty.class)
|| annotationClass.equals(PlanningEntityCollectionProperty.class)) {
processPlanningEntityPropertyAnnotation(descriptorPolicy, member, annotationClass);
} else if (annotationClass.equals(PlanningScore.class)) {
if (scoreDescriptor == null) {
// Bottom class wins. Bottom classes are parsed first due to ConfigUtil.getAllAnnotatedLineageClasses().
scoreDescriptor = descriptorPolicy.buildScoreDescriptor(member, solutionClass);
} else {
scoreDescriptor.failFastOnDuplicateMember(descriptorPolicy, member, solutionClass);
}
}
}
private Class<? extends Annotation> extractFactEntityOrScoreAnnotationClassOrAutoDiscover(
Member member, List<Class<?>> entityClassList) {
var annotationClass = ConfigUtils.extractAnnotationClass(member,
ConstraintConfigurationProvider.class,
ProblemFactProperty.class,
ProblemFactCollectionProperty.class,
PlanningEntityProperty.class, PlanningEntityCollectionProperty.class,
PlanningScore.class);
if (annotationClass == null) {
Class<?> type;
if (autoDiscoverMemberType == AutoDiscoverMemberType.FIELD
&& member instanceof Field field) {
type = field.getType();
} else if (autoDiscoverMemberType == AutoDiscoverMemberType.GETTER
&& (member instanceof Method method) && ReflectionHelper.isGetterMethod(method)) {
type = method.getReturnType();
} else {
type = null;
}
if (type != null) {
if (Score.class.isAssignableFrom(type)) {
annotationClass = PlanningScore.class;
} else if (Collection.class.isAssignableFrom(type) || type.isArray()) {
Class<?> elementType;
if (Collection.class.isAssignableFrom(type)) {
var genericType = (member instanceof Field f) ? f.getGenericType()
: ((Method) member).getGenericReturnType();
var memberName = member.getName();
if (!(genericType instanceof ParameterizedType)) {
throw new IllegalArgumentException(
"""
The solutionClass (%s) has a auto discovered member (%s) with a member type (%s) that returns a %s which has no generic parameters.
Maybe the member (%s) should return a typed %s."""
.formatted(solutionClass, memberName, type, Collection.class.getSimpleName(),
memberName, Collection.class.getSimpleName()));
}
elementType = ConfigUtils.extractGenericTypeParameter("solutionClass", solutionClass, type, genericType,
null, member.getName()).orElse(Object.class);
} else {
elementType = type.getComponentType();
}
if (entityClassList.stream().anyMatch(entityClass -> entityClass.isAssignableFrom(elementType))) {
annotationClass = PlanningEntityCollectionProperty.class;
} else if (elementType.isAnnotationPresent(ConstraintConfiguration.class)) {
throw new IllegalStateException(
"""
The autoDiscoverMemberType (%s) cannot accept a member (%s) of type (%s) with an elementType (%s) that has a @%s annotation.
Maybe use a member of the type (%s) directly instead of a %s or array of that type."""
.formatted(autoDiscoverMemberType, member, type, elementType,
ConstraintConfiguration.class.getSimpleName(), elementType,
Collection.class.getSimpleName()));
} else {
annotationClass = ProblemFactCollectionProperty.class;
}
} else if (Map.class.isAssignableFrom(type)) {
throw new IllegalStateException(
"The autoDiscoverMemberType (%s) does not yet support the member (%s) of type (%s) which is an implementation of %s."
.formatted(autoDiscoverMemberType, member, type, Map.class.getSimpleName()));
} else if (entityClassList.stream().anyMatch(entityClass -> entityClass.isAssignableFrom(type))) {
annotationClass = PlanningEntityProperty.class;
} else if (type.isAnnotationPresent(ConstraintConfiguration.class)) {
annotationClass = ConstraintConfigurationProvider.class;
} else {
annotationClass = ProblemFactProperty.class;
}
}
}
return annotationClass;
}
/**
* @deprecated {@link ConstraintConfiguration} was replaced by {@link ConstraintWeightOverrides}.
*/
@Deprecated(forRemoval = true, since = "1.13.0")
private void processConstraintConfigurationProviderAnnotation(DescriptorPolicy descriptorPolicy, Member member,
Class<? extends Annotation> annotationClass) {
if (constraintWeightSupplier != null) {
throw new IllegalStateException("""
The solution class (%s) has both a %s member and a %s-annotated member.
%s is deprecated, please remove it from your codebase and keep %s only."""
.formatted(solutionClass, ConstraintWeightOverrides.class.getSimpleName(),
ConstraintConfigurationProvider.class.getSimpleName(),
ConstraintConfigurationProvider.class.getSimpleName(),
ConstraintWeightOverrides.class.getSimpleName()));
}
var memberAccessor = descriptorPolicy.getMemberAccessorFactory().buildAndCacheMemberAccessor(member,
FIELD_OR_READ_METHOD, annotationClass, descriptorPolicy.getDomainAccessType());
if (constraintConfigurationMemberAccessor != null) {
if (!constraintConfigurationMemberAccessor.getName().equals(memberAccessor.getName())
|| !constraintConfigurationMemberAccessor.getClass().equals(memberAccessor.getClass())) {
throw new IllegalStateException(
"""
The solutionClass (%s) has a @%s annotated member (%s) that is duplicated by another member (%s).
Maybe the annotation is defined on both the field and its getter."""
.formatted(solutionClass, ConstraintConfigurationProvider.class.getSimpleName(), memberAccessor,
constraintConfigurationMemberAccessor));
}
// Bottom class wins. Bottom classes are parsed first due to ConfigUtil.getAllAnnotatedLineageClasses()
return;
}
assertNoFieldAndGetterDuplicationOrConflict(memberAccessor, annotationClass);
constraintConfigurationMemberAccessor = memberAccessor;
// Every ConstraintConfiguration is also a problem fact
problemFactMemberAccessorMap.put(memberAccessor.getName(), memberAccessor);
var constraintConfigurationClass = constraintConfigurationMemberAccessor.getType();
if (!constraintConfigurationClass.isAnnotationPresent(ConstraintConfiguration.class)) {
throw new IllegalStateException(
"The solutionClass (%s) has a @%s annotated member (%s) that does not return a class (%s) that has a %s annotation."
.formatted(solutionClass, ConstraintConfigurationProvider.class.getSimpleName(), member,
constraintConfigurationClass, ConstraintConfiguration.class.getSimpleName()));
}
constraintWeightSupplier =
ConstraintConfigurationBasedConstraintWeightSupplier.create(this, constraintConfigurationClass);
}
private void processProblemFactPropertyAnnotation(DescriptorPolicy descriptorPolicy, Member member,
Class<? extends Annotation> annotationClass) {
var memberAccessor = descriptorPolicy.getMemberAccessorFactory().buildAndCacheMemberAccessor(member,
FIELD_OR_READ_METHOD, annotationClass, descriptorPolicy.getDomainAccessType());
Class<?> problemFactType;
assertNoFieldAndGetterDuplicationOrConflict(memberAccessor, annotationClass);
if (annotationClass == ProblemFactProperty.class) {
problemFactMemberAccessorMap.put(memberAccessor.getName(), memberAccessor);
problemFactType = memberAccessor.getType();
} else if (annotationClass == ProblemFactCollectionProperty.class) {
var type = memberAccessor.getType();
if (!(Collection.class.isAssignableFrom(type) || type.isArray())) {
throw new IllegalStateException(
"The solutionClass (%s) has a @%s-annotated member (%s) that does not return a %s or an array."
.formatted(solutionClass, ProblemFactCollectionProperty.class.getSimpleName(), member,
Collection.class.getSimpleName()));
}
problemFactCollectionMemberAccessorMap.put(memberAccessor.getName(), memberAccessor);
if (type.isArray()) {
problemFactType = type.getComponentType();
} else {
problemFactType = ConfigUtils.extractGenericTypeParameterOrFail(PlanningSolution.class.getSimpleName(),
memberAccessor.getDeclaringClass(),
type, memberAccessor.getGenericType(), annotationClass, memberAccessor.getName());
}
} else {
throw new IllegalStateException("Impossible situation with annotationClass (" + annotationClass + ").");
}
if (problemFactType.isAnnotationPresent(PlanningEntity.class)) {
throw new IllegalStateException("""
The solutionClass (%s) has a @%s-annotated member (%s) that returns a @%s.
Maybe use @%s instead?"""
.formatted(solutionClass, annotationClass.getSimpleName(), memberAccessor.getName(),
PlanningEntity.class.getSimpleName(),
((annotationClass == ProblemFactProperty.class)
? PlanningEntityProperty.class.getSimpleName()
: PlanningEntityCollectionProperty.class.getSimpleName())));
}
}
private void processPlanningEntityPropertyAnnotation(DescriptorPolicy descriptorPolicy, Member member,
Class<? extends Annotation> annotationClass) {
var memberAccessor = descriptorPolicy.getMemberAccessorFactory().buildAndCacheMemberAccessor(member,
FIELD_OR_GETTER_METHOD, annotationClass, descriptorPolicy.getDomainAccessType());
assertNoFieldAndGetterDuplicationOrConflict(memberAccessor, annotationClass);
if (annotationClass == PlanningEntityProperty.class) {
entityMemberAccessorMap.put(memberAccessor.getName(), memberAccessor);
} else if (annotationClass == PlanningEntityCollectionProperty.class) {
var type = memberAccessor.getType();
if (!(Collection.class.isAssignableFrom(type) || type.isArray())) {
throw new IllegalStateException(
"The solutionClass (%s) has a @%s annotated member (%s) that does not return a %s or an array."
.formatted(solutionClass, PlanningEntityCollectionProperty.class.getSimpleName(), member,
Collection.class.getSimpleName()));
}
entityCollectionMemberAccessorMap.put(memberAccessor.getName(), memberAccessor);
} else {
throw new IllegalStateException("Impossible situation with annotationClass (" + annotationClass + ").");
}
}
private void assertNoFieldAndGetterDuplicationOrConflict(
MemberAccessor memberAccessor, Class<? extends Annotation> annotationClass) {
MemberAccessor duplicate;
Class<? extends Annotation> otherAnnotationClass;
var memberName = memberAccessor.getName();
if (constraintConfigurationMemberAccessor != null
&& constraintConfigurationMemberAccessor.getName().equals(memberName)) {
duplicate = constraintConfigurationMemberAccessor;
otherAnnotationClass = ConstraintConfigurationProvider.class;
} else if (problemFactMemberAccessorMap.containsKey(memberName)) {
duplicate = problemFactMemberAccessorMap.get(memberName);
otherAnnotationClass = ProblemFactProperty.class;
} else if (problemFactCollectionMemberAccessorMap.containsKey(memberName)) {
duplicate = problemFactCollectionMemberAccessorMap.get(memberName);
otherAnnotationClass = ProblemFactCollectionProperty.class;
} else if (entityMemberAccessorMap.containsKey(memberName)) {
duplicate = entityMemberAccessorMap.get(memberName);
otherAnnotationClass = PlanningEntityProperty.class;
} else if (entityCollectionMemberAccessorMap.containsKey(memberName)) {
duplicate = entityCollectionMemberAccessorMap.get(memberName);
otherAnnotationClass = PlanningEntityCollectionProperty.class;
} else {
return;
}
throw new IllegalStateException("""
The solutionClass (%s) has a @%s annotated member (%s) that is duplicated by a @%s annotated member (%s).
%s""".formatted(solutionClass, annotationClass.getSimpleName(), memberAccessor,
otherAnnotationClass.getSimpleName(),
duplicate, annotationClass.equals(otherAnnotationClass)
? "Maybe the annotation is defined on both the field and its getter."
: "Maybe 2 mutually exclusive annotations are configured."));
}
private void afterAnnotationsProcessed(DescriptorPolicy descriptorPolicy) {
for (var entityDescriptor : entityDescriptorMap.values()) {
entityDescriptor.linkEntityDescriptors(descriptorPolicy);
}
for (var entityDescriptor : entityDescriptorMap.values()) {
entityDescriptor.linkVariableDescriptors(descriptorPolicy);
}
determineGlobalShadowOrder();
problemFactOrEntityClassSet = collectEntityAndProblemFactClasses();
listVariableDescriptorList = findListVariableDescriptors();
validateListVariableDescriptors();
// And finally log the successful completion of processing.
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(" Model annotations parsed for solution {}:", solutionClass.getSimpleName());
for (var entry : entityDescriptorMap.entrySet()) {
var entityDescriptor = entry.getValue();
LOGGER.trace(" Entity {}:", entityDescriptor.getEntityClass().getSimpleName());
for (var variableDescriptor : entityDescriptor.getDeclaredVariableDescriptors()) {
LOGGER.trace(" {} variable {} ({})",
variableDescriptor instanceof GenuineVariableDescriptor ? "Genuine" : "Shadow",
variableDescriptor.getVariableName(),
variableDescriptor.getMemberAccessorSpeedNote());
}
}
}
initSolutionCloner(descriptorPolicy);
}
private void determineGlobalShadowOrder() {
// Topological sorting with Kahn's algorithm
var pairList = new ArrayList<MutablePair<ShadowVariableDescriptor<Solution_>, Integer>>();
var shadowToPairMap =
new HashMap<ShadowVariableDescriptor<Solution_>, MutablePair<ShadowVariableDescriptor<Solution_>, Integer>>();
for (var entityDescriptor : entityDescriptorMap.values()) {
for (var shadow : entityDescriptor.getDeclaredShadowVariableDescriptors()) {
var sourceSize = shadow.getSourceVariableDescriptorList().size();
var pair = MutablePair.of(shadow, sourceSize);
pairList.add(pair);
shadowToPairMap.put(shadow, pair);
}
}
for (var entityDescriptor : entityDescriptorMap.values()) {
for (var genuine : entityDescriptor.getDeclaredGenuineVariableDescriptors()) {
for (var sink : genuine.getSinkVariableDescriptorList()) {
var sinkPair = shadowToPairMap.get(sink);
sinkPair.setValue(sinkPair.getValue() - 1);
}
}
}
var globalShadowOrder = 0;
while (!pairList.isEmpty()) {
pairList.sort(Comparator.comparingInt(MutablePair::getValue));
var pair = pairList.remove(0);
var shadow = pair.getKey();
if (pair.getValue() != 0) {
if (pair.getValue() < 0) {
throw new IllegalStateException(
"Impossible state because the shadowVariable (%s) cannot be used more as a sink than it has sources."
.formatted(shadow.getSimpleEntityAndVariableName()));
}
throw new IllegalStateException(
"There is a cyclic shadow variable path that involves the shadowVariable (%s) because it must be later than its sources (%s) and also earlier than its sinks (%s)."
.formatted(shadow.getSimpleEntityAndVariableName(), shadow.getSourceVariableDescriptorList(),
shadow.getSinkVariableDescriptorList()));
}
for (var sink : shadow.getSinkVariableDescriptorList()) {
var sinkPair = shadowToPairMap.get(sink);
sinkPair.setValue(sinkPair.getValue() - 1);
}
shadow.setGlobalShadowOrder(globalShadowOrder);
globalShadowOrder++;
}
}
private void validateListVariableDescriptors() {
if (listVariableDescriptorList.isEmpty()) {
return;
}
if (listVariableDescriptorList.size() > 1) {
throw new UnsupportedOperationException(
"Defining multiple list variables (%s) across the model is currently not supported."
.formatted(listVariableDescriptorList));
}
var listVariableDescriptor = listVariableDescriptorList.get(0);
var listVariableEntityDescriptor = listVariableDescriptor.getEntityDescriptor();
// We will not support chained and list variables at the same entity,
// and the validation can be removed once we discontinue support for chained variables.
if (hasChainedVariable()) {
var basicVariableDescriptorList = new ArrayList<>(listVariableEntityDescriptor.getGenuineVariableDescriptorList());
basicVariableDescriptorList.remove(listVariableDescriptor);
throw new UnsupportedOperationException(
"Combining chained variables (%s) with list variables (%s) on a single planning entity (%s) is not supported."
.formatted(basicVariableDescriptorList, listVariableDescriptor,
listVariableDescriptor.getEntityDescriptor().getEntityClass().getCanonicalName()));
}
}
private Set<Class<?>> collectEntityAndProblemFactClasses() {
// Figure out all problem fact or entity types that are used within this solution,
// using the knowledge we've already gained by processing all the annotations.
var entityClassStream = entityDescriptorMap.keySet()
.stream();
var factClassStream = problemFactMemberAccessorMap
.values()
.stream()
.map(MemberAccessor::getType);
var problemFactOrEntityClassStream = concat(entityClassStream, factClassStream);
var factCollectionClassStream = problemFactCollectionMemberAccessorMap.values()
.stream()
.map(accessor -> ConfigUtils
.extractGenericTypeParameter("solutionClass", getSolutionClass(), accessor.getType(),
accessor.getGenericType(), ProblemFactCollectionProperty.class, accessor.getName())
.orElse(Object.class));
problemFactOrEntityClassStream = concat(problemFactOrEntityClassStream, factCollectionClassStream);
// Add constraint configuration, if configured.
if (constraintWeightSupplier != null) {
problemFactOrEntityClassStream = concat(problemFactOrEntityClassStream,
Stream.of(constraintWeightSupplier.getProblemFactClass()));
}
return problemFactOrEntityClassStream.collect(Collectors.toSet());
}
private List<ListVariableDescriptor<Solution_>> findListVariableDescriptors() {
return getGenuineEntityDescriptors().stream()
.map(EntityDescriptor::getGenuineVariableDescriptorList)
.flatMap(Collection::stream)
.filter(VariableDescriptor::isListVariable)
.map(variableDescriptor -> ((ListVariableDescriptor<Solution_>) variableDescriptor))
.toList();
}
private void initSolutionCloner(DescriptorPolicy descriptorPolicy) {
solutionCloner = solutionCloner == null ? descriptorPolicy.getGeneratedSolutionClonerMap()
.get(GizmoSolutionClonerFactory.getGeneratedClassName(this))
: solutionCloner;
if (solutionCloner instanceof GizmoSolutionCloner<Solution_> gizmoSolutionCloner) {
gizmoSolutionCloner.setSolutionDescriptor(this);
}
if (solutionCloner == null) {
switch (descriptorPolicy.getDomainAccessType()) {
case GIZMO:
solutionCloner = GizmoSolutionClonerFactory.build(this, memberAccessorFactory.getGizmoClassLoader());
break;
case REFLECTION:
solutionCloner = new FieldAccessingSolutionCloner<>(this);
break;
default:
throw new IllegalStateException("The domainAccessType (" + domainAccessType
+ ") is not implemented.");
}
}
}
public Class<Solution_> getSolutionClass() {
return solutionClass;
}
public MemberAccessorFactory getMemberAccessorFactory() {
return memberAccessorFactory;
}
public DomainAccessType getDomainAccessType() {
return domainAccessType;
}
public <Score_ extends Score<Score_>> ScoreDefinition<Score_> getScoreDefinition() {
return this.<Score_> getScoreDescriptor().getScoreDefinition();
}
@SuppressWarnings("unchecked")
public <Score_ extends Score<Score_>> ScoreDescriptor<Score_> getScoreDescriptor() {
return (ScoreDescriptor<Score_>) scoreDescriptor;
}
public Map<String, MemberAccessor> getProblemFactMemberAccessorMap() {
return problemFactMemberAccessorMap;
}
public Map<String, MemberAccessor> getProblemFactCollectionMemberAccessorMap() {
return problemFactCollectionMemberAccessorMap;
}
public Map<String, MemberAccessor> getEntityMemberAccessorMap() {
return entityMemberAccessorMap;
}
public Map<String, MemberAccessor> getEntityCollectionMemberAccessorMap() {
return entityCollectionMemberAccessorMap;
}
public Set<Class<?>> getProblemFactOrEntityClassSet() {
return problemFactOrEntityClassSet;
}
public ListVariableDescriptor<Solution_> getListVariableDescriptor() {
return listVariableDescriptorList.isEmpty() ? null : listVariableDescriptorList.get(0);
}
public SolutionCloner<Solution_> getSolutionCloner() {
return solutionCloner;
}
// ************************************************************************
// Model methods
// ************************************************************************
public PlanningSolutionMetaModel<Solution_> getMetaModel() {
if (planningSolutionMetaModel == null) {
var metaModel = new DefaultPlanningSolutionMetaModel<>(this);
for (var entityDescriptor : getEntityDescriptors()) {
var entityMetaModel = new DefaultPlanningEntityMetaModel<>(metaModel, entityDescriptor);
for (var variableDescriptor : entityDescriptor.getGenuineVariableDescriptorList()) {
if (variableDescriptor.isListVariable()) {
var listVariableDescriptor = (ListVariableDescriptor<Solution_>) variableDescriptor;
var listVariableMetaModel = new DefaultPlanningListVariableMetaModel<>(entityMetaModel,
listVariableDescriptor);
entityMetaModel.addVariable(listVariableMetaModel);
} else {
var basicVariableDescriptor = (BasicVariableDescriptor<Solution_>) variableDescriptor;
var basicVariableMetaModel =
new DefaultPlanningVariableMetaModel<>(entityMetaModel, basicVariableDescriptor);
entityMetaModel.addVariable(basicVariableMetaModel);
}
}
for (var shadowVariableDescriptor : entityDescriptor.getShadowVariableDescriptors()) {
var shadowVariableMetaModel =
new DefaultShadowVariableMetaModel<>(entityMetaModel, shadowVariableDescriptor);
entityMetaModel.addVariable(shadowVariableMetaModel);
}
metaModel.addEntity(entityMetaModel);
}
this.planningSolutionMetaModel = metaModel;
}
return planningSolutionMetaModel;
}
public List<BasicVariableDescriptor<Solution_>> getBasicVariableDescriptorList() {
return getGenuineEntityDescriptors().stream()
.flatMap(entityDescriptor -> entityDescriptor.getGenuineBasicVariableDescriptorList().stream())
.map(descriptor -> (BasicVariableDescriptor<Solution_>) descriptor)
.toList();
}
public boolean hasBasicVariable() {
return !getBasicVariableDescriptorList().isEmpty();
}
public boolean hasChainedVariable() {
return getGenuineEntityDescriptors().stream().anyMatch(EntityDescriptor::hasAnyGenuineChainedVariables);
}
public boolean hasListVariable() {
return getListVariableDescriptor() != null;
}
public boolean hasBothBasicAndListVariables() {
return hasBasicVariable() && hasListVariable();
}
/**
* @deprecated {@link ConstraintConfiguration} was replaced by {@link ConstraintWeightOverrides}.
*/
@Deprecated(forRemoval = true, since = "1.13.0")
public MemberAccessor getConstraintConfigurationMemberAccessor() {
return constraintConfigurationMemberAccessor;
}
@SuppressWarnings("unchecked")
public <Score_ extends Score<Score_>> ConstraintWeightSupplier<Solution_, Score_> getConstraintWeightSupplier() {
return (ConstraintWeightSupplier<Solution_, Score_>) constraintWeightSupplier;
}
public Set<Class<?>> getEntityClassSet() {
return entityDescriptorMap.keySet();
}
public Collection<EntityDescriptor<Solution_>> getEntityDescriptors() {
return entityDescriptorMap.values();
}
public Collection<EntityDescriptor<Solution_>> getGenuineEntityDescriptors() {
var genuineEntityDescriptorList = new ArrayList<EntityDescriptor<Solution_>>(entityDescriptorMap.size());
for (var entityDescriptor : entityDescriptorMap.values()) {
if (entityDescriptor.hasAnyDeclaredGenuineVariableDescriptor()) {
genuineEntityDescriptorList.add(entityDescriptor);
}
}
return genuineEntityDescriptorList;
}
public EntityDescriptor<Solution_> getEntityDescriptorStrict(Class<?> entityClass) {
return entityDescriptorMap.get(entityClass);
}
public boolean hasEntityDescriptor(Class<?> entitySubclass) {
var entityDescriptor = findEntityDescriptor(entitySubclass);
return entityDescriptor != null;
}
public EntityDescriptor<Solution_> findEntityDescriptorOrFail(Class<?> entitySubclass) {
var entityDescriptor = findEntityDescriptor(entitySubclass);
if (entityDescriptor == null) {
throw new IllegalArgumentException(
"""
A planning entity is an instance of a class (%s) that is not configured as a planning entity class (%s).
If that class (%s) (or superclass thereof) is not a @%s annotated class, maybe your @%s annotated class has an incorrect @%s or @%s annotated member.
Otherwise, if you're not using the Quarkus extension or Spring Boot starter, maybe that entity class (%s) is missing from your solver configuration."""
.formatted(entitySubclass, getEntityClassSet(), entitySubclass.getSimpleName(),
PlanningEntity.class.getSimpleName(), PlanningSolution.class.getSimpleName(),
PlanningEntityCollectionProperty.class.getSimpleName(),
PlanningEntityProperty.class.getSimpleName(), entitySubclass.getSimpleName()));
}
return entityDescriptor;
}
public EntityDescriptor<Solution_> findEntityDescriptor(Class<?> entitySubclass) {
/*
* A slightly optimized variant of map.computeIfAbsent(...).
* computeIfAbsent(...) would require the creation of a capturing lambda every time this method is called,
* which is created, executed once, and immediately thrown away.
* This is a micro-optimization, but it is valuable on the hot path.
*/
var cachedEntityDescriptor = lowestEntityDescriptorMap.get(entitySubclass);
if (cachedEntityDescriptor == NULL_ENTITY_DESCRIPTOR) { // Cache hit, no descriptor found.
return null;
} else if (cachedEntityDescriptor != null) { // Cache hit, descriptor found.
return cachedEntityDescriptor;
}
// Cache miss, look for the descriptor.
var newEntityDescriptor = innerFindEntityDescriptor(entitySubclass);
if (newEntityDescriptor == null) {
// Dummy entity descriptor value, as ConcurrentMap does not allow null values.
lowestEntityDescriptorMap.put(entitySubclass, (EntityDescriptor<Solution_>) NULL_ENTITY_DESCRIPTOR);
return null;
} else {
lowestEntityDescriptorMap.put(entitySubclass, newEntityDescriptor);
return newEntityDescriptor;
}
}
private EntityDescriptor<Solution_> innerFindEntityDescriptor(Class<?> entitySubclass) {
// Reverse order to find the nearest ancestor
for (var entityClass : reversedEntityClassList) {
if (entityClass.isAssignableFrom(entitySubclass)) {
return entityDescriptorMap.get(entityClass);
}
}
return null;
}
public VariableDescriptor<Solution_> findVariableDescriptorOrFail(Object entity, String variableName) {
var entityDescriptor = findEntityDescriptorOrFail(entity.getClass());
var variableDescriptor = entityDescriptor.getVariableDescriptor(variableName);
if (variableDescriptor == null) {
throw new IllegalArgumentException(entityDescriptor.buildInvalidVariableNameExceptionMessage(variableName));
}
return variableDescriptor;
}
// ************************************************************************
// Look up methods
// ************************************************************************
public LookUpStrategyResolver getLookUpStrategyResolver() {
return lookUpStrategyResolver;
}
// ************************************************************************
// Extraction methods
// ************************************************************************
public Collection<Object> getAllEntitiesAndProblemFacts(Solution_ solution) {
var facts = new ArrayList<>();
visitAll(solution, facts::add);
return facts;
}
/**
* @param solution never null
* @return {@code >= 0}
*/
public int getGenuineEntityCount(Solution_ solution) {
var entityCount = new MutableInt();
// Need to go over every element in every entity collection, as some of the entities may not be genuine.
visitAllEntities(solution, fact -> {
var entityDescriptor = findEntityDescriptorOrFail(fact.getClass());
if (entityDescriptor.isGenuine()) {
entityCount.increment();
}
});
return entityCount.intValue();
}
/**
* Return accessor for a given member of a given class, if present,
* and cache it for future use.
*
* @param factClass never null
* @return null if no such member exists
*/
public MemberAccessor getPlanningIdAccessor(Class<?> factClass) {
var memberAccessor = planningIdMemberAccessorMap.get(factClass);
if (memberAccessor == null) {
memberAccessor =
ConfigUtils.findPlanningIdMemberAccessor(factClass, getMemberAccessorFactory(), getDomainAccessType());
var nonNullMemberAccessor = Objects.requireNonNullElse(memberAccessor, DummyMemberAccessor.INSTANCE);
planningIdMemberAccessorMap.put(factClass, nonNullMemberAccessor);
return memberAccessor;
} else if (memberAccessor == DummyMemberAccessor.INSTANCE) {
return null;
} else {
return memberAccessor;
}
}
public void visitAllEntities(Solution_ solution, Consumer<Object> visitor) {
visitAllEntities(solution, visitor, collection -> collection.forEach(visitor));
}
private void visitAllEntities(Solution_ solution, Consumer<Object> visitor,
Consumer<Collection<Object>> collectionVisitor) {
for (var entityMemberAccessor : entityMemberAccessorMap.values()) {
var entity = extractMemberObject(entityMemberAccessor, solution);
if (entity != null) {
visitor.accept(entity);
}
}
for (var entityCollectionMemberAccessor : entityCollectionMemberAccessorMap.values()) {
var entityCollection = extractMemberCollectionOrArray(entityCollectionMemberAccessor, solution, false);
collectionVisitor.accept(entityCollection);
}
}
/**
*
* @param solution solution to extract the entities from
* @param entityClass class of the entity to be visited, including subclasses
* @param visitor never null; applied to every entity, iteration stops if it returns true
*/
public void visitEntitiesByEntityClass(Solution_ solution, Class<?> entityClass, Predicate<Object> visitor) {
for (var entityMemberAccessor : entityMemberAccessorMap.values()) {
var entity = extractMemberObject(entityMemberAccessor, solution);
if (entityClass.isInstance(entity) && visitor.test(entity)) {
return;
}
}
for (var entityCollectionMemberAccessor : entityCollectionMemberAccessorMap.values()) {
var optionalTypeParameter = ConfigUtils.extractGenericTypeParameter("solutionClass",
entityCollectionMemberAccessor.getDeclaringClass(), entityCollectionMemberAccessor.getType(),
entityCollectionMemberAccessor.getGenericType(), null, entityCollectionMemberAccessor.getName());
boolean collectionGuaranteedToContainOnlyGivenEntityType = optionalTypeParameter
.map(entityClass::isAssignableFrom)
.orElse(false);
if (collectionGuaranteedToContainOnlyGivenEntityType) {
/*
* In a typical case typeParameter is specified and it is the expected entity or its superclass.
* Therefore we can simply apply the visitor on each element.
*/
var entityCollection = extractMemberCollectionOrArray(entityCollectionMemberAccessor, solution, false);
for (var o : entityCollection) {
if (visitor.test(o)) {
return;
}
}
continue;
}
// The collection now is either raw, or it is not of an entity type, such as perhaps a parent interface.
boolean collectionCouldPossiblyContainGivenEntityType = optionalTypeParameter
.map(e -> e.isAssignableFrom(entityClass))
.orElse(true);
if (!collectionCouldPossiblyContainGivenEntityType) {
// There is no way how this collection could possibly contain entities of the given type.
continue;
}
// We need to go over every collection member and check if it is an entity of the given type.
var entityCollection = extractMemberCollectionOrArray(entityCollectionMemberAccessor, solution, false);
for (var entity : entityCollection) {
if (entityClass.isInstance(entity) && visitor.test(entity)) {
return;
}
}
}
}
public void visitAllProblemFacts(Solution_ solution, Consumer<Object> visitor) {
// Visits facts.
for (var accessor : problemFactMemberAccessorMap.values()) {
var object = extractMemberObject(accessor, solution);
if (object != null) {
visitor.accept(object);
}
}
// Visits problem facts from problem fact collections.
for (var accessor : problemFactCollectionMemberAccessorMap.values()) {
var objects = extractMemberCollectionOrArray(accessor, solution, true);
for (var object : objects) {
visitor.accept(object);
}
}
}
public void visitAll(Solution_ solution, Consumer<Object> visitor) {
visitAllProblemFacts(solution, visitor);
visitAllEntities(solution, visitor);
}
/**
* @param scoreDirector never null
* @return {@code >= 0}
*/
public boolean hasMovableEntities(ScoreDirector<Solution_> scoreDirector) {
var workingSolution = scoreDirector.getWorkingSolution();
return extractAllEntitiesStream(workingSolution)
.anyMatch(entity -> findEntityDescriptorOrFail(entity.getClass()).isMovable(workingSolution, entity));
}
/**
* @param solution never null
* @return {@code >= 0}
*/
public long getGenuineVariableCount(Solution_ solution) {
var result = new MutableLong();
visitAllEntities(solution, entity -> {
var entityDescriptor = findEntityDescriptorOrFail(entity.getClass());
if (entityDescriptor.isGenuine()) {
result.add(entityDescriptor.getGenuineVariableCount());
}
});
return result.longValue();
}
public List<ShadowVariableDescriptor<Solution_>> getAllShadowVariableDescriptors() {
var out = new ArrayList<ShadowVariableDescriptor<Solution_>>();
for (var entityDescriptor : entityDescriptorMap.values()) {
out.addAll(entityDescriptor.getShadowVariableDescriptors());
}
return out;
}
public int getValueRangeDescriptorCount() {
var count = 0;
for (var entityDescriptor : entityDescriptorMap.values()) {
count += entityDescriptor.getValueRangeCount();
}
return count;
}
public List<DeclarativeShadowVariableDescriptor<Solution_>> getDeclarativeShadowVariableDescriptors() {
var out = new HashSet<DeclarativeShadowVariableDescriptor<Solution_>>();
for (var entityDescriptor : entityDescriptorMap.values()) {
entityDescriptor.getShadowVariableDescriptors();
for (var shadowVariableDescriptor : entityDescriptor.getShadowVariableDescriptors()) {
if (shadowVariableDescriptor instanceof DeclarativeShadowVariableDescriptor<Solution_> declarativeShadowVariableDescriptor) {
out.add(declarativeShadowVariableDescriptor);
}
}
}
return new ArrayList<>(out);
}
public Stream<Object> extractAllEntitiesStream(Solution_ solution) {
var stream = Stream.empty();
for (var memberAccessor : entityMemberAccessorMap.values()) {
var entity = extractMemberObject(memberAccessor, solution);
if (entity != null) {
stream = concat(stream, Stream.of(entity));
}
}
for (var memberAccessor : entityCollectionMemberAccessorMap.values()) {
var entityCollection = extractMemberCollectionOrArray(memberAccessor, solution, false);
stream = concat(stream, entityCollection.stream());
}
return stream;
}
private Object extractMemberObject(MemberAccessor memberAccessor, Solution_ solution) {
return memberAccessor.executeGetter(solution);
}
private Collection<Object> extractMemberCollectionOrArray(MemberAccessor memberAccessor, Solution_ solution,
boolean isFact) {
Collection<Object> collection;
if (memberAccessor.getType().isArray()) {
var arrayObject = memberAccessor.executeGetter(solution);
collection = ReflectionHelper.transformArrayToList(arrayObject);
} else {
collection = (Collection<Object>) memberAccessor.executeGetter(solution);
}
if (collection == null) {
throw new IllegalArgumentException(
"""
The solutionClass (%s)'s %s (%s) should never return null.
%sMaybe that property (%s) was set with null instead of an empty collection/array when the class (%s) instance was created."""
.formatted(solutionClass, isFact ? "factCollectionProperty" : "entityCollectionProperty",
memberAccessor, memberAccessor instanceof ReflectionFieldMemberAccessor ? ""
: "Maybe the getter/method always returns null instead of the actual data.\n",
memberAccessor.getName(), solutionClass.getSimpleName()));
}
return collection;
}
/**
* @param solution never null
* @return sometimes null, if the {@link Score} hasn't been calculated yet
*/
public <Score_ extends Score<Score_>> Score_ getScore(Solution_ solution) {
return this.<Score_> getScoreDescriptor().getScore(solution);
}
/**
* Called when the {@link Score} has been calculated or predicted.
*
* @param solution never null
* @param score sometimes null, in rare occasions to indicate that the old {@link Score} is stale,
* but no new ones has been calculated
*/
public <Score_ extends Score<Score_>> void setScore(Solution_ solution, Score_ score) {
this.<Score_> getScoreDescriptor().setScore(solution, score);
}
public PlanningSolutionDiff<Solution_> diff(Solution_ oldSolution, Solution_ newSolution) {
// Genuine entities first, then sort by class name.
var oldEntities = sortEntitiesForDiff(oldSolution);
var newEntities = sortEntitiesForDiff(newSolution);
var removedOldEntities = new LinkedHashSet<>(oldEntities.size());
var oldToNewEntities = new LinkedHashMap<>(newEntities.size());
for (var entry : oldEntities.entrySet()) {
var entityClassName = entry.getKey();
for (var oldEntity : entry.getValue()) {
var newEntity = newEntities.getOrDefault(entityClassName, Collections.emptySet())
.stream()
.filter(e -> Objects.equals(e, oldEntity))
.findFirst()
.orElse(null);
if (newEntity == null) {
removedOldEntities.add(oldEntity);
} else {
oldToNewEntities.put(oldEntity, newEntity);
}
}
}
var addedNewEntities = newEntities.values().stream()
.flatMap(Collection::stream)
.filter(newEntity -> !oldToNewEntities.containsValue(newEntity))
.collect(Collectors.toCollection(LinkedHashSet::new));
// Genuine variables first, then sort by ordinal.
var variableDescriptorComparator = Comparator.<VariableDescriptor<Solution_>, String> comparing(
variableDescriptor -> variableDescriptor instanceof GenuineVariableDescriptor<Solution_> ? "0" : "1")
.thenComparingInt(VariableDescriptor::getOrdinal);
var solutionDiff = new DefaultPlanningSolutionDiff<>(getMetaModel(), oldSolution, newSolution, removedOldEntities,
addedNewEntities);
for (var entry : oldToNewEntities.entrySet()) {
var oldEntity = entry.getKey();
var newEntity = entry.getValue();
var entityDescriptor = findEntityDescriptorOrFail(oldEntity.getClass());
var entityDiff = new DefaultPlanningEntityDiff<>(solutionDiff, entry.getKey());
entityDescriptor.getVariableDescriptorMap().values().stream()
.sorted(variableDescriptorComparator)
.flatMap(variableDescriptor -> {
var oldValue = variableDescriptor.getValue(oldEntity);
var newValue = variableDescriptor.getValue(newEntity);
if (Objects.equals(oldValue, newValue)) {
return Stream.empty();
}
var variableMetaModel = entityDiff.entityMetaModel().variable(variableDescriptor.getVariableName());
var variableDiff = new DefaultPlanningVariableDiff<>(entityDiff, variableMetaModel, oldValue, newValue);
return Stream.of(variableDiff);
}).forEach(entityDiff::addVariableDiff);
if (!entityDiff.variableDiffs().isEmpty()) {
solutionDiff.addEntityDiff(entityDiff);
}
}
return solutionDiff;
}
private SortedMap<String, Set<Object>> sortEntitiesForDiff(Solution_ solution) {
return getEntityDescriptors().stream()
.map(descriptor -> descriptor.extractEntities(solution))
.flatMap(Collection::stream)
// TreeMap and LinkedHashSet for fully reproducible ordering of entities and variables.
.collect(Collectors.groupingBy(s -> s.getClass().getCanonicalName(), TreeMap::new,
Collectors.toCollection(LinkedHashSet::new)));
}
@Override
public String toString() {
return "%s(%s)".formatted(getClass().getSimpleName(), solutionClass.getName());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/solution/mutation/MutationCounter.java | package ai.timefold.solver.core.impl.domain.solution.mutation;
import java.util.Iterator;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
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.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class MutationCounter<Solution_> {
protected final SolutionDescriptor<Solution_> solutionDescriptor;
public MutationCounter(SolutionDescriptor<Solution_> solutionDescriptor) {
this.solutionDescriptor = solutionDescriptor;
}
/**
*
* @param a never null
* @param b never null
* @return {@code >= 0}, the number of planning variables that have a different value in {@code a} and {@code b}.
*/
public int countMutations(Solution_ a, Solution_ b) {
int mutationCount = 0;
for (EntityDescriptor<Solution_> entityDescriptor : solutionDescriptor.getGenuineEntityDescriptors()) {
List<Object> aEntities = entityDescriptor.extractEntities(a);
List<Object> bEntities = entityDescriptor.extractEntities(b);
for (Iterator<Object> aIt = aEntities.iterator(), bIt = bEntities.iterator(); aIt.hasNext() && bIt.hasNext();) {
Object aEntity = aIt.next();
Object bEntity = bIt.next();
for (GenuineVariableDescriptor<Solution_> variableDescriptor : entityDescriptor
.getGenuineVariableDescriptorList()) {
if (variableDescriptor.isListVariable()) {
ListVariableDescriptor<Solution_> listVariableDescriptor =
(ListVariableDescriptor<Solution_>) variableDescriptor;
List<Object> aValues = listVariableDescriptor.getValue(aEntity);
List<Object> bValues = listVariableDescriptor.getValue(bEntity);
int aSize = aValues.size();
int bSize = bValues.size();
if (aSize != bSize) {
// First add mutations for the elements that are missing in one list.
mutationCount += Math.abs(aSize - bSize);
}
// Then iterate over the list and count every item that is different.
int shorterListSize = Math.min(aSize, bSize);
for (int i = 0; i < shorterListSize; i++) {
Object aValue = aValues.get(i);
Object bValue = bValues.get(i);
if (areDifferent(aValue, bValue)) {
mutationCount++;
}
}
} else {
Object aValue = variableDescriptor.getValue(aEntity);
Object bValue = variableDescriptor.getValue(bEntity);
if (areDifferent(aValue, bValue)) {
mutationCount++;
}
}
}
}
if (aEntities.size() != bEntities.size()) {
mutationCount += Math.abs(aEntities.size() - bEntities.size())
* entityDescriptor.getGenuineVariableDescriptorList().size();
}
}
return mutationCount;
}
private boolean areDifferent(Object aValue, Object bValue) {
EntityDescriptor<Solution_> aValueEntityDescriptor =
solutionDescriptor.findEntityDescriptor(aValue.getClass());
EntityDescriptor<Solution_> bValueEntityDescriptor =
solutionDescriptor.findEntityDescriptor(bValue.getClass());
if (aValueEntityDescriptor == null && bValueEntityDescriptor == null) { // Neither are entities.
if (aValue == bValue) {
return false;
}
return areDifferentPlanningIds(aValue, bValue);
} else if (aValueEntityDescriptor != null && bValueEntityDescriptor != null) {
/*
* Both are entities.
* Entities will all be cloned and therefore different.
* But maybe they have the same planning ID?
*/
if (aValueEntityDescriptor != bValueEntityDescriptor) {
// Different entities means mutation guaranteed.
return true;
}
return areDifferentPlanningIds(aValue, bValue);
} else { // One is entity and the other one is not.
return true;
}
}
private boolean areDifferentPlanningIds(Object aValue, Object bValue) {
MemberAccessor aIdAccessor = solutionDescriptor.getPlanningIdAccessor(aValue.getClass());
MemberAccessor bIdAccessor = solutionDescriptor.getPlanningIdAccessor(bValue.getClass());
if (aIdAccessor != null && bIdAccessor != null) {
Object aId = aIdAccessor.executeGetter(aValue);
Object bId = bIdAccessor.executeGetter(bValue);
return !aId.equals(bId);
} else {
return aValue != bValue; // This counts all entities that get as far as here.
}
}
@Override
public String toString() {
return "MutationCounter(" + solutionDescriptor + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/AbstractCountableValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange;
import java.time.OffsetDateTime;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeFactory;
/**
* Abstract superclass for {@link CountableValueRange} (and therefore {@link ValueRange}).
*
* @see CountableValueRange
* @see ValueRange
* @see ValueRangeFactory
*/
public abstract class AbstractCountableValueRange<T> implements CountableValueRange<T> {
/**
* Certain optimizations can be applied if {@link Object#equals(Object)} can be relied upon
* to determine that two objects are the same.
* Typically, this is not guaranteed for user-provided objects,
* but is true for many builtin types and classes,
* such as {@link String}, {@link Integer}, {@link OffsetDateTime}, etc.
*
* @return true if we should trust {@link Object#equals(Object)} in this value range
*/
public boolean isValueImmutable() {
return true; // Override in subclasses if needed.
}
@Override
public boolean isEmpty() {
return getSize() == 0L;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/AbstractUncountableValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeFactory;
/**
* Abstract superclass for {@link ValueRange} that is not a {@link CountableValueRange}).
*
* @see ValueRange
* @see ValueRangeFactory
* @deprecated Uncountable value ranges were never fully supported in many places throughout the solver
* and therefore never gained traction.
* Use {@link CountableValueRange} instead, and configure a step.
*/
@Deprecated(forRemoval = true, since = "1.1.0")
public abstract class AbstractUncountableValueRange<T> implements ValueRange<T> {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/ValueRangeCache.java | package ai.timefold.solver.core.impl.domain.valuerange;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.CachedListRandomIterator;
import ai.timefold.solver.core.impl.util.CollectionUtils;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/**
* Instances should be created using the {@link Builder} enum.
*
* @param <Value_>
*/
@NullMarked
public final class ValueRangeCache<Value_>
implements Iterable<Value_> {
private final List<Value_> valuesWithFastRandomAccess;
private final Set<Value_> valuesWithFastLookup;
private ValueRangeCache(int size, Set<Value_> emptyCacheSet) {
this.valuesWithFastRandomAccess = new ArrayList<>(size);
this.valuesWithFastLookup = emptyCacheSet;
}
private ValueRangeCache(Collection<Value_> collection, Set<Value_> emptyCacheSet) {
this.valuesWithFastRandomAccess = new ArrayList<>(collection);
this.valuesWithFastLookup = emptyCacheSet;
this.valuesWithFastLookup.addAll(valuesWithFastRandomAccess);
}
public void add(@Nullable Value_ value) {
if (valuesWithFastLookup.add(value)) {
valuesWithFastRandomAccess.add(value);
}
}
public Value_ get(int index) {
if (index < 0 || index >= valuesWithFastRandomAccess.size()) {
throw new IndexOutOfBoundsException("Index: %d, Size: %d".formatted(index, valuesWithFastRandomAccess.size()));
}
return valuesWithFastRandomAccess.get(index);
}
public boolean contains(@Nullable Value_ value) {
return valuesWithFastLookup.contains(value);
}
public long getSize() {
return valuesWithFastRandomAccess.size();
}
/**
* Iterates in original order of the values as provided, terminates when the last value is reached.
*/
public Iterator<Value_> iterator() {
return valuesWithFastRandomAccess.iterator();
}
/**
* Iterates in random order, does not terminate.
*/
public Iterator<Value_> iterator(Random workingRandom) {
return new CachedListRandomIterator<>(valuesWithFastRandomAccess, workingRandom);
}
public enum Builder {
/**
* Use when {@link #FOR_TRUSTED_VALUES} is not suitable.
*/
FOR_USER_VALUES {
@Override
public <Value_> ValueRangeCache<Value_> buildCache(int size) {
return new ValueRangeCache<>(size, CollectionUtils.newIdentityHashSet(size));
}
@Override
public <Value_> ValueRangeCache<Value_> buildCache(Collection<Value_> collection) {
return new ValueRangeCache<>(collection, CollectionUtils.newIdentityHashSet(collection.size()));
}
},
/**
* For types where we can trust that {@link Object#equals(Object)} means
* that if two objects are equal, they are the same object.
* For example, this is the case for {@link String}, {@link Number}, {@link OffsetDateTime}
* and many other JDK types.
* It is not guaranteed to be the case for user-defined types,
* which is when {@link #FOR_USER_VALUES} should be used instead.
*/
FOR_TRUSTED_VALUES {
@Override
public <Value_> ValueRangeCache<Value_> buildCache(int size) {
return new ValueRangeCache<>(size, CollectionUtils.newHashSet(size));
}
@Override
public <Value_> ValueRangeCache<Value_> buildCache(Collection<Value_> collection) {
return new ValueRangeCache<>(collection, CollectionUtils.newHashSet(collection.size()));
}
};
public abstract <Value_> ValueRangeCache<Value_> buildCache(int size);
public abstract <Value_> ValueRangeCache<Value_> buildCache(Collection<Value_> collection);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/EmptyValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/**
* Special range for empty value ranges.
*/
@NullMarked
public final class EmptyValueRange<T> extends AbstractCountableValueRange<T> {
private static final EmptyValueRange<Object> INSTANCE = new EmptyValueRange<>();
@SuppressWarnings("unchecked")
public static <T> EmptyValueRange<T> instance() {
return (EmptyValueRange<T>) INSTANCE;
}
private EmptyValueRange() {
// Intentionally empty
}
@Override
public long getSize() {
return 0;
}
@Override
public @Nullable T get(long index) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
@Override
public @NonNull Iterator<T> createOriginalIterator() {
return (Iterator<T>) EmptyIterator.INSTANCE;
}
@Override
public boolean contains(@Nullable T value) {
return false;
}
@SuppressWarnings("unchecked")
@Override
public @NonNull Iterator<T> createRandomIterator(@NonNull Random workingRandom) {
return (Iterator<T>) EmptyIterator.INSTANCE;
}
private static final class EmptyIterator<T> implements Iterator<T> {
private static final EmptyIterator<Object> INSTANCE = new EmptyIterator<>();
@Override
public boolean hasNext() {
return false;
}
@Override
public T next() {
throw new NoSuchElementException();
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/bigdecimal/BigDecimalValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.bigdecimal;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
import org.jspecify.annotations.NonNull;
public final class BigDecimalValueRange extends AbstractCountableValueRange<BigDecimal> {
private final BigDecimal from;
private final BigDecimal to;
private final BigDecimal incrementUnit;
/**
* All parameters must have the same {@link BigDecimal#scale()}.
*
* @param from never null, inclusive minimum
* @param to never null, exclusive maximum, {@code >= from}
*/
public BigDecimalValueRange(BigDecimal from, BigDecimal to) {
this(from, to, BigDecimal.valueOf(1L, from.scale()));
}
/**
* All parameters must have the same {@link BigDecimal#scale()}.
*
* @param from never null, inclusive minimum
* @param to never null, exclusive maximum, {@code >= from}
* @param incrementUnit never null, {@code > 0}
*/
public BigDecimalValueRange(BigDecimal from, BigDecimal to, BigDecimal incrementUnit) {
this.from = from;
this.to = to;
this.incrementUnit = incrementUnit;
int scale = from.scale();
if (scale != to.scale()) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a to (" + to + ") scale (" + to.scale()
+ ") which is different than its from (" + from + ") scale (" + scale + ").");
}
if (scale != incrementUnit.scale()) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a from (" + incrementUnit + ") scale (" + incrementUnit.scale()
+ ") which is different than its from (" + from + ") scale (" + scale + ").");
}
if (to.compareTo(from) < 0) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a from (" + from + ") which is strictly higher than its to (" + to + ").");
}
if (incrementUnit.compareTo(BigDecimal.ZERO) <= 0) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " must have strictly positive incrementUnit (" + incrementUnit + ").");
}
if (!to.unscaledValue().subtract(from.unscaledValue()).remainder(incrementUnit.unscaledValue())
.equals(BigInteger.ZERO)) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ "'s incrementUnit (" + incrementUnit
+ ") must fit an integer number of times between from (" + from + ") and to (" + to + ").");
}
}
@Override
public long getSize() {
return to.unscaledValue().subtract(from.unscaledValue()).divide(incrementUnit.unscaledValue()).longValue();
}
@Override
public BigDecimal get(long index) {
if (index < 0L || index >= getSize()) {
throw new IndexOutOfBoundsException("The index (" + index + ") must be >= 0 and < size ("
+ getSize() + ").");
}
return incrementUnit.multiply(BigDecimal.valueOf(index)).add(from);
}
@Override
public boolean contains(BigDecimal value) {
if (value == null || value.compareTo(from) < 0 || value.compareTo(to) >= 0) {
return false;
}
return value.subtract(from).remainder(incrementUnit).compareTo(BigDecimal.ZERO) == 0;
}
@Override
public @NonNull Iterator<BigDecimal> createOriginalIterator() {
return new OriginalBigDecimalValueRangeIterator();
}
private class OriginalBigDecimalValueRangeIterator extends ValueRangeIterator<BigDecimal> {
private BigDecimal upcoming = from;
@Override
public boolean hasNext() {
return upcoming.compareTo(to) < 0;
}
@Override
public BigDecimal next() {
if (upcoming.compareTo(to) >= 0) {
throw new NoSuchElementException();
}
BigDecimal next = upcoming;
upcoming = upcoming.add(incrementUnit);
return next;
}
}
@Override
public @NonNull Iterator<BigDecimal> createRandomIterator(@NonNull Random workingRandom) {
return new RandomBigDecimalValueRangeIterator(workingRandom);
}
private class RandomBigDecimalValueRangeIterator extends ValueRangeIterator<BigDecimal> {
private final Random workingRandom;
private final long size = getSize();
public RandomBigDecimalValueRangeIterator(Random workingRandom) {
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return size > 0L;
}
@Override
public BigDecimal next() {
if (size <= 0L) {
throw new NoSuchElementException();
}
long index = RandomUtils.nextLong(workingRandom, size);
return incrementUnit.multiply(BigDecimal.valueOf(index)).add(from);
}
}
@Override
public String toString() {
return "[" + from + "-" + to + ")"; // Formatting: interval (mathematics) ISO 31-11
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/biginteger/BigIntegerValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.biginteger;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
import org.jspecify.annotations.NonNull;
public final class BigIntegerValueRange extends AbstractCountableValueRange<BigInteger> {
private final BigInteger from;
private final BigInteger to;
private final BigInteger incrementUnit;
/**
* @param from never null, inclusive minimum
* @param to never null, exclusive maximum, {@code >= from}
*/
public BigIntegerValueRange(BigInteger from, BigInteger to) {
this(from, to, BigInteger.valueOf(1L));
}
/**
* @param from never null, inclusive minimum
* @param to never null, exclusive maximum, {@code >= from}
* @param incrementUnit never null, {@code > 0}
*/
public BigIntegerValueRange(BigInteger from, BigInteger to, BigInteger incrementUnit) {
this.from = from;
this.to = to;
this.incrementUnit = incrementUnit;
if (to.compareTo(from) < 0) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a from (" + from + ") which is strictly higher than its to (" + to + ").");
}
if (incrementUnit.compareTo(BigInteger.ZERO) <= 0) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " must have strictly positive incrementUnit (" + incrementUnit + ").");
}
if (!to.subtract(from).remainder(incrementUnit).equals(BigInteger.ZERO)) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ "'s incrementUnit (" + incrementUnit
+ ") must fit an integer number of times between from (" + from + ") and to (" + to + ").");
}
}
@Override
public long getSize() {
return to.subtract(from).divide(incrementUnit).longValue();
}
@Override
public BigInteger get(long index) {
if (index < 0L || index >= getSize()) {
throw new IndexOutOfBoundsException("The index (" + index + ") must be >= 0 and < size ("
+ getSize() + ").");
}
return incrementUnit.multiply(BigInteger.valueOf(index)).add(from);
}
@Override
public boolean contains(BigInteger value) {
if (value == null || value.compareTo(from) < 0 || value.compareTo(to) >= 0) {
return false;
}
return value.subtract(from).remainder(incrementUnit).compareTo(BigInteger.ZERO) == 0;
}
@Override
public @NonNull Iterator<BigInteger> createOriginalIterator() {
return new OriginalBigIntegerValueRangeIterator();
}
private class OriginalBigIntegerValueRangeIterator extends ValueRangeIterator<BigInteger> {
private BigInteger upcoming = from;
@Override
public boolean hasNext() {
return upcoming.compareTo(to) < 0;
}
@Override
public BigInteger next() {
if (upcoming.compareTo(to) >= 0) {
throw new NoSuchElementException();
}
BigInteger next = upcoming;
upcoming = upcoming.add(incrementUnit);
return next;
}
}
@Override
public @NonNull Iterator<BigInteger> createRandomIterator(@NonNull Random workingRandom) {
return new RandomBigIntegerValueRangeIterator(workingRandom);
}
private class RandomBigIntegerValueRangeIterator extends ValueRangeIterator<BigInteger> {
private final Random workingRandom;
private final long size = getSize();
public RandomBigIntegerValueRangeIterator(Random workingRandom) {
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return size > 0L;
}
@Override
public BigInteger next() {
if (size <= 0L) {
throw new NoSuchElementException();
}
long index = RandomUtils.nextLong(workingRandom, size);
return incrementUnit.multiply(BigInteger.valueOf(index)).add(from);
}
}
@Override
public String toString() {
return "[" + from + "-" + to + ")"; // Formatting: interval (mathematics) ISO 31-11
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/collection/ListValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.collection;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.ValueRangeCache;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.CachedListRandomIterator;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
public final class ListValueRange<T> extends AbstractCountableValueRange<T> {
private final boolean isValueImmutable;
private final List<T> list;
private @Nullable ValueRangeCache<T> cache;
public ListValueRange(List<T> list) {
this(list, false);
}
public ListValueRange(List<T> list, boolean isValueImmutable) {
this.isValueImmutable = isValueImmutable;
this.list = list;
}
@Override
public boolean isValueImmutable() {
return isValueImmutable;
}
@Override
public long getSize() {
return list.size();
}
@Override
public @Nullable T get(long index) {
if (index > Integer.MAX_VALUE) {
throw new IndexOutOfBoundsException("The index (" + index + ") must fit in an int.");
}
return list.get((int) index);
}
@Override
public boolean contains(@Nullable T value) {
if (cache == null) {
var cacheBuilder = isValueImmutable ? ValueRangeCache.Builder.FOR_TRUSTED_VALUES
: ValueRangeCache.Builder.FOR_USER_VALUES;
cache = cacheBuilder.buildCache(list);
}
return cache.contains(value);
}
@Override
public Iterator<T> createOriginalIterator() {
return list.iterator();
}
@Override
public Iterator<T> createRandomIterator(Random workingRandom) {
return new CachedListRandomIterator<>(list, workingRandom);
}
@Override
public String toString() {
// Formatting: interval (mathematics) ISO 31-11
return list.isEmpty() ? "[]" : "[" + list.get(0) + "-" + list.get(list.size() - 1) + "]";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/collection/SetValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.collection;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.ValueRangeCache;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
public final class SetValueRange<T> extends AbstractCountableValueRange<T> {
private static final int VALUES_TO_LIST_IN_TO_STRING = 3;
private static final String VALUE_DELIMITER = ", ";
private final boolean isValueImmutable;
private final Set<T> set;
private @Nullable ValueRangeCache<T> cache;
public SetValueRange(Set<T> set) {
this(set, false);
}
public SetValueRange(Set<T> set, boolean isValueImmutable) {
this.isValueImmutable = isValueImmutable;
this.set = set;
}
@Override
public boolean isValueImmutable() {
return isValueImmutable;
}
@Override
public long getSize() {
return set.size();
}
@Override
public @Nullable T get(long index) {
return getCache().get((int) index);
}
private ValueRangeCache<T> getCache() {
if (cache == null) {
var cacheBuilder = isValueImmutable ? ValueRangeCache.Builder.FOR_TRUSTED_VALUES
: ValueRangeCache.Builder.FOR_USER_VALUES;
cache = cacheBuilder.buildCache(set);
}
return cache;
}
@Override
public boolean contains(@Nullable T value) {
return set.contains(value);
}
@Override
public Iterator<T> createOriginalIterator() {
return set.iterator();
}
@Override
public Iterator<T> createRandomIterator(Random workingRandom) {
return getCache().iterator(workingRandom);
}
@Override
public String toString() { // Formatting: interval (mathematics) ISO 31-11
var suffix = set.size() > VALUES_TO_LIST_IN_TO_STRING ? VALUE_DELIMITER + "...}" : "}";
return set.isEmpty() ? "{}"
: set.stream()
.limit(VALUES_TO_LIST_IN_TO_STRING)
.map(Object::toString)
.collect(Collectors.joining(VALUE_DELIMITER, "{", suffix));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/composite/CompositeCountableValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.composite;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.ValueRangeCache;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
public final class CompositeCountableValueRange<T> extends AbstractCountableValueRange<T> {
private final boolean isValueImmutable;
private final ValueRangeCache<T> cache;
public CompositeCountableValueRange(List<? extends AbstractCountableValueRange<T>> childValueRangeList) {
var maximumSize = 0L;
var isValueImmutable = true;
for (AbstractCountableValueRange<T> childValueRange : childValueRangeList) {
isValueImmutable &= childValueRange.isValueImmutable();
maximumSize += childValueRange.getSize();
}
// To eliminate duplicates, we immediately expand the child value ranges into a cache.
var cacheBuilder = isValueImmutable ? ValueRangeCache.Builder.FOR_TRUSTED_VALUES
: ValueRangeCache.Builder.FOR_USER_VALUES;
this.cache = cacheBuilder.buildCache((int) maximumSize);
for (var childValueRange : childValueRangeList) {
// If the child value range includes nulls, we will ignore them.
// They will be added later by the wrapper, if necessary.
if (childValueRange instanceof NullAllowingCountableValueRange<T> nullAllowingCountableValueRange) {
childValueRange = nullAllowingCountableValueRange.getChildValueRange();
}
childValueRange.createOriginalIterator().forEachRemaining(cache::add);
}
this.isValueImmutable = isValueImmutable;
}
@Override
public boolean isValueImmutable() {
return isValueImmutable;
}
@Override
public long getSize() {
return cache.getSize();
}
@Override
public T get(long index) {
return cache.get((int) index);
}
@Override
public boolean contains(@Nullable T value) {
return cache.contains(value);
}
@Override
public Iterator<T> createOriginalIterator() {
return cache.iterator();
}
@Override
public Iterator<T> createRandomIterator(Random workingRandom) {
return cache.iterator(workingRandom);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/composite/NullAllowingCountableValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.composite;
import java.util.Iterator;
import java.util.Random;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
import org.jspecify.annotations.NonNull;
public final class NullAllowingCountableValueRange<T> extends AbstractCountableValueRange<T> {
private final AbstractCountableValueRange<T> childValueRange;
private final long size;
public NullAllowingCountableValueRange(CountableValueRange<T> childValueRange) {
this.childValueRange = (AbstractCountableValueRange<T>) childValueRange;
if (childValueRange instanceof NullAllowingCountableValueRange<T>) {
throw new IllegalArgumentException(
"Impossible state: The childValueRange (%s) must not be a %s, because it is already wrapped in one."
.formatted(childValueRange, NullAllowingCountableValueRange.class.getSimpleName()));
}
size = childValueRange.getSize() + 1L;
}
@Override
public boolean isValueImmutable() {
return super.isValueImmutable();
}
AbstractCountableValueRange<T> getChildValueRange() {
return childValueRange;
}
@Override
public long getSize() {
return size;
}
@Override
public T get(long index) {
if (index == 0) { // Consistent with the iterator.
return null;
} else {
return childValueRange.get(index - 1L);
}
}
@Override
public boolean contains(T value) {
if (value == null) {
return true;
}
return childValueRange.contains(value);
}
@Override
public @NonNull Iterator<T> createOriginalIterator() {
return new OriginalNullValueRangeIterator(childValueRange.createOriginalIterator());
}
private class OriginalNullValueRangeIterator extends ValueRangeIterator<T> {
private boolean nullReturned = false;
private final Iterator<T> childIterator;
public OriginalNullValueRangeIterator(Iterator<T> childIterator) {
this.childIterator = childIterator;
}
@Override
public boolean hasNext() {
return !nullReturned || childIterator.hasNext();
}
@Override
public T next() {
if (!nullReturned) {
nullReturned = true;
return null;
} else {
return childIterator.next();
}
}
}
@Override
public @NonNull Iterator<T> createRandomIterator(@NonNull Random workingRandom) {
return new RandomNullValueRangeIterator(workingRandom);
}
private class RandomNullValueRangeIterator extends ValueRangeIterator<T> {
private final Random workingRandom;
public RandomNullValueRangeIterator(Random workingRandom) {
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return true;
}
@Override
public T next() {
long index = RandomUtils.nextLong(workingRandom, size);
return get(index);
}
}
@Override
public String toString() {
return "[null]∪" + childValueRange; // Formatting: interval (mathematics) ISO 31-11
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/primboolean/BooleanValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.primboolean;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
import org.jspecify.annotations.NonNull;
public final class BooleanValueRange extends AbstractCountableValueRange<Boolean> {
@Override
public long getSize() {
return 2L;
}
@Override
public boolean contains(Boolean value) {
if (value == null) {
return false;
}
return true;
}
@Override
public Boolean get(long index) {
if (index < 0L || index >= 2L) {
throw new IndexOutOfBoundsException("The index (" + index + ") must be >= 0 and < 2.");
}
return index == 0L ? Boolean.FALSE : Boolean.TRUE;
}
@Override
public @NonNull Iterator<Boolean> createOriginalIterator() {
return new OriginalBooleanValueRangeIterator();
}
private static final class OriginalBooleanValueRangeIterator extends ValueRangeIterator<Boolean> {
private boolean hasNext = true;
private Boolean upcoming = Boolean.FALSE;
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public Boolean next() {
if (!hasNext) {
throw new NoSuchElementException();
}
Boolean next = upcoming;
if (upcoming) {
hasNext = false;
} else {
upcoming = Boolean.TRUE;
}
return next;
}
}
@Override
public @NonNull Iterator<Boolean> createRandomIterator(@NonNull Random workingRandom) {
return new RandomBooleanValueRangeIterator(workingRandom);
}
private static final class RandomBooleanValueRangeIterator extends ValueRangeIterator<Boolean> {
private final Random workingRandom;
public RandomBooleanValueRangeIterator(Random workingRandom) {
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return true;
}
@Override
public Boolean next() {
return Boolean.valueOf(workingRandom.nextBoolean());
}
}
@Override
public String toString() {
return "[false, true]"; // Formatting: interval (mathematics) ISO 31-11
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/primdouble/DoubleValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.primdouble;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractUncountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.buildin.bigdecimal.BigDecimalValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
import org.jspecify.annotations.NonNull;
/**
* Note: Floating point numbers (float, double) cannot represent a decimal number correctly.
* If floating point numbers leak into the scoring function, they are likely to cause score corruptions.
* To avoid that, use either {@link java.math.BigDecimal} or fixed-point arithmetic.
*
* @deprecated Prefer {@link BigDecimalValueRange}.
*/
@Deprecated(forRemoval = true, since = "1.1.0")
public class DoubleValueRange extends AbstractUncountableValueRange<Double> {
private final double from;
private final double to;
/**
* @param from inclusive minimum
* @param to exclusive maximum, {@code >= from}
*/
public DoubleValueRange(double from, double to) {
this.from = from;
this.to = to;
if (to < from) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a from (" + from + ") which is strictly higher than its to (" + to + ").");
}
}
@Override
public boolean isEmpty() {
return from == to;
}
@Override
public boolean contains(Double value) {
if (value == null) {
return false;
}
return value >= from && value < to;
}
// In theory, we can implement createOriginalIterator() by using Math.nextAfter().
// But in practice, no one could use it.
@Override
public @NonNull Iterator<Double> createRandomIterator(@NonNull Random workingRandom) {
return new RandomDoubleValueRangeIterator(workingRandom);
}
private class RandomDoubleValueRangeIterator extends ValueRangeIterator<Double> {
private final Random workingRandom;
public RandomDoubleValueRangeIterator(Random workingRandom) {
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return to != from;
}
@Override
public Double next() {
if (to == from) {
throw new NoSuchElementException();
}
double diff = to - from;
double next = from + diff * workingRandom.nextDouble();
if (next >= to) {
// Rounding error occurred
next = Math.nextAfter(next, Double.NEGATIVE_INFINITY);
}
return next;
}
}
@Override
public String toString() {
return "[" + from + "-" + to + ")"; // Formatting: interval (mathematics) ISO 31-11
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/primint/IntValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.primint;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
import org.jspecify.annotations.NonNull;
public final class IntValueRange extends AbstractCountableValueRange<Integer> {
private final int from;
private final int to;
private final int incrementUnit;
/**
* @param from inclusive minimum
* @param to exclusive maximum, {@code >= from}
*/
public IntValueRange(int from, int to) {
this(from, to, 1);
}
/**
* @param from inclusive minimum
* @param to exclusive maximum, {@code >= from}
* @param incrementUnit {@code > 0}
*/
public IntValueRange(int from, int to, int incrementUnit) {
this.from = from;
this.to = to;
this.incrementUnit = incrementUnit;
if (to < from) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a from (" + from + ") which is strictly higher than its to (" + to + ").");
}
if (incrementUnit <= 0) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " must have strictly positive incrementUnit (" + incrementUnit + ").");
}
if ((to - (long) from) % incrementUnit != 0L) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ "'s incrementUnit (" + incrementUnit
+ ") must fit an integer number of times between from (" + from + ") and to (" + to + ").");
}
}
@Override
public long getSize() {
return (to - (long) from) / incrementUnit;
}
@Override
public boolean contains(Integer value) {
if (value == null || value < from || value >= to) {
return false;
}
if (incrementUnit == 1) {
return true;
}
return ((long) value - from) % incrementUnit == 0;
}
@Override
public Integer get(long index) {
if (index < 0L || index >= getSize()) {
throw new IndexOutOfBoundsException("The index (" + index + ") must be >= 0 and < size ("
+ getSize() + ").");
}
return (int) (index * incrementUnit + from);
}
@Override
public @NonNull Iterator<Integer> createOriginalIterator() {
return new OriginalIntValueRangeIterator();
}
private class OriginalIntValueRangeIterator extends ValueRangeIterator<Integer> {
private int upcoming = from;
@Override
public boolean hasNext() {
return upcoming < to;
}
@Override
public Integer next() {
if (upcoming >= to) {
throw new NoSuchElementException();
}
int next = upcoming;
upcoming += incrementUnit;
return next;
}
}
@Override
public @NonNull Iterator<Integer> createRandomIterator(@NonNull Random workingRandom) {
return new RandomIntValueRangeIterator(workingRandom);
}
private class RandomIntValueRangeIterator extends ValueRangeIterator<Integer> {
private final Random workingRandom;
private final long size = getSize();
public RandomIntValueRangeIterator(Random workingRandom) {
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return size > 0L;
}
@Override
public Integer next() {
if (size <= 0L) {
throw new NoSuchElementException();
}
long index = RandomUtils.nextLong(workingRandom, size);
return (int) (index * incrementUnit + from);
}
}
@Override
public String toString() {
return "[" + from + "-" + to + ")"; // Formatting: interval (mathematics) ISO 31-11
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/primlong/LongValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.primlong;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
import org.jspecify.annotations.NonNull;
public final class LongValueRange extends AbstractCountableValueRange<Long> {
private final long from;
private final long to;
private final long incrementUnit;
/**
* @param from inclusive minimum
* @param to exclusive maximum, {@code >= from}
*/
public LongValueRange(long from, long to) {
this(from, to, 1);
}
/**
* @param from inclusive minimum
* @param to exclusive maximum, {@code >= from}
* @param incrementUnit {@code > 0}
*/
public LongValueRange(long from, long to, long incrementUnit) {
this.from = from;
this.to = to;
this.incrementUnit = incrementUnit;
if (to < from) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a from (" + from + ") which is strictly higher than its to (" + to + ").");
}
if (incrementUnit <= 0L) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " must have strictly positive incrementUnit (" + incrementUnit + ").");
}
if ((to - from) < 0L) { // Overflow way to detect if ((to - from) > Long.MAX_VALUE)
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a from (" + from + ") and to (" + to
+ ") with a gap greater than Long.MAX_VALUE (" + Long.MAX_VALUE + ").");
}
if ((to - from) % incrementUnit != 0L) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ "'s incrementUnit (" + incrementUnit
+ ") must fit an integer number of times between from (" + from + ") and to (" + to + ").");
}
}
@Override
public long getSize() {
return (to - from) / incrementUnit;
}
@Override
public boolean contains(Long value) {
if (value == null || value < from || value >= to) {
return false;
}
if (incrementUnit == 1L) {
return true;
}
return (value - from) % incrementUnit == 0L;
}
@Override
public Long get(long index) {
if (index < 0L || index >= getSize()) {
throw new IndexOutOfBoundsException("The index (" + index + ") must be >= 0 and < size ("
+ getSize() + ").");
}
return index * incrementUnit + from;
}
@Override
public @NonNull Iterator<Long> createOriginalIterator() {
return new OriginalLongValueRangeIterator();
}
private class OriginalLongValueRangeIterator extends ValueRangeIterator<Long> {
private long upcoming = from;
@Override
public boolean hasNext() {
return upcoming < to;
}
@Override
public Long next() {
if (upcoming >= to) {
throw new NoSuchElementException();
}
long next = upcoming;
upcoming += incrementUnit;
return next;
}
}
@Override
public @NonNull Iterator<Long> createRandomIterator(@NonNull Random workingRandom) {
return new RandomLongValueRangeIterator(workingRandom);
}
private class RandomLongValueRangeIterator extends ValueRangeIterator<Long> {
private final Random workingRandom;
private final long size = getSize();
public RandomLongValueRangeIterator(Random workingRandom) {
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return size > 0L;
}
@Override
public Long next() {
if (size <= 0L) {
throw new NoSuchElementException();
}
long index = RandomUtils.nextLong(workingRandom, size);
return index * incrementUnit + from;
}
}
@Override
public String toString() {
return "[" + from + "-" + to + ")"; // Formatting: interval (mathematics) ISO 31-11
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/temporal/TemporalValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.temporal;
import java.time.DateTimeException;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalUnit;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
import org.jspecify.annotations.NonNull;
public final class TemporalValueRange<Temporal_ extends Temporal & Comparable<? super Temporal_>>
extends AbstractCountableValueRange<Temporal_> {
private final Temporal_ from;
private final Temporal_ to;
/** We could not use a {@link TemporalAmount} as {@code incrementUnit} due to lack of calculus functions. */
private final long incrementUnitAmount;
private final TemporalUnit incrementUnitType;
private final long size;
/**
* @param from never null, inclusive minimum
* @param to never null, exclusive maximum, {@code >= from}
* @param incrementUnitAmount {@code > 0}
* @param incrementUnitType never null, must be {@link Temporal#isSupported(TemporalUnit) supported} by {@code from}
* and {@code to}
*/
public TemporalValueRange(Temporal_ from, Temporal_ to, long incrementUnitAmount, TemporalUnit incrementUnitType) {
this.from = from;
this.to = to;
this.incrementUnitAmount = incrementUnitAmount;
this.incrementUnitType = incrementUnitType;
if (from == null || to == null || incrementUnitType == null) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " must have a from (" + from + "), to (" + to + ") and incrementUnitType (" + incrementUnitType
+ ") that are not null.");
}
if (incrementUnitAmount <= 0) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " must have strictly positive incrementUnitAmount (" + incrementUnitAmount + ").");
}
if (!from.isSupported(incrementUnitType) || !to.isSupported(incrementUnitType)) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " must have an incrementUnitType (" + incrementUnitType
+ ") that is supported by its from (" + from + ") class (" + from.getClass().getSimpleName()
+ ") and to (" + to + ") class (" + to.getClass().getSimpleName() + ").");
}
// We cannot use Temporal.until() to check bounds due to rounding errors
if (from.compareTo(to) > 0) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a from (" + from + ") which is strictly higher than its to (" + to + ").");
}
long space = from.until(to, incrementUnitType);
Temporal expectedTo = from.plus(space, incrementUnitType);
if (!to.equals(expectedTo)) {
// Temporal.until() rounds down, but it needs to round up, to be consistent with Temporal.plus()
space++;
Temporal roundedExpectedTo;
try {
roundedExpectedTo = from.plus(space, incrementUnitType);
} catch (DateTimeException e) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ "'s incrementUnitType (" + incrementUnitType
+ ") must fit an integer number of times in the space (" + space
+ ") between from (" + from + ") and to (" + to + ").\n"
+ "The to (" + to + ") is not the expectedTo (" + expectedTo + ").", e);
}
// Fail fast if there's a remainder on type (to be consistent with other value ranges)
if (!to.equals(roundedExpectedTo)) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ "'s incrementUnitType (" + incrementUnitType
+ ") must fit an integer number of times in the space (" + space
+ ") between from (" + from + ") and to (" + to + ").\n"
+ "The to (" + to + ") is not the expectedTo (" + expectedTo
+ ") nor the roundedExpectedTo (" + roundedExpectedTo + ").");
}
}
// Fail fast if there's a remainder on amount (to be consistent with other value ranges)
if (space % incrementUnitAmount > 0) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ "'s incrementUnitAmount (" + incrementUnitAmount
+ ") must fit an integer number of times in the space (" + space
+ ") between from (" + from + ") and to (" + to + ").");
}
size = space / incrementUnitAmount;
}
@Override
public long getSize() {
return size;
}
@Override
public Temporal_ get(long index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException();
}
return (Temporal_) from.plus(index * incrementUnitAmount, incrementUnitType);
}
@Override
public boolean contains(Temporal_ value) {
if (value == null || !value.isSupported(incrementUnitType)) {
return false;
}
// We cannot use Temporal.until() to check bounds due to rounding errors
if (value.compareTo(from) < 0 || value.compareTo(to) >= 0) {
return false;
}
long fromSpace = from.until(value, incrementUnitType);
if (value.equals(from.plus(fromSpace + 1, incrementUnitType))) {
// Temporal.until() rounds down, but it needs to round up, to be consistent with Temporal.plus()
fromSpace++;
}
// Only checking the modulus is not enough: 1-MAR + 1 month doesn't include 7-MAR but the modulus is 0 anyway
return fromSpace % incrementUnitAmount == 0
&& value.equals(from.plus(fromSpace, incrementUnitType));
}
@Override
public @NonNull Iterator<Temporal_> createOriginalIterator() {
return new OriginalTemporalValueRangeIterator();
}
private class OriginalTemporalValueRangeIterator extends ValueRangeIterator<Temporal_> {
private long index = 0L;
@Override
public boolean hasNext() {
return index < size;
}
@Override
public Temporal_ next() {
if (index >= size) {
throw new NoSuchElementException();
}
// Do not use upcoming += incrementUnitAmount because 31-JAN + 1 month + 1 month returns 28-MAR
Temporal_ next = get(index);
index++;
return next;
}
}
@Override
public @NonNull Iterator<Temporal_> createRandomIterator(@NonNull Random workingRandom) {
return new RandomTemporalValueRangeIterator(workingRandom);
}
private class RandomTemporalValueRangeIterator extends ValueRangeIterator<Temporal_> {
private final Random workingRandom;
public RandomTemporalValueRangeIterator(Random workingRandom) {
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return size > 0L;
}
@Override
public Temporal_ next() {
long index = RandomUtils.nextLong(workingRandom, size);
return get(index);
}
}
@Override
public String toString() {
return "[" + from + "-" + to + ")"; // Formatting: interval (mathematics) ISO 31-11
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/descriptor/AbstractFromPropertyValueRangeDescriptor.java | package ai.timefold.solver.core.impl.domain.valuerange.descriptor;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.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.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.valuerange.buildin.EmptyValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.buildin.collection.ListValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.buildin.collection.SetValueRange;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract non-sealed class AbstractFromPropertyValueRangeDescriptor<Solution_>
extends AbstractValueRangeDescriptor<Solution_> {
protected final MemberAccessor memberAccessor;
protected boolean collectionWrapping;
protected boolean arrayWrapping;
protected boolean countable;
// Field related to the generic type of the value range, e.g., List<String> -> String
private final boolean isGenericTypeImmutable;
protected AbstractFromPropertyValueRangeDescriptor(int ordinalId, GenuineVariableDescriptor<Solution_> variableDescriptor,
MemberAccessor memberAccessor) {
super(ordinalId, variableDescriptor);
this.memberAccessor = memberAccessor;
ValueRangeProvider valueRangeProviderAnnotation = memberAccessor.getAnnotation(ValueRangeProvider.class);
if (valueRangeProviderAnnotation == null) {
throw new IllegalStateException("The member (%s) must have a valueRangeProviderAnnotation (%s)."
.formatted(memberAccessor, valueRangeProviderAnnotation));
}
var type = memberAccessor.getType();
collectionWrapping = Collection.class.isAssignableFrom(type);
arrayWrapping = type.isArray();
processValueRangeProviderAnnotation(valueRangeProviderAnnotation);
if (collectionWrapping) {
var genericType = ConfigUtils.extractGenericTypeParameterOrFail("solutionClass or entityClass",
memberAccessor.getDeclaringClass(), memberAccessor.getType(), memberAccessor.getGenericType(),
ValueRangeProvider.class, memberAccessor.getName());
this.isGenericTypeImmutable = ConfigUtils.isGenericTypeImmutable(genericType);
} else {
this.isGenericTypeImmutable = true;
}
}
private void processValueRangeProviderAnnotation(ValueRangeProvider valueRangeProviderAnnotation) {
EntityDescriptor<Solution_> entityDescriptor = variableDescriptor.getEntityDescriptor();
Class<?> type = memberAccessor.getType();
if (!collectionWrapping && !arrayWrapping && !ValueRange.class.isAssignableFrom(type)) {
throw new IllegalArgumentException("""
The entityClass (%s) has a @%s-annotated property (%s) that refers to a @%s-annotated member \
(%s) that does not return a %s, an array or a %s."""
.formatted(entityDescriptor.getEntityClass(), PlanningVariable.class.getSimpleName(),
variableDescriptor.getVariableName(), ValueRangeProvider.class.getSimpleName(),
memberAccessor, Collection.class.getSimpleName(), ValueRange.class.getSimpleName()));
}
if (collectionWrapping) {
Class<?> collectionElementClass = ConfigUtils.extractGenericTypeParameterOrFail("solutionClass or entityClass",
memberAccessor.getDeclaringClass(), memberAccessor.getType(), memberAccessor.getGenericType(),
ValueRangeProvider.class, memberAccessor.getName());
if (!variableDescriptor.acceptsValueType(collectionElementClass)) {
throw new IllegalArgumentException("""
The entityClass (%s) has a @%s-annotated property (%s) that refers to a @%s-annotated member (%s) \
that returns a %s with elements of type (%s) which cannot be assigned to the type of %s (%s)."""
.formatted(entityDescriptor.getEntityClass(), PlanningVariable.class.getSimpleName(),
variableDescriptor.getVariableName(), ValueRangeProvider.class.getSimpleName(),
memberAccessor, Collection.class.getSimpleName(), collectionElementClass,
PlanningVariable.class.getSimpleName(), variableDescriptor.getVariablePropertyType()));
}
} else if (arrayWrapping) {
Class<?> arrayElementClass = type.getComponentType();
if (!variableDescriptor.acceptsValueType(arrayElementClass)) {
throw new IllegalArgumentException(
"""
The entityClass (%s) has a @%s-annotated property (%s) that refers to a @%s-annotated member (%s) \
that returns an array with elements of type (%s) which cannot be assigned to the type of the @%s (%s);"""
.formatted(entityDescriptor.getEntityClass(), PlanningVariable.class.getSimpleName(),
variableDescriptor.getVariableName(), ValueRangeProvider.class.getSimpleName(),
memberAccessor, arrayElementClass, PlanningVariable.class.getSimpleName(),
variableDescriptor.getVariablePropertyType()));
}
}
countable = collectionWrapping || arrayWrapping || CountableValueRange.class.isAssignableFrom(type);
}
@Override
public boolean isCountable() {
return countable;
}
@SuppressWarnings("unchecked")
protected <Value_> CountableValueRange<Value_> readValueRange(Object bean) {
Object valueRangeObject = memberAccessor.executeGetter(bean);
if (valueRangeObject == null) {
throw new IllegalStateException(
"The @%s-annotated member (%s) called on bean (%s) must not return a null valueRangeObject (%s)."
.formatted(ValueRangeProvider.class.getSimpleName(), memberAccessor, bean, valueRangeObject));
}
if (arrayWrapping) {
List<Value_> list = transformArrayToList(valueRangeObject);
assertNullNotPresent(list, bean);
return buildValueRange(list);
} else if (collectionWrapping) {
var collection = (Collection<Value_>) valueRangeObject;
if (collection instanceof Set<Value_> set) {
if (!(collection instanceof SortedSet<Value_> || collection instanceof LinkedHashSet<Value_>)) {
throw new IllegalStateException("""
The @%s-annotated member (%s) called on bean (%s) returns a Set (%s) with undefined iteration order.
Use SortedSet or LinkedHashSet to ensure solver reproducibility.
"""
.formatted(ValueRangeProvider.class.getSimpleName(), memberAccessor, bean, set.getClass()));
} else if (set.contains(null)) {
throw new IllegalStateException("""
The @%s-annotated member (%s) called on bean (%s) returns a Set (%s) with a null element.
Maybe remove that null element from the dataset \
and use @%s(allowsUnassigned = true) or @%s(allowsUnassignedValues = true) instead."""
.formatted(ValueRangeProvider.class.getSimpleName(), memberAccessor, bean, set,
PlanningVariable.class.getSimpleName(), PlanningListVariable.class.getSimpleName()));
}
return buildValueRange(set);
} else {
List<Value_> list = transformCollectionToList(collection);
assertNullNotPresent(list, bean);
return buildValueRange(list);
}
} else {
var valueRange = (CountableValueRange<Value_>) valueRangeObject;
return valueRange.isEmpty() ? EmptyValueRange.instance() : valueRange;
}
}
private void assertNullNotPresent(List<?> list, Object bean) {
// Don't check the entire list for performance reasons, but do check common pitfalls
if (!list.isEmpty() && (list.get(0) == null || list.get(list.size() - 1) == null)) {
throw new IllegalStateException("""
The @%s-annotated member (%s) called on bean (%s) must not return a %s (%s) with an element that is null.
Maybe remove that null element from the dataset \
and use @%s(allowsUnassigned = true) or @%s(allowsUnassignedValues = true) instead."""
.formatted(ValueRangeProvider.class.getSimpleName(), memberAccessor, bean,
collectionWrapping ? Collection.class.getSimpleName() : "array", list,
PlanningVariable.class.getSimpleName(), PlanningListVariable.class.getSimpleName()));
}
}
private <T> CountableValueRange<T> buildValueRange(Collection<T> valueCollection) {
if (valueCollection.isEmpty()) {
return EmptyValueRange.instance();
} else if (valueCollection instanceof Set<T> set) {
return new SetValueRange<>(set, isGenericTypeImmutable);
} else if (valueCollection instanceof List<T> list) {
return new ListValueRange<>(list, isGenericTypeImmutable);
} else {
throw new IllegalArgumentException("Impossible state: The collection (%s) must be a Set or a List."
.formatted(valueCollection));
}
}
@SuppressWarnings("unchecked")
public static <Value_> List<Value_> transformArrayToList(Object arrayObject) {
if (arrayObject == null) {
return Collections.emptyList();
}
var array = (Value_[]) arrayObject;
if (array.length == 0) {
return Collections.emptyList();
}
return Arrays.asList(array); // Does not involve any copying, just a view of the array.
}
private static <T> List<T> transformCollectionToList(Collection<T> collection) {
if (collection.isEmpty()) {
return Collections.emptyList();
} else if (collection instanceof List<T> list) {
// Avoid copying the list if it is already a List; even though it will keep mutability.
return Collections.unmodifiableList(list);
} else {
return List.copyOf(collection);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/descriptor/AbstractValueRangeDescriptor.java | package ai.timefold.solver.core.impl.domain.valuerange.descriptor;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import org.jspecify.annotations.NullMarked;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
@NullMarked
public abstract sealed class AbstractValueRangeDescriptor<Solution_>
implements ValueRangeDescriptor<Solution_>
permits AbstractFromPropertyValueRangeDescriptor, CompositeValueRangeDescriptor {
private final int ordinal;
protected final GenuineVariableDescriptor<Solution_> variableDescriptor;
protected AbstractValueRangeDescriptor(int ordinal, GenuineVariableDescriptor<Solution_> variableDescriptor) {
this.ordinal = ordinal;
this.variableDescriptor = variableDescriptor;
}
@Override
public int getOrdinal() {
return ordinal;
}
@Override
public GenuineVariableDescriptor<Solution_> getVariableDescriptor() {
return variableDescriptor;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean mightContainEntity() {
SolutionDescriptor<Solution_> solutionDescriptor = variableDescriptor.getEntityDescriptor().getSolutionDescriptor();
Class<?> variablePropertyType = variableDescriptor.getVariablePropertyType();
for (Class<?> entityClass : solutionDescriptor.getEntityClassSet()) {
if (variablePropertyType.isAssignableFrom(entityClass)) {
return true;
}
}
return false;
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + variableDescriptor.getVariableName() + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/descriptor/CompositeValueRangeDescriptor.java | package ai.timefold.solver.core.impl.domain.valuerange.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.valuerange.ValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.buildin.bigdecimal.BigDecimalValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.buildin.composite.CompositeCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.buildin.primdouble.DoubleValueRange;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import org.jspecify.annotations.NullMarked;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
@NullMarked
public final class CompositeValueRangeDescriptor<Solution_> extends AbstractValueRangeDescriptor<Solution_> {
private final boolean canExtractValueRangeFromSolution;
private final List<ValueRangeDescriptor<Solution_>> childValueRangeDescriptorList;
public CompositeValueRangeDescriptor(int ordinal, GenuineVariableDescriptor<Solution_> variableDescriptor,
List<ValueRangeDescriptor<Solution_>> childValueRangeDescriptorList) {
super(ordinal, variableDescriptor);
this.childValueRangeDescriptorList = childValueRangeDescriptorList;
var canExtractFromSolution = true;
for (var valueRangeDescriptor : childValueRangeDescriptorList) {
if (!valueRangeDescriptor.isCountable()) {
throw new IllegalStateException("""
The valueRange (%s) has a childValueRange (%s) which is not countable.
Maybe replace %s with %s?"""
.formatted(this, valueRangeDescriptor, DoubleValueRange.class.getSimpleName(),
BigDecimalValueRange.class.getSimpleName()));
}
canExtractFromSolution = canExtractFromSolution && valueRangeDescriptor.canExtractValueRangeFromSolution();
}
this.canExtractValueRangeFromSolution = canExtractFromSolution;
}
public int getValueRangeCount() {
return childValueRangeDescriptorList.size();
}
@Override
public boolean canExtractValueRangeFromSolution() {
return canExtractValueRangeFromSolution;
}
@Override
public boolean isCountable() {
return true;
}
@Override
public <T> ValueRange<T> extractAllValues(Solution_ solution) {
var childValueRangeList = new ArrayList<AbstractCountableValueRange<T>>(childValueRangeDescriptorList.size());
for (var valueRangeDescriptor : childValueRangeDescriptorList) {
childValueRangeList.add((AbstractCountableValueRange<T>) valueRangeDescriptor.<T> extractAllValues(solution));
}
return new CompositeCountableValueRange<>(childValueRangeList);
}
@Override
public <T> ValueRange<T> extractValuesFromEntity(Solution_ solution, Object entity) {
var childValueRangeList = new ArrayList<AbstractCountableValueRange<T>>(childValueRangeDescriptorList.size());
for (var valueRangeDescriptor : childValueRangeDescriptorList) {
childValueRangeList
.add((AbstractCountableValueRange<T>) valueRangeDescriptor.<T> extractValuesFromEntity(solution, entity));
}
return new CompositeCountableValueRange<>(childValueRangeList);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/descriptor/FromEntityPropertyValueRangeDescriptor.java | package ai.timefold.solver.core.impl.domain.valuerange.descriptor;
import java.util.ArrayList;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.buildin.composite.CompositeCountableValueRange;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import org.jspecify.annotations.NullMarked;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
@NullMarked
public final class FromEntityPropertyValueRangeDescriptor<Solution_>
extends AbstractFromPropertyValueRangeDescriptor<Solution_> {
public FromEntityPropertyValueRangeDescriptor(int ordinal, GenuineVariableDescriptor<Solution_> variableDescriptor,
MemberAccessor memberAccessor) {
super(ordinal, variableDescriptor, memberAccessor);
}
@Override
public <T> ValueRange<T> extractAllValues(Solution_ solution) {
var entityList = variableDescriptor.getEntityDescriptor().extractEntities(solution);
var rangesFromEntities = new ArrayList<AbstractCountableValueRange<T>>(entityList.size());
for (var entity : entityList) {
var valueRange = (AbstractCountableValueRange<T>) this.<T> extractValuesFromEntity(solution, entity);
rangesFromEntities.add(valueRange);
}
return new CompositeCountableValueRange<>(rangesFromEntities);
}
@Override
public <T> ValueRange<T> extractValuesFromEntity(Solution_ solution, Object entity) {
return readValueRange(entity);
}
@Override
public boolean canExtractValueRangeFromSolution() {
return false;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/descriptor/FromSolutionPropertyValueRangeDescriptor.java | package ai.timefold.solver.core.impl.domain.valuerange.descriptor;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import org.jspecify.annotations.NullMarked;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
@NullMarked
public final class FromSolutionPropertyValueRangeDescriptor<Solution_>
extends AbstractFromPropertyValueRangeDescriptor<Solution_> {
public FromSolutionPropertyValueRangeDescriptor(int ordinal, GenuineVariableDescriptor<Solution_> variableDescriptor,
MemberAccessor memberAccessor) {
super(ordinal, variableDescriptor, memberAccessor);
}
@Override
public <T> ValueRange<T> extractAllValues(Solution_ solution) {
return readValueRange(solution);
}
@Override
public <T> ValueRange<T> extractValuesFromEntity(Solution_ solution, Object entity) {
return readValueRange(solution); // Needed for composite ranges on solution and on entity.
}
@Override
public boolean canExtractValueRangeFromSolution() {
return true;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/descriptor/ValueRangeDescriptor.java | package ai.timefold.solver.core.impl.domain.valuerange.descriptor;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.score.director.ValueRangeManager;
import org.jspecify.annotations.NullMarked;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
@NullMarked
public sealed interface ValueRangeDescriptor<Solution_> permits AbstractValueRangeDescriptor {
/**
* A number unique within a {@link SolutionDescriptor}, increasing sequentially from zero.
* Used for indexing in arrays to avoid object hash lookups in maps.
*
* @return zero or higher
*/
int getOrdinal();
/**
* @return never null
*/
GenuineVariableDescriptor<Solution_> getVariableDescriptor();
/**
* True when {@link PlanningVariable#allowsUnassigned()}.
* Always false with {@link PlanningListVariable}
* as list variables get unassigned through a different mechanism
* (e.g. ElementPositionRandomIterator).
*/
default boolean acceptsNullInValueRange() {
return getVariableDescriptor() instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor
&& basicVariableDescriptor.allowsUnassigned();
}
/**
* @return true if the {@link ValueRange} is countable
* (for example a double value range between 1.2 and 1.4 is not countable)
*/
boolean isCountable();
/**
* Returns true if the value range is defined at the solution level and can be directly extracted from the solution;
* otherwise, it returns false, as the value range can only be extracted or computed from the entities.
*/
boolean canExtractValueRangeFromSolution();
/**
* @return true if the {@link ValueRange} might contain a planning entity instance
* (not necessarily of the same entity class as this entity class of this descriptor.
*/
boolean mightContainEntity();
/**
* Extracts the {@link ValueRange} from the solution or,
* if the value range is defined at the entity level,
* extracts a composite {@link ValueRange} from all entities in the solution.
* <p>
* The method should not be invoked directly by selectors or other components of the solver.
* The {@link ValueRangeManager#getFromSolution(ValueRangeDescriptor, Object)}
* and {@link ValueRangeManager#getFromEntity(ValueRangeDescriptor, Object)}
* serve as the single source of truth for managing value ranges and should be used by outer components.
* <p>
* Calling this method outside {@link ValueRangeManager} may lead to unnecessary recomputation of ranges.
*/
<T> ValueRange<T> extractAllValues(Solution_ solution);
/**
* Extracts the {@link ValueRange} from the planning entity.
* If the value range is defined at the solution level instead,
* this method reads the value range from there.
* <p>
* The method should not be invoked directly by selectors or other components of the solver.
* The {@link ValueRangeManager#getFromSolution(ValueRangeDescriptor, Object)}
* and {@link ValueRangeManager#getFromEntity(ValueRangeDescriptor, Object)}
* serve as the single source of truth for managing value ranges and should be used by outer components.
* <p>
* Calling this method outside {@link ValueRangeManager} may lead to unnecessary recomputation of ranges.
*/
<T> ValueRange<T> extractValuesFromEntity(Solution_ solution, Object entity);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/valuerange/util/ValueRangeIterator.java | package ai.timefold.solver.core.impl.domain.valuerange.util;
import java.util.Iterator;
public abstract class ValueRangeIterator<S> implements Iterator<S> {
@Override
public void remove() {
throw new UnsupportedOperationException("The optional operation remove() is not supported.");
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/ExternalizedIndexVariableProcessor.java | package ai.timefold.solver.core.impl.domain.variable;
import java.util.Objects;
import ai.timefold.solver.core.impl.domain.variable.index.IndexShadowVariableDescriptor;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
final class ExternalizedIndexVariableProcessor<Solution_> {
private final IndexShadowVariableDescriptor<Solution_> shadowVariableDescriptor;
public ExternalizedIndexVariableProcessor(IndexShadowVariableDescriptor<Solution_> shadowVariableDescriptor) {
this.shadowVariableDescriptor = shadowVariableDescriptor;
}
public void addElement(InnerScoreDirector<Solution_, ?> scoreDirector, Object element, Integer index) {
updateIndex(scoreDirector, element, index);
}
public void removeElement(InnerScoreDirector<Solution_, ?> scoreDirector, Object element) {
updateIndex(scoreDirector, element, null);
}
public void unassignElement(InnerScoreDirector<Solution_, ?> scoreDirector, Object element) {
removeElement(scoreDirector, element);
}
public void changeElement(InnerScoreDirector<Solution_, ?> scoreDirector, Object element, Integer index) {
updateIndex(scoreDirector, element, index);
}
private void updateIndex(InnerScoreDirector<Solution_, ?> scoreDirector, Object element, Integer index) {
var oldIndex = getIndex(element);
if (!Objects.equals(oldIndex, index)) {
scoreDirector.beforeVariableChanged(shadowVariableDescriptor, element);
shadowVariableDescriptor.setValue(element, index);
scoreDirector.afterVariableChanged(shadowVariableDescriptor, element);
}
}
public Integer getIndex(Object planningValue) {
return shadowVariableDescriptor.getValue(planningValue);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/ExternalizedListInverseVariableProcessor.java | package ai.timefold.solver.core.impl.domain.variable;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.InverseRelationShadowVariableDescriptor;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
final class ExternalizedListInverseVariableProcessor<Solution_> {
private final InverseRelationShadowVariableDescriptor<Solution_> shadowVariableDescriptor;
private final ListVariableDescriptor<Solution_> sourceVariableDescriptor;
public ExternalizedListInverseVariableProcessor(
InverseRelationShadowVariableDescriptor<Solution_> shadowVariableDescriptor,
ListVariableDescriptor<Solution_> sourceVariableDescriptor) {
this.shadowVariableDescriptor = shadowVariableDescriptor;
this.sourceVariableDescriptor = sourceVariableDescriptor;
}
public void addElement(InnerScoreDirector<Solution_, ?> scoreDirector, Object entity, Object element) {
setInverseAsserted(scoreDirector, element, entity, null);
}
private void setInverseAsserted(InnerScoreDirector<Solution_, ?> scoreDirector, Object element, Object inverseEntity,
Object expectedOldInverseEntity) {
var oldInverseEntity = getInverseSingleton(element);
if (oldInverseEntity == inverseEntity) {
return;
}
if (scoreDirector.expectShadowVariablesInCorrectState() && oldInverseEntity != expectedOldInverseEntity) {
throw new IllegalStateException("""
The entity (%s) has a list variable (%s) and one of its elements (%s) which has a shadow variable (%s) \
has an oldInverseEntity (%s) which is not that entity.
Verify the consistency of your input problem for that shadow variable."""
.formatted(inverseEntity, sourceVariableDescriptor.getVariableName(), element,
shadowVariableDescriptor.getVariableName(), oldInverseEntity));
}
setInverse(scoreDirector, inverseEntity, element);
}
private void setInverse(InnerScoreDirector<Solution_, ?> scoreDirector, Object entity, Object element) {
scoreDirector.beforeVariableChanged(shadowVariableDescriptor, element);
shadowVariableDescriptor.setValue(element, entity);
scoreDirector.afterVariableChanged(shadowVariableDescriptor, element);
}
public void removeElement(InnerScoreDirector<Solution_, ?> scoreDirector, Object entity, Object element) {
setInverseAsserted(scoreDirector, element, null, entity);
}
public void unassignElement(InnerScoreDirector<Solution_, ?> scoreDirector, Object element) {
changeElement(scoreDirector, null, element);
}
public void changeElement(InnerScoreDirector<Solution_, ?> scoreDirector, Object entity, Object element) {
if (getInverseSingleton(element) != entity) {
setInverse(scoreDirector, entity, element);
}
}
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 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/ExternalizedListVariableStateSupply.java | package ai.timefold.solver.core.impl.domain.variable;
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.index.IndexShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.InverseRelationShadowVariableDescriptor;
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.score.director.InnerScoreDirector;
import ai.timefold.solver.core.preview.api.domain.metamodel.ElementPosition;
import ai.timefold.solver.core.preview.api.domain.metamodel.PositionInList;
import org.jspecify.annotations.NonNull;
final class ExternalizedListVariableStateSupply<Solution_>
implements ListVariableStateSupply<Solution_> {
private final ListVariableDescriptor<Solution_> sourceVariableDescriptor;
private final ListVariableState<Solution_> listVariableState;
private boolean previousExternalized = false;
private boolean nextExternalized = false;
private Solution_ workingSolution;
public ExternalizedListVariableStateSupply(ListVariableDescriptor<Solution_> sourceVariableDescriptor) {
this.sourceVariableDescriptor = sourceVariableDescriptor;
this.listVariableState = new ListVariableState<>(sourceVariableDescriptor);
}
@Override
public void externalize(IndexShadowVariableDescriptor<Solution_> shadowVariableDescriptor) {
listVariableState.linkShadowVariable(shadowVariableDescriptor);
}
@Override
public void externalize(InverseRelationShadowVariableDescriptor<Solution_> shadowVariableDescriptor) {
listVariableState.linkShadowVariable(shadowVariableDescriptor);
}
@Override
public void externalize(PreviousElementShadowVariableDescriptor<Solution_> shadowVariableDescriptor) {
listVariableState.linkShadowVariable(shadowVariableDescriptor);
previousExternalized = true;
}
@Override
public void externalize(NextElementShadowVariableDescriptor<Solution_> shadowVariableDescriptor) {
listVariableState.linkShadowVariable(shadowVariableDescriptor);
nextExternalized = true;
}
@Override
public void resetWorkingSolution(@NonNull ScoreDirector<Solution_> scoreDirector) {
workingSolution = scoreDirector.getWorkingSolution();
var innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
listVariableState.initialize(innerScoreDirector, (int) innerScoreDirector.getValueRangeManager()
.countOnSolution(sourceVariableDescriptor.getValueRangeDescriptor(), workingSolution));
// Will run over all entities and unmark all present elements as unassigned.
sourceVariableDescriptor.getEntityDescriptor()
.visitAllEntities(workingSolution, this::insert);
}
private void insert(Object entity) {
var assignedElements = sourceVariableDescriptor.getValue(entity);
var index = 0;
for (var element : assignedElements) {
listVariableState.addElement(entity, assignedElements, element, index);
index++;
}
}
@Override
public void beforeEntityAdded(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) {
// No need to do anything.
}
@Override
public void afterEntityAdded(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) {
insert(entity);
}
@Override
public void beforeEntityRemoved(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) {
// No need to do anything.
}
@Override
public void afterEntityRemoved(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) {
// When the entity is removed, its values become unassigned.
// An unassigned value has no inverse entity and no index.
var assignedElements = sourceVariableDescriptor.getValue(entity);
for (var index = 0; index < assignedElements.size(); index++) {
listVariableState.removeElement(entity, assignedElements.get(index), index);
}
}
@Override
public void afterListVariableElementUnassigned(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object element) {
listVariableState.unassignElement(element);
}
@Override
public void beforeListVariableChanged(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity,
int fromIndex, int toIndex) {
// No need to do anything.
}
@Override
public void afterListVariableChanged(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity, int fromIndex,
int toIndex) {
var assignedElements = sourceVariableDescriptor.getValue(entity);
var elementCount = assignedElements.size();
// Include the last element of the previous part of the list, if any, for the next element shadow var.
// But only if the next element shadow var is externalized; otherwise, there is nothing to update.
var firstChangeIndex = nextExternalized ? Math.max(0, fromIndex - 1) : fromIndex;
// Include the first element of the next part of the list, if any, for the previous element shadow var.
// But only if the previous element shadow var is externalized; otherwise, there is nothing to update.
var lastChangeIndex = previousExternalized ? Math.min(toIndex + 1, elementCount) : toIndex;
for (var index = firstChangeIndex; index < elementCount; index++) {
var positionsDiffer = listVariableState.changeElement(entity, assignedElements, index);
if (!positionsDiffer && index >= lastChangeIndex) {
// Position is unchanged and we are past the part of the list that changed.
// We can terminate the loop prematurely.
return;
}
}
}
@Override
public ElementPosition getElementPosition(Object planningValue) {
return listVariableState.getElementPosition(planningValue);
}
@Override
public Integer getIndex(Object planningValue) {
return listVariableState.getIndex(planningValue);
}
@Override
public Object getInverseSingleton(Object planningValue) {
return listVariableState.getInverseSingleton(planningValue);
}
@Override
public boolean isAssigned(Object element) {
return getInverseSingleton(element) != null;
}
@Override
public boolean isPinned(Object element) {
if (!sourceVariableDescriptor.supportsPinning()) {
return false;
}
var position = getElementPosition(element);
if (position instanceof PositionInList assignedPosition) {
return sourceVariableDescriptor.isElementPinned(workingSolution, assignedPosition.entity(),
assignedPosition.index());
} else {
return false;
}
}
@Override
public int getUnassignedCount() {
return listVariableState.getUnassignedCount();
}
@Override
public Object getPreviousElement(Object element) {
return listVariableState.getPreviousElement(element);
}
@Override
public Object getNextElement(Object element) {
return listVariableState.getNextElement(element);
}
@Override
public ListVariableDescriptor<Solution_> getSourceVariableDescriptor() {
return sourceVariableDescriptor;
}
@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 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/ExternalizedNextPrevElementVariableProcessor.java | package ai.timefold.solver.core.impl.domain.variable;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor;
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.score.director.InnerScoreDirector;
final class ExternalizedNextPrevElementVariableProcessor<Solution_> {
public static <Solution_> ExternalizedNextPrevElementVariableProcessor<Solution_>
ofPrevious(PreviousElementShadowVariableDescriptor<Solution_> shadowVariableDescriptor) {
return new ExternalizedNextPrevElementVariableProcessor<>(shadowVariableDescriptor, -1);
}
public static <Solution_> ExternalizedNextPrevElementVariableProcessor<Solution_>
ofNext(NextElementShadowVariableDescriptor<Solution_> shadowVariableDescriptor) {
return new ExternalizedNextPrevElementVariableProcessor<>(shadowVariableDescriptor, 1);
}
private final ShadowVariableDescriptor<Solution_> shadowVariableDescriptor;
private final int modifier;
private ExternalizedNextPrevElementVariableProcessor(ShadowVariableDescriptor<Solution_> shadowVariableDescriptor,
int modifier) {
this.shadowVariableDescriptor = Objects.requireNonNull(shadowVariableDescriptor);
this.modifier = modifier;
}
public void setElement(InnerScoreDirector<Solution_, ?> scoreDirector, List<Object> listVariable, Object element,
int index) {
var target = index + modifier;
if (target < 0 || target >= listVariable.size()) {
setValue(scoreDirector, element, null);
} else {
setValue(scoreDirector, element, listVariable.get(target));
}
}
private void setValue(InnerScoreDirector<Solution_, ?> scoreDirector, Object element, Object value) {
if (getElement(element) != value) {
scoreDirector.beforeVariableChanged(shadowVariableDescriptor, element);
shadowVariableDescriptor.setValue(element, value);
scoreDirector.afterVariableChanged(shadowVariableDescriptor, element);
}
}
public Object getElement(Object element) {
return shadowVariableDescriptor.getValue(element);
}
public void unsetElement(InnerScoreDirector<Solution_, ?> scoreDirector, Object element) {
setValue(scoreDirector, element, null);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/ListVariableState.java | package ai.timefold.solver.core.impl.domain.variable;
import java.util.List;
import java.util.Map;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
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.nextprev.NextElementShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.nextprev.PreviousElementShadowVariableDescriptor;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.util.CollectionUtils;
import ai.timefold.solver.core.preview.api.domain.metamodel.ElementPosition;
import ai.timefold.solver.core.preview.api.domain.metamodel.PositionInList;
final class ListVariableState<Solution_> {
private final ListVariableDescriptor<Solution_> sourceVariableDescriptor;
private ExternalizedIndexVariableProcessor<Solution_> externalizedIndexProcessor = null;
private ExternalizedListInverseVariableProcessor<Solution_> externalizedInverseProcessor = null;
private ExternalizedNextPrevElementVariableProcessor<Solution_> externalizedPreviousElementProcessor = null;
private ExternalizedNextPrevElementVariableProcessor<Solution_> externalizedNextElementProcessor = null;
private boolean requiresPositionMap = true;
private InnerScoreDirector<Solution_, ?> scoreDirector;
private int unassignedCount = 0;
private Map<Object, MutablePosition> elementPositionMap;
public ListVariableState(ListVariableDescriptor<Solution_> sourceVariableDescriptor) {
this.sourceVariableDescriptor = sourceVariableDescriptor;
}
public void linkShadowVariable(IndexShadowVariableDescriptor<Solution_> shadowVariableDescriptor) {
this.externalizedIndexProcessor = new ExternalizedIndexVariableProcessor<>(shadowVariableDescriptor);
}
public void linkShadowVariable(InverseRelationShadowVariableDescriptor<Solution_> shadowVariableDescriptor) {
this.externalizedInverseProcessor =
new ExternalizedListInverseVariableProcessor<>(shadowVariableDescriptor, sourceVariableDescriptor);
}
public void linkShadowVariable(PreviousElementShadowVariableDescriptor<Solution_> shadowVariableDescriptor) {
this.externalizedPreviousElementProcessor =
ExternalizedNextPrevElementVariableProcessor.ofPrevious(shadowVariableDescriptor);
}
public void linkShadowVariable(NextElementShadowVariableDescriptor<Solution_> shadowVariableDescriptor) {
this.externalizedNextElementProcessor = ExternalizedNextPrevElementVariableProcessor.ofNext(shadowVariableDescriptor);
}
public void initialize(InnerScoreDirector<Solution_, ?> scoreDirector, int initialUnassignedCount) {
this.scoreDirector = scoreDirector;
this.unassignedCount = initialUnassignedCount;
this.requiresPositionMap = externalizedIndexProcessor == null || externalizedInverseProcessor == null
|| externalizedPreviousElementProcessor == null || externalizedNextElementProcessor == null;
if (requiresPositionMap) {
if (elementPositionMap == null) {
elementPositionMap = CollectionUtils.newIdentityHashMap(unassignedCount);
} else {
elementPositionMap.clear();
}
} else {
elementPositionMap = null;
}
}
public void addElement(Object entity, List<Object> elements, Object element, int index) {
if (requiresPositionMap) {
var oldPosition = elementPositionMap.put(element, new MutablePosition(entity, index));
if (oldPosition != null) {
throw new IllegalStateException(
"The supply for list variable (%s) is corrupted, because the element (%s) at index (%d) already exists (%s)."
.formatted(sourceVariableDescriptor, element, index, oldPosition));
}
}
if (externalizedIndexProcessor != null) {
externalizedIndexProcessor.addElement(scoreDirector, element, index);
}
if (externalizedInverseProcessor != null) {
externalizedInverseProcessor.addElement(scoreDirector, entity, element);
}
if (externalizedPreviousElementProcessor != null) {
externalizedPreviousElementProcessor.setElement(scoreDirector, elements, element, index);
}
if (externalizedNextElementProcessor != null) {
externalizedNextElementProcessor.setElement(scoreDirector, elements, element, index);
}
unassignedCount--;
}
public void removeElement(Object entity, Object element, int index) {
if (requiresPositionMap) {
var oldPosition = elementPositionMap.remove(element);
if (oldPosition == null) {
throw new IllegalStateException(
"The supply for list variable (%s) is corrupted, because the element (%s) at index (%d) was already unassigned (%s)."
.formatted(sourceVariableDescriptor, element, index, oldPosition));
}
var oldIndex = oldPosition.getIndex();
if (oldIndex != index) {
throw new IllegalStateException(
"The supply for list variable (%s) is corrupted, because the element (%s) at index (%d) had an old index (%d) which is not the current index (%d)."
.formatted(sourceVariableDescriptor, element, index, oldIndex, index));
}
}
if (externalizedIndexProcessor != null) {
externalizedIndexProcessor.removeElement(scoreDirector, element);
}
if (externalizedInverseProcessor != null) {
externalizedInverseProcessor.removeElement(scoreDirector, entity, element);
}
if (externalizedPreviousElementProcessor != null) {
externalizedPreviousElementProcessor.unsetElement(scoreDirector, element);
}
if (externalizedNextElementProcessor != null) {
externalizedNextElementProcessor.unsetElement(scoreDirector, element);
}
unassignedCount++;
}
public void unassignElement(Object element) {
if (requiresPositionMap) {
var oldPosition = elementPositionMap.remove(element);
if (oldPosition == null) {
throw new IllegalStateException(
"The supply for list variable (%s) is corrupted, because the element (%s) did not exist before unassigning."
.formatted(sourceVariableDescriptor, element));
}
}
if (externalizedIndexProcessor != null) {
externalizedIndexProcessor.unassignElement(scoreDirector, element);
}
if (externalizedInverseProcessor != null) {
externalizedInverseProcessor.unassignElement(scoreDirector, element);
}
if (externalizedPreviousElementProcessor != null) {
externalizedPreviousElementProcessor.unsetElement(scoreDirector, element);
}
if (externalizedNextElementProcessor != null) {
externalizedNextElementProcessor.unsetElement(scoreDirector, element);
}
unassignedCount++;
}
public boolean changeElement(Object entity, List<Object> elements, int index) {
var element = elements.get(index);
var difference = processElementPosition(entity, element, index);
if (difference.indexChanged && externalizedIndexProcessor != null) {
externalizedIndexProcessor.changeElement(scoreDirector, element, index);
}
if (difference.entityChanged && externalizedInverseProcessor != null) {
externalizedInverseProcessor.changeElement(scoreDirector, entity, element);
}
// Next and previous still might have changed, even if the index and entity did not.
// Those are based on what happened elsewhere in the list.
if (externalizedPreviousElementProcessor != null) {
externalizedPreviousElementProcessor.setElement(scoreDirector, elements, element, index);
}
if (externalizedNextElementProcessor != null) {
externalizedNextElementProcessor.setElement(scoreDirector, elements, element, index);
}
return difference.anythingChanged;
}
private ChangeType processElementPosition(Object entity, Object element, int index) {
if (requiresPositionMap) { // Update the position and figure out if it is different from previous.
var oldPosition = elementPositionMap.get(element);
if (oldPosition == null) {
elementPositionMap.put(element, new MutablePosition(entity, index));
unassignedCount--;
return ChangeType.BOTH;
}
var changeType = comparePositions(entity, oldPosition.getEntity(), index, oldPosition.getIndex());
if (changeType.anythingChanged) { // Replace the map value in-place, to avoid a put() on the hot path.
if (changeType.entityChanged) {
oldPosition.setEntity(entity);
}
if (changeType.indexChanged) {
oldPosition.setIndex(index);
}
}
return changeType;
} else { // Read the position and figure out if it is different from previous.
var oldEntity = getInverseSingleton(element);
if (oldEntity == null) {
unassignedCount--;
return ChangeType.BOTH;
}
var oldIndex = getIndex(element);
if (oldIndex == null) { // Technically impossible, but we handle it anyway.
return ChangeType.BOTH;
}
return comparePositions(entity, oldEntity, index, oldIndex);
}
}
private static ChangeType comparePositions(Object entity, Object otherEntity, int index, int otherIndex) {
if (entity != otherEntity) {
return ChangeType.BOTH; // Entity changed, so index changed too.
} else if (index != otherIndex) {
return ChangeType.INDEX;
} else {
return ChangeType.NEITHER;
}
}
public ElementPosition getElementPosition(Object planningValue) {
if (requiresPositionMap) {
var mutablePosition = elementPositionMap.get(planningValue);
if (mutablePosition == null) {
return ElementPosition.unassigned();
}
return mutablePosition.getPosition();
} else { // At this point, both inverse and index are externalized.
var inverse = externalizedInverseProcessor.getInverseSingleton(planningValue);
if (inverse == null) {
return ElementPosition.unassigned();
}
return ElementPosition.of(inverse, externalizedIndexProcessor.getIndex(planningValue));
}
}
public Integer getIndex(Object planningValue) {
if (externalizedIndexProcessor == null) {
var position = elementPositionMap.get(planningValue);
if (position == null) {
return null;
}
return position.getIndex();
}
return externalizedIndexProcessor.getIndex(planningValue);
}
public Object getInverseSingleton(Object planningValue) {
if (externalizedInverseProcessor == null) {
var position = elementPositionMap.get(planningValue);
if (position == null) {
return null;
}
return position.getEntity();
}
return externalizedInverseProcessor.getInverseSingleton(planningValue);
}
public Object getPreviousElement(Object element) {
if (externalizedPreviousElementProcessor == null) {
var mutablePosition = elementPositionMap.get(element);
if (mutablePosition == null) {
return null;
}
var index = mutablePosition.getIndex();
if (index == 0) {
return null;
}
return sourceVariableDescriptor.getValue(mutablePosition.getEntity())
.get(index - 1);
}
return externalizedPreviousElementProcessor.getElement(element);
}
public Object getNextElement(Object element) {
if (externalizedNextElementProcessor == null) {
var mutablePosition = elementPositionMap.get(element);
if (mutablePosition == null) {
return null;
}
var list = sourceVariableDescriptor.getValue(mutablePosition.getEntity());
var index = mutablePosition.getIndex();
if (index == list.size() - 1) {
return null;
}
return list.get(index + 1);
}
return externalizedNextElementProcessor.getElement(element);
}
public int getUnassignedCount() {
return unassignedCount;
}
private enum ChangeType {
BOTH(true, true),
INDEX(false, true),
NEITHER(false, false);
final boolean anythingChanged;
final boolean entityChanged;
final boolean indexChanged;
ChangeType(boolean entityChanged, boolean indexChanged) {
this.anythingChanged = entityChanged || indexChanged;
this.entityChanged = entityChanged;
this.indexChanged = indexChanged;
}
}
/**
* This class is used to avoid creating a new {@link PositionInList} object every time we need to return a position.
* The actual value is held in a map and can be updated without doing a put() operation, which is more efficient.
* The {@link PositionInList} object is only created when it is actually requested,
* and stored until the next time the mutable state is updated and therefore the cache invalidated.
*/
private static final class MutablePosition {
private Object entity;
private int index;
private PositionInList position;
public MutablePosition(Object entity, int index) {
this.entity = entity;
this.index = index;
}
public Object getEntity() {
return entity;
}
public void setEntity(Object entity) {
this.entity = entity;
this.position = null;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
this.position = null;
}
public PositionInList getPosition() {
if (position == null) {
position = ElementPosition.of(entity, index);
}
return position;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/ListVariableStateDemand.java | package ai.timefold.solver.core.impl.domain.variable;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.supply.AbstractVariableDescriptorBasedDemand;
import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
public final class ListVariableStateDemand<Solution_>
extends AbstractVariableDescriptorBasedDemand<Solution_, ListVariableStateSupply<Solution_>> {
public ListVariableStateDemand(ListVariableDescriptor<Solution_> variableDescriptor) {
super(variableDescriptor);
}
@Override
public ListVariableStateSupply<Solution_> createExternalizedSupply(SupplyManager supplyManager) {
var listVariableDescriptor = (ListVariableDescriptor<Solution_>) variableDescriptor;
return new ExternalizedListVariableStateSupply<>(listVariableDescriptor);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/ListVariableStateSupply.java | package ai.timefold.solver.core.impl.domain.variable;
import ai.timefold.solver.core.api.domain.variable.ListVariableListener;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.index.IndexShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.index.IndexVariableSupply;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.InverseRelationShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import ai.timefold.solver.core.impl.domain.variable.listener.SourcedVariableListener;
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.preview.api.domain.metamodel.ElementPosition;
/**
* Single source of truth for all information about elements inside {@link PlanningListVariable list variables}.
* Shadow variables can be connected to this class to save on iteration costs
* that would've been incurred otherwise if using variable listeners for each of them independently.
* This way, there is only one variable listener for all such shadow variables,
* and therefore only a single iteration to update all the information.
*
* <p>
* If a particular shadow variable is externalized,
* it means that there is a field on an entity holding the value of the shadow variable.
* In this case, we will attempt to use that value.
* Otherwise, we will keep an internal track of all the possible shadow variables
* ({@link ai.timefold.solver.core.api.domain.variable.IndexShadowVariable},
* {@link ai.timefold.solver.core.api.domain.variable.InverseRelationShadowVariable},
* {@link ai.timefold.solver.core.api.domain.variable.PreviousElementShadowVariable},
* {@link ai.timefold.solver.core.api.domain.variable.NextElementShadowVariable}),
* and use values from this internal representation.
*
* @param <Solution_>
* @see ListVariableState The logic of switching between internal and externalized shadow variables.
* @see ExternalizedListVariableStateSupply The external representation of these shadow variables,
* which doesn't care whether the variable is internal or externalized.
*/
public interface ListVariableStateSupply<Solution_> extends
SourcedVariableListener<Solution_>,
ListVariableListener<Solution_, Object, Object>,
SingletonInverseVariableSupply,
IndexVariableSupply {
void externalize(IndexShadowVariableDescriptor<Solution_> shadowVariableDescriptor);
void externalize(InverseRelationShadowVariableDescriptor<Solution_> shadowVariableDescriptor);
void externalize(PreviousElementShadowVariableDescriptor<Solution_> shadowVariableDescriptor);
void externalize(NextElementShadowVariableDescriptor<Solution_> shadowVariableDescriptor);
@Override
ListVariableDescriptor<Solution_> getSourceVariableDescriptor();
/**
*
* @param element never null
* @return true if the element is contained in a list variable of any entity.
*/
boolean isAssigned(Object element);
/**
*
* @param element never null
* @return true if the element is in a pinned part of a list variable of any entity
*/
boolean isPinned(Object element);
/**
*
* @param value never null
* @return never null
*/
ElementPosition getElementPosition(Object value);
/**
* Consider calling this before {@link #isAssigned(Object)} to eliminate some map accesses.
* If unassigned count is 0, {@link #isAssigned(Object)} is guaranteed to return true.
*
* @return number of elements for which {@link #isAssigned(Object)} would return false.
*/
int getUnassignedCount();
/**
*
* @param element never null
* @return null if the element is the first element in the list
*/
Object getPreviousElement(Object element);
/**
*
* @param element never null
* @return null if the element is the last element in the list
*/
Object getNextElement(Object element);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/domain/variable/ShadowVariableUpdateHelper.java | package ai.timefold.solver.core.impl.domain.variable;
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 static ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy.DISABLED;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.variable.CascadingUpdateShadowVariable;
import ai.timefold.solver.core.api.domain.variable.IndexShadowVariable;
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.PreviousElementShadowVariable;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal;
import ai.timefold.solver.core.api.score.constraint.Indictment;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.solution.descriptor.DefaultShadowVariableMetaModel;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.domain.variable.cascade.CascadingUpdateShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.custom.CustomShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.declarative.ChangedVariableNotifier;
import ai.timefold.solver.core.impl.domain.variable.declarative.DefaultShadowVariableSessionFactory;
import ai.timefold.solver.core.impl.domain.variable.declarative.VariableReferenceGraph;
import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor;
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.support.ShadowVariableType;
import ai.timefold.solver.core.impl.domain.variable.listener.support.VariableListenerSupport;
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.score.director.AbstractScoreDirector;
import ai.timefold.solver.core.impl.score.director.AbstractScoreDirectorFactory;
import ai.timefold.solver.core.impl.score.director.InnerScore;
import ai.timefold.solver.core.preview.api.domain.metamodel.ShadowVariableMetaModel;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/**
* Utility class for updating shadow variables at entity level.
*/
@NullMarked
public final class ShadowVariableUpdateHelper<Solution_> {
private static final EnumSet<ShadowVariableType> SUPPORTED_TYPES =
EnumSet.of(BASIC, CUSTOM_LISTENER, CASCADING_UPDATE, DECLARATIVE);
public static <Solution_> ShadowVariableUpdateHelper<Solution_> create() {
return new ShadowVariableUpdateHelper<>(SUPPORTED_TYPES);
}
// Testing purposes
static <Solution_> ShadowVariableUpdateHelper<Solution_> create(ShadowVariableType... supportedTypes) {
var typesSet = EnumSet.noneOf(ShadowVariableType.class);
typesSet.addAll(Arrays.asList(supportedTypes));
return new ShadowVariableUpdateHelper<>(typesSet);
}
private final EnumSet<ShadowVariableType> supportedShadowVariableTypes;
private ShadowVariableUpdateHelper(EnumSet<ShadowVariableType> supportedShadowVariableTypes) {
this.supportedShadowVariableTypes = supportedShadowVariableTypes;
}
@SuppressWarnings("unchecked")
public void updateShadowVariables(Solution_ solution) {
var solutionClass = (Class<Solution_>) Objects.requireNonNull(solution).getClass();
var initialSolutionDescriptor = SolutionDescriptor.buildSolutionDescriptor(solutionClass);
var entityClassSet = new LinkedHashSet<Class<?>>();
initialSolutionDescriptor.visitAllEntities(solution, entity -> entityClassSet.add(entity.getClass()));
var solutionDescriptor = SolutionDescriptor.buildSolutionDescriptor(solutionClass,
entityClassSet.toArray(new Class<?>[0]));
try (var scoreDirector = new InternalScoreDirector.Builder<>(solutionDescriptor).build()) {
// When we have a solution, we can reuse the logic from VariableListenerSupport to update all variable types
scoreDirector.setWorkingSolution(solution);
}
}
public void updateShadowVariables(Class<Solution_> solutionClass, Object... entities) {
var entityClassList = Arrays.stream(entities).map(Object::getClass)
.filter(clazz -> clazz.isAnnotationPresent(PlanningEntity.class))
.distinct().toList();
var solutionDescriptor =
SolutionDescriptor.buildSolutionDescriptor(Objects.requireNonNull(solutionClass),
entityClassList.toArray(new Class<?>[0]));
var customShadowVariableDescriptorList = solutionDescriptor.getAllShadowVariableDescriptors().stream()
.filter(CustomShadowVariableDescriptor.class::isInstance)
.toList();
if (!customShadowVariableDescriptorList.isEmpty()) {
throw new IllegalArgumentException(
"Custom shadow variable descriptors are not supported (%s)".formatted(customShadowVariableDescriptorList));
}
var variableListenerSupport =
VariableListenerSupport.create(new InternalScoreDirector.Builder<>(solutionDescriptor).build());
var missingShadowVariableTypeList = variableListenerSupport.getSupportedShadowVariableTypes().stream()
.filter(type -> !supportedShadowVariableTypes.contains(type))
.toList();
if (!missingShadowVariableTypeList.isEmpty()) {
throw new IllegalStateException(
"Impossible state: The following shadow variable types are not currently supported (%s)."
.formatted(missingShadowVariableTypeList));
}
// No solution, we trigger all supported events manually
var session = InternalShadowVariableSession.build(solutionDescriptor, entities);
// Update all built-in shadow variables
var listVariableDescriptor = solutionDescriptor.getListVariableDescriptor();
if (listVariableDescriptor == null) {
session.processBasicVariable(entities);
session.processChainedVariable(entities);
} else {
session.processListVariable(entities);
session.processCascadingVariable(entities);
}
session.processDeclarativeVariables();
}
private record InternalShadowVariableSession<Solution_>(SolutionDescriptor<Solution_> solutionDescriptor,
VariableReferenceGraph graph) {
public static <Solution_> InternalShadowVariableSession<Solution_> build(
SolutionDescriptor<Solution_> solutionDescriptor,
Object... entities) {
return new InternalShadowVariableSession<>(solutionDescriptor,
DefaultShadowVariableSessionFactory.buildGraph(
new DefaultShadowVariableSessionFactory.GraphDescriptor<>(solutionDescriptor,
ChangedVariableNotifier.empty(), entities)));
}
/**
* Identify and auto-update {@link InverseRelationShadowVariable inverse shadow variables} of shadow entities.
*
* @param entities the entities to be analyzed
*/
public void processBasicVariable(Object... entities) {
var shadowEntityToUpdate = new IdentityHashMap<Object, ShadowEntityVariable>();
for (var entityWithDescriptor : fetchEntityAndDescriptors(entities)) {
// Iterate over all basic variables and update the inverse relation field
for (var variableDescriptor : fetchBasicDescriptors(entityWithDescriptor.entityDescriptor(), false)) {
var shadowEntity = variableDescriptor.getValue(entityWithDescriptor.entity());
addShadowEntity(entityWithDescriptor, variableDescriptor, shadowEntity, shadowEntityToUpdate);
}
}
shadowEntityToUpdate.forEach((key, value) -> updateShadowVariable(value.variableName(), key, value.values()));
}
private void addShadowEntity(EntityWithDescriptor<Solution_> entityWithDescriptor,
BasicVariableDescriptor<Solution_> variableDescriptor, Object shadowEntity,
Map<Object, ShadowEntityVariable> shadowEntityToUpdate) {
// If the planning value is set, we update the inverse element collection
var descriptor = findShadowVariableDescriptor(shadowEntity.getClass(),
InverseRelationShadowVariableDescriptor.class);
if (descriptor != null) {
var values = (Collection<Object>) descriptor.getValue(shadowEntity);
if (values == null) {
throw new IllegalStateException(
"The entity (%s) has a variable (%s) with value (%s) which has a sourceVariableName variable (%s) which is null."
.formatted(entityWithDescriptor.entity().getClass(),
variableDescriptor.getVariableName(),
shadowEntity, descriptor.getVariableName()));
}
if (!values.contains(entityWithDescriptor.entity())) {
values.add(entityWithDescriptor.entity());
}
shadowEntityToUpdate.putIfAbsent(shadowEntity,
new ShadowEntityVariable(descriptor.getVariableName(), values));
}
}
/**
* Identify and auto-update {@link InverseRelationShadowVariable inverse shadow variables} of shadow entities for
* chained models.
*
* @param entities the entities to be analyzed
*/
public void processChainedVariable(Object... entities) {
for (var entityWithDescriptor : fetchEntityAndDescriptors(entities)) {
// We filter all planning entities and update the inverse shadow variable
for (var variableDescriptor : fetchBasicDescriptors(entityWithDescriptor.entityDescriptor(), true)) {
var shadowEntity = variableDescriptor.getValue(entityWithDescriptor.entity());
if (shadowEntity != null) {
// If the planning value is set, we update the inverse element
updateShadowVariable(shadowEntity.getClass(), InverseRelationShadowVariableDescriptor.class,
shadowEntity, entityWithDescriptor.entity());
}
}
}
}
/**
* Identify and auto-update the following shadow variables of shadow entities:
* {@link InverseRelationShadowVariable }, {@link PreviousElementShadowVariable}, {@link NextElementShadowVariable},
* and {@link IndexShadowVariable}.
*
* @param entities the entities to be analyzed
*/
public void processListVariable(Object... entities) {
var listVariableDescriptor = Objects.requireNonNull(solutionDescriptor.getListVariableDescriptor());
// We filter all planning entities and update the shadow variables of their planning values.
// There is no need to evaluate other variables from the entity,
// as we fail fast when variables based on listeners are detected.
var planningEntityList = Arrays.stream(entities)
.filter(entity -> listVariableDescriptor.getEntityDescriptor().getEntityClass()
.equals(entity.getClass()))
.toList();
for (var entity : planningEntityList) {
var values = listVariableDescriptor.getValue(entity);
if (values.isEmpty()) {
continue;
}
var entityType = values.get(0).getClass();
for (var i = 0; i < values.size(); i++) {
var shadowEntity = values.get(i);
// Inverse relation
updateShadowVariable(entityType, InverseRelationShadowVariableDescriptor.class, shadowEntity,
entity);
// Previous element
var previousElement = i > 0 ? values.get(i - 1) : null;
updateShadowVariable(entityType, PreviousElementShadowVariableDescriptor.class, shadowEntity,
previousElement);
// Next element
var nextElement = i < values.size() - 1 ? values.get(i + 1) : null;
updateShadowVariable(entityType, NextElementShadowVariableDescriptor.class, shadowEntity,
nextElement);
// Index
updateShadowVariable(entityType, IndexShadowVariableDescriptor.class, shadowEntity, i);
}
}
}
/**
* Identify and auto-update {@link CascadingUpdateShadowVariable shadow
* variables} of entities.
*
* @param entities the entities to be analyzed
*/
@SuppressWarnings("unchecked")
public void processCascadingVariable(Object... entities) {
var listVariableDescriptor = solutionDescriptor.getListVariableDescriptor();
if (listVariableDescriptor != null) {
for (var entity : entities) {
var cascadingVariableDescriptor =
findShadowVariableDescriptor(entity.getClass(), CascadingUpdateShadowVariableDescriptor.class);
if (cascadingVariableDescriptor != null) {
cascadingVariableDescriptor.update(new InternalScoreDirector.Builder<>(solutionDescriptor).build(),
entity);
}
}
}
}
@SuppressWarnings("unchecked")
private <T> @Nullable T findShadowVariableDescriptor(Class<?> entityType, Class<T> descriptorType) {
var valueMetaModel = solutionDescriptor.getMetaModel().entities().stream()
.filter(type -> type.type().equals(entityType))
.findFirst()
.orElse(null);
if (valueMetaModel == null) {
return null;
}
return (T) valueMetaModel.variables().stream()
.filter(ShadowVariableMetaModel.class::isInstance)
.map(DefaultShadowVariableMetaModel.class::cast)
.map(DefaultShadowVariableMetaModel::variableDescriptor)
.filter(descriptorType::isInstance)
.findFirst()
.orElse(null);
}
private void updateShadowVariable(String variableName, Object destination, @Nullable Object value) {
var variableDescriptor =
solutionDescriptor.getEntityDescriptorStrict(destination.getClass()).getVariableDescriptor(variableName);
if (solutionDescriptor.getDeclarativeShadowVariableDescriptors().isEmpty() && variableDescriptor != null) {
variableDescriptor.setValue(destination, value);
} else if (variableDescriptor != null) {
var variableMetamodel = solutionDescriptor.getMetaModel().entity(destination.getClass()).variable(variableName);
graph.beforeVariableChanged(variableMetamodel, destination);
variableDescriptor.setValue(destination, value);
graph.afterVariableChanged(variableMetamodel, destination);
}
}
@SuppressWarnings("rawtypes")
private void updateShadowVariable(Class<?> entityType,
Class<? extends ShadowVariableDescriptor> descriptorType, Object destination, @Nullable Object value) {
var descriptor = findShadowVariableDescriptor(entityType, descriptorType);
if (descriptor != null) {
updateShadowVariable(descriptor.getVariableName(), destination, value);
}
}
public void processDeclarativeVariables() {
if (!solutionDescriptor.getDeclarativeShadowVariableDescriptors().isEmpty()) {
graph.updateChanged();
}
}
private List<EntityWithDescriptor<Solution_>> fetchEntityAndDescriptors(Object... entities) {
var descriptorList = new ArrayList<EntityWithDescriptor<Solution_>>();
var genuineEntityDescriptorCollection = solutionDescriptor.getGenuineEntityDescriptors();
for (var entity : entities) {
genuineEntityDescriptorCollection.stream()
.filter(variableDescriptor -> variableDescriptor.getEntityClass().equals(entity.getClass()))
.findFirst()
.ifPresent(genuineEntityDescriptor -> descriptorList
.add(new EntityWithDescriptor<>(entity, genuineEntityDescriptor)));
}
return descriptorList;
}
private List<BasicVariableDescriptor<Solution_>> fetchBasicDescriptors(EntityDescriptor<Solution_> entityDescriptor,
boolean chained) {
var descriptorList = new ArrayList<BasicVariableDescriptor<Solution_>>();
for (var descriptor : entityDescriptor.getDeclaredGenuineVariableDescriptors()) {
if (descriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor
&& ((!chained && !basicVariableDescriptor.isChained())
|| (chained && basicVariableDescriptor.isChained()))) {
descriptorList.add(basicVariableDescriptor);
}
}
return descriptorList;
}
}
private static class InternalScoreDirectorFactory<Solution_, Score_ extends Score<Score_>>
extends AbstractScoreDirectorFactory<Solution_, Score_, InternalScoreDirectorFactory<Solution_, Score_>> {
public InternalScoreDirectorFactory(SolutionDescriptor<Solution_> solutionDescriptor) {
super(solutionDescriptor);
}
@Override
public AbstractScoreDirector.AbstractScoreDirectorBuilder<Solution_, Score_, ?, ?> createScoreDirectorBuilder() {
throw new UnsupportedOperationException();
}
}
private static class InternalScoreDirector<Solution_, Score_ extends Score<Score_>>
extends AbstractScoreDirector<Solution_, Score_, InternalScoreDirectorFactory<Solution_, Score_>> {
private InternalScoreDirector(Builder<Solution_, Score_> builder) {
super(builder);
}
@Override
public void setWorkingSolutionWithoutUpdatingShadows(Solution_ workingSolution) {
super.setWorkingSolutionWithoutUpdatingShadows(workingSolution, ignore -> {
});
}
@Override
public InnerScore<Score_> calculateScore() {
throw new UnsupportedOperationException();
}
@Override
public Map<String, ConstraintMatchTotal<Score_>> getConstraintMatchTotalMap() {
throw new UnsupportedOperationException();
}
@Override
public Map<Object, Indictment<Score_>> getIndictmentMap() {
throw new UnsupportedOperationException();
}
@Override
public boolean requiresFlushing() {
throw new UnsupportedOperationException();
}
@NullMarked
public static final class Builder<Solution_, Score_ extends Score<Score_>>
extends
AbstractScoreDirectorBuilder<Solution_, Score_, InternalScoreDirectorFactory<Solution_, Score_>, InternalScoreDirector.Builder<Solution_, Score_>> {
public Builder(SolutionDescriptor<Solution_> solutionDescriptor) {
super(new InternalScoreDirectorFactory<>(solutionDescriptor));
withConstraintMatchPolicy(DISABLED);
withLookUpEnabled(false);
withExpectShadowVariablesInCorrectState(false);
}
@Override
public InternalScoreDirector<Solution_, Score_> build() {
return new InternalScoreDirector<>(this);
}
}
}
private record ShadowEntityVariable(String variableName, Collection<Object> values) {
}
private record EntityWithDescriptor<Solution_>(Object entity, EntityDescriptor<Solution_> entityDescriptor) {
}
}
|
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/anchor/AnchorShadowVariableDescriptor.java | package ai.timefold.solver.core.impl.domain.variable.anchor;
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.AnchorShadowVariable;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy;
import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableDemand;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import ai.timefold.solver.core.impl.domain.variable.listener.VariableListenerWithSources;
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 AnchorShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> {
private VariableDescriptor<Solution_> sourceVariableDescriptor;
public AnchorShadowVariableDescriptor(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);
}
private void linkShadowSources(DescriptorPolicy descriptorPolicy) {
AnchorShadowVariable shadowVariableAnnotation = variableMemberAccessor.getAnnotation(AnchorShadowVariable.class);
String sourceVariableName = shadowVariableAnnotation.sourceVariableName();
sourceVariableDescriptor = entityDescriptor.getVariableDescriptor(sourceVariableName);
if (sourceVariableDescriptor == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has an @" + AnchorShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with sourceVariableName (" + sourceVariableName
+ ") which is not a valid planning variable on entityClass ("
+ entityDescriptor.getEntityClass() + ").\n"
+ entityDescriptor.buildInvalidVariableNameExceptionMessage(sourceVariableName));
}
if (!(sourceVariableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor) ||
!basicVariableDescriptor.isChained()) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has an @" + AnchorShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with sourceVariableName (" + sourceVariableName
+ ") which is not chained.");
}
sourceVariableDescriptor.registerSinkVariableDescriptor(this);
}
@Override
public List<VariableDescriptor<Solution_>> getSourceVariableDescriptorList() {
return Collections.singletonList(sourceVariableDescriptor);
}
@Override
public Collection<Class<? extends AbstractVariableListener>> getVariableListenerClasses() {
return Collections.singleton(AnchorVariableListener.class);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public AnchorVariableDemand<Solution_> getProvidedDemand() {
return new AnchorVariableDemand<>(sourceVariableDescriptor);
}
@Override
public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) {
SingletonInverseVariableSupply inverseVariableSupply = supplyManager
.demand(new SingletonInverseVariableDemand<>(sourceVariableDescriptor));
return new VariableListenerWithSources<>(
new AnchorVariableListener<>(this, sourceVariableDescriptor, inverseVariableSupply),
sourceVariableDescriptor).toCollection();
}
@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/anchor/AnchorVariableDemand.java | package ai.timefold.solver.core.impl.domain.variable.anchor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableDemand;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import ai.timefold.solver.core.impl.domain.variable.supply.AbstractVariableDescriptorBasedDemand;
import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
public final class AnchorVariableDemand<Solution_>
extends AbstractVariableDescriptorBasedDemand<Solution_, AnchorVariableSupply> {
public AnchorVariableDemand(VariableDescriptor<Solution_> sourceVariableDescriptor) {
super(sourceVariableDescriptor);
}
// ************************************************************************
// Creation method
// ************************************************************************
@Override
public AnchorVariableSupply createExternalizedSupply(SupplyManager supplyManager) {
SingletonInverseVariableSupply inverseVariableSupply = supplyManager
.demand(new SingletonInverseVariableDemand<>(variableDescriptor));
return new ExternalizedAnchorVariableSupply<>(variableDescriptor, inverseVariableSupply);
}
}
|
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/anchor/AnchorVariableListener.java | package ai.timefold.solver.core.impl.domain.variable.anchor;
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;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import org.jspecify.annotations.NonNull;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class AnchorVariableListener<Solution_> implements VariableListener<Solution_, Object>, AnchorVariableSupply {
protected final AnchorShadowVariableDescriptor<Solution_> anchorShadowVariableDescriptor;
protected final VariableDescriptor<Solution_> previousVariableDescriptor;
protected final SingletonInverseVariableSupply nextVariableSupply;
public AnchorVariableListener(AnchorShadowVariableDescriptor<Solution_> anchorShadowVariableDescriptor,
VariableDescriptor<Solution_> previousVariableDescriptor,
SingletonInverseVariableSupply nextVariableSupply) {
this.anchorShadowVariableDescriptor = anchorShadowVariableDescriptor;
this.previousVariableDescriptor = previousVariableDescriptor;
this.nextVariableSupply = nextVariableSupply;
}
@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) {
// No need to retract() because the insert (which is guaranteed to be called later) affects the same trailing entities.
}
@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) {
// No need to retract() because the trailing entities will be removed too or change their previousVariable
}
@Override
public void afterEntityRemoved(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) {
// Do nothing
}
protected void insert(InnerScoreDirector<Solution_, ?> scoreDirector, Object entity) {
Object previousEntity = previousVariableDescriptor.getValue(entity);
Object anchor;
if (previousEntity == null) {
anchor = null;
} else if (previousVariableDescriptor.isValuePotentialAnchor(previousEntity)) {
anchor = previousEntity;
} else {
anchor = anchorShadowVariableDescriptor.getValue(previousEntity);
}
Object nextEntity = entity;
while (nextEntity != null && anchorShadowVariableDescriptor.getValue(nextEntity) != anchor) {
scoreDirector.beforeVariableChanged(anchorShadowVariableDescriptor, nextEntity);
anchorShadowVariableDescriptor.setValue(nextEntity, anchor);
scoreDirector.afterVariableChanged(anchorShadowVariableDescriptor, nextEntity);
nextEntity = nextVariableSupply.getInverseSingleton(nextEntity);
}
}
@Override
public Object getAnchor(Object entity) {
return anchorShadowVariableDescriptor.getValue(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/anchor/AnchorVariableSupply.java | package ai.timefold.solver.core.impl.domain.variable.anchor;
import ai.timefold.solver.core.impl.domain.variable.supply.Supply;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
/**
* Only supported for chained variables.
* <p>
* To get an instance, demand an {@link AnchorVariableDemand} from {@link InnerScoreDirector#getSupplyManager()}.
*/
public interface AnchorVariableSupply extends Supply {
/**
* @param entity never null
* @return sometimes null, the anchor for the entity
*/
Object getAnchor(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/anchor/ExternalizedAnchorVariableSupply.java | package ai.timefold.solver.core.impl.domain.variable.anchor;
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.inverserelation.SingletonInverseVariableSupply;
import ai.timefold.solver.core.impl.domain.variable.listener.SourcedVariableListener;
import org.jspecify.annotations.NonNull;
/**
* Alternative to {@link AnchorVariableListener}.
*/
public class ExternalizedAnchorVariableSupply<Solution_> implements
SourcedVariableListener<Solution_>,
VariableListener<Solution_, Object>,
AnchorVariableSupply {
protected final VariableDescriptor<Solution_> previousVariableDescriptor;
protected final SingletonInverseVariableSupply nextVariableSupply;
protected Map<Object, Object> anchorMap = null;
public ExternalizedAnchorVariableSupply(VariableDescriptor<Solution_> previousVariableDescriptor,
SingletonInverseVariableSupply nextVariableSupply) {
this.previousVariableDescriptor = previousVariableDescriptor;
this.nextVariableSupply = nextVariableSupply;
}
@Override
public VariableDescriptor<Solution_> getSourceVariableDescriptor() {
return previousVariableDescriptor;
}
@Override
public void resetWorkingSolution(@NonNull ScoreDirector<Solution_> scoreDirector) {
anchorMap = new IdentityHashMap<>();
previousVariableDescriptor.getEntityDescriptor().visitAllEntities(scoreDirector.getWorkingSolution(), this::insert);
}
@Override
public void close() {
anchorMap = 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) {
// No need to retract() because the insert (which is guaranteed to be called later) affects the same trailing entities.
}
@Override
public void afterVariableChanged(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) {
insert(entity);
}
@Override
public void beforeEntityRemoved(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) {
boolean removeSucceeded = anchorMap.remove(entity) != null;
if (!removeSucceeded) {
throw new IllegalStateException("The supply (" + this + ") is corrupted,"
+ " because the entity (" + entity
+ ") for sourceVariable (" + previousVariableDescriptor.getVariableName()
+ ") cannot be retracted: it was never inserted.");
}
// No need to retract the trailing entities because they will be removed too or change their previousVariable
}
@Override
public void afterEntityRemoved(@NonNull ScoreDirector<Solution_> scoreDirector, @NonNull Object entity) {
// Do nothing
}
protected void insert(Object entity) {
Object previousEntity = previousVariableDescriptor.getValue(entity);
Object anchor;
if (previousEntity == null) {
anchor = null;
} else if (previousVariableDescriptor.isValuePotentialAnchor(previousEntity)) {
anchor = previousEntity;
} else {
anchor = anchorMap.get(previousEntity);
}
Object nextEntity = entity;
while (nextEntity != null && anchorMap.get(nextEntity) != anchor) {
anchorMap.put(nextEntity, anchor);
nextEntity = nextVariableSupply.getInverseSingleton(nextEntity);
}
}
@Override
public Object getAnchor(Object entity) {
return anchorMap.get(entity);
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + previousVariableDescriptor.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/cascade/CascadingUpdateShadowVariableDescriptor.java | package ai.timefold.solver.core.impl.domain.variable.cascade;
import static java.util.stream.Collectors.joining;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener;
import ai.timefold.solver.core.api.domain.variable.CascadingUpdateShadowVariable;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory;
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 final class CascadingUpdateShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> {
private final List<ShadowVariableTarget<Solution_>> shadowVariableTargetList;
private final List<VariableDescriptor<Solution_>> targetVariableDescriptorList = new ArrayList<>();
private VariableDescriptor<Solution_> firstTargetVariableDescriptor;
private MemberAccessor targetMethod;
public CascadingUpdateShadowVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor,
MemberAccessor variableMemberAccessor) {
super(ordinal, entityDescriptor, variableMemberAccessor);
shadowVariableTargetList = new ArrayList<>();
addTargetVariable(entityDescriptor, variableMemberAccessor);
}
public void addTargetVariable(EntityDescriptor<Solution_> entityDescriptor,
MemberAccessor variableMemberAccessor) {
shadowVariableTargetList.add(new ShadowVariableTarget<>(entityDescriptor, variableMemberAccessor));
}
public String getTargetMethodName() {
var variableMemberAccessor = shadowVariableTargetList.get(0).variableMemberAccessor();
return Arrays
.stream(variableMemberAccessor.getDeclaredAnnotationsByType(CascadingUpdateShadowVariable.class))
.findFirst().map(CascadingUpdateShadowVariable::targetMethodName)
.orElseThrow(() -> new IllegalStateException("The entity %s is not annotated with @%s."
.formatted(entityDescriptor.getEntityClass(), CascadingUpdateShadowVariable.class.getSimpleName())));
}
public boolean update(ScoreDirector<Solution_> scoreDirector, Object entity) {
if (targetVariableDescriptorList.size() == 1) {
return updateSingle(scoreDirector, entity);
} else {
return updateMultiple(scoreDirector, entity);
}
}
private boolean updateSingle(ScoreDirector<Solution_> scoreDirector, Object entity) {
var oldValue = firstTargetVariableDescriptor.getValue(entity);
scoreDirector.beforeVariableChanged(entity, firstTargetVariableDescriptor.getVariableName());
targetMethod.executeGetter(entity);
var newValue = firstTargetVariableDescriptor.getValue(entity);
scoreDirector.afterVariableChanged(entity, firstTargetVariableDescriptor.getVariableName());
return !Objects.equals(oldValue, newValue);
}
private boolean updateMultiple(ScoreDirector<Solution_> scoreDirector, Object entity) {
var oldValueList = new ArrayList<>(targetVariableDescriptorList.size());
for (var targetVariableDescriptor : targetVariableDescriptorList) {
scoreDirector.beforeVariableChanged(entity, targetVariableDescriptor.getVariableName());
oldValueList.add(targetVariableDescriptor.getValue(entity));
}
targetMethod.executeGetter(entity);
var hasChange = false;
for (var i = 0; i < targetVariableDescriptorList.size(); i++) {
var targetVariableDescriptor = targetVariableDescriptorList.get(i);
var newValue = targetVariableDescriptor.getValue(entity);
scoreDirector.afterVariableChanged(entity, targetVariableDescriptor.getVariableName());
if (!hasChange && !Objects.equals(oldValueList.get(i), newValue)) {
hasChange = true;
}
}
return hasChange;
}
@Override
public void processAnnotations(DescriptorPolicy descriptorPolicy) {
// Do nothing
}
@Override
public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) {
for (var shadowVariableTarget : shadowVariableTargetList) {
targetVariableDescriptorList.add(shadowVariableTarget.entityDescriptor()
.getShadowVariableDescriptor(shadowVariableTarget.variableMemberAccessor().getName()));
}
// Currently, only one list variable is supported per design.
// So, we assume that only one list variable can be found in the available entities, or we fail fast otherwise.
var listVariableDescriptorList = entityDescriptor.getSolutionDescriptor().getEntityDescriptors().stream()
.flatMap(e -> e.getGenuineVariableDescriptorList().stream())
.filter(VariableDescriptor::isListVariable)
.toList();
if (listVariableDescriptorList.size() > 1) {
throw new IllegalArgumentException(
"The shadow variable @%s does not support models with multiple planning list variables [%s].".formatted(
CascadingUpdateShadowVariable.class.getSimpleName(),
listVariableDescriptorList.stream().map(
v -> v.getEntityDescriptor().getEntityClass().getSimpleName() + "::" + v.getVariableName())
.collect(joining(", "))));
}
var targetMethodName = getTargetMethodName();
var allSourceMethodMembers = ConfigUtils.getDeclaredMembers(entityDescriptor.getEntityClass())
.stream()
.filter(member -> member.getName().equals(targetMethodName)
&& member instanceof Method method
&& method.getParameterCount() == 0)
.toList();
if (allSourceMethodMembers.isEmpty()) {
throw new IllegalArgumentException(
"The entity class (%s) has an @%s annotated property (%s), but the method \"%s\" cannot be found."
.formatted(entityDescriptor.getEntityClass(),
CascadingUpdateShadowVariable.class.getSimpleName(),
variableMemberAccessor.getName(),
targetMethodName));
}
targetMethod = descriptorPolicy.getMemberAccessorFactory().buildAndCacheMemberAccessor(allSourceMethodMembers.get(0),
MemberAccessorFactory.MemberAccessorType.VOID_METHOD, null, descriptorPolicy.getDomainAccessType());
firstTargetVariableDescriptor = targetVariableDescriptorList.get(0);
}
@Override
public List<VariableDescriptor<Solution_>> getSourceVariableDescriptorList() {
return Collections.emptyList();
}
@Override
public Collection<Class<? extends AbstractVariableListener>> getVariableListenerClasses() {
return Collections.emptyList();
}
@Override
public Demand<?> getProvidedDemand() {
throw new UnsupportedOperationException("Cascade update element shadow variable cannot be demanded.");
}
@Override
public boolean hasVariableListener() {
return false;
}
@Override
public boolean canBeUsedAsSource() {
return false;
}
@Override
public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) {
throw new UnsupportedOperationException("Cascade update element generates no listeners.");
}
@Override
public boolean isListVariableSource() {
return false;
}
private record ShadowVariableTarget<Solution_>(EntityDescriptor<Solution_> entityDescriptor,
MemberAccessor variableMemberAccessor) {
}
}
|
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/custom/CustomShadowVariableDescriptor.java | package ai.timefold.solver.core.impl.domain.variable.custom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
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.CascadingUpdateShadowVariable;
import ai.timefold.solver.core.api.domain.variable.ListVariableListener;
import ai.timefold.solver.core.api.domain.variable.ShadowVariable;
import ai.timefold.solver.core.api.domain.variable.VariableListener;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy;
import ai.timefold.solver.core.impl.domain.variable.descriptor.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 CustomShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> {
private final Map<Class<? extends AbstractVariableListener>, List<VariableDescriptor<Solution_>>> listenerClassToSourceDescriptorListMap =
new HashMap<>();
public CustomShadowVariableDescriptor(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) {
for (ShadowVariable shadowVariable : variableMemberAccessor.getDeclaredAnnotationsByType(ShadowVariable.class)) {
linkSourceVariableDescriptorToListenerClass(shadowVariable);
}
}
private void linkSourceVariableDescriptorToListenerClass(ShadowVariable shadowVariable) {
EntityDescriptor<Solution_> sourceEntityDescriptor;
var sourceEntityClass = shadowVariable.sourceEntityClass();
if (sourceEntityClass.equals(ShadowVariable.NullEntityClass.class)) {
sourceEntityDescriptor = entityDescriptor;
} else {
sourceEntityDescriptor = entityDescriptor.getSolutionDescriptor().findEntityDescriptor(sourceEntityClass);
if (sourceEntityDescriptor == null) {
throw new IllegalArgumentException(
"""
The entityClass (%s) has a @%s annotated property (%s) with a sourceEntityClass (%s) which is not a valid planning entity.
Maybe check the annotations of the class (%s).
Maybe add the class (%s) among planning entities in the solver configuration."""
.formatted(entityDescriptor.getEntityClass(), ShadowVariable.class.getSimpleName(),
variableMemberAccessor.getName(), sourceEntityClass, sourceEntityClass,
sourceEntityClass));
}
}
var sourceVariableName = shadowVariable.sourceVariableName();
var sourceVariableDescriptor = sourceEntityDescriptor.getVariableDescriptor(sourceVariableName);
if (sourceVariableDescriptor == null) {
throw new IllegalArgumentException(
"""
The entityClass (%s) has a @%s annotated property (%s) with sourceVariableName (%s) which is not a valid planning variable on entityClass (%s).
%s"""
.formatted(entityDescriptor.getEntityClass(), ShadowVariable.class.getSimpleName(),
variableMemberAccessor.getName(), sourceVariableName,
sourceEntityDescriptor.getEntityClass(),
sourceEntityDescriptor.buildInvalidVariableNameExceptionMessage(sourceVariableName)));
}
if (!sourceVariableDescriptor.canBeUsedAsSource()) {
throw new IllegalArgumentException(
"""
The entityClass (%s) has a @%s annotated property (%s) with sourceVariableName (%s) which cannot be used as source.
Shadow variables such as @%s are not allowed to be used as source.
Maybe check if %s is annotated with @%s."""
.formatted(entityDescriptor.getEntityClass(), ShadowVariable.class.getSimpleName(),
variableMemberAccessor.getName(), sourceVariableName,
CascadingUpdateShadowVariable.class.getSimpleName(), sourceVariableName,
CascadingUpdateShadowVariable.class.getSimpleName()));
}
var variableListenerClass = shadowVariable.variableListenerClass();
if (sourceVariableDescriptor.isListVariable()
&& !ListVariableListener.class.isAssignableFrom(variableListenerClass)) {
throw new IllegalArgumentException(
"""
The entityClass (%s) has a @%s annotated property (%s) with a sourceVariable (%s) which is a list variable but the variableListenerClass (%s) is not a %s.
Maybe make the variableListenerClass ("%s) implement %s."""
.formatted(entityDescriptor.getEntityClass(), ShadowVariable.class.getSimpleName(),
variableMemberAccessor.getName(), sourceVariableDescriptor.getSimpleEntityAndVariableName(),
variableListenerClass, ListVariableListener.class.getSimpleName(),
variableListenerClass.getSimpleName(), ListVariableListener.class.getSimpleName()));
}
if (!sourceVariableDescriptor.isListVariable()
&& !VariableListener.class.isAssignableFrom(variableListenerClass)) {
throw new IllegalArgumentException(
"""
The entityClass (%s) has a @%s annotated property (%s) with a sourceVariable (%s) which is a basic variable but the variableListenerClass (%s) is not a %s.
Maybe make the variableListenerClass ("%s) implement %s."""
.formatted(entityDescriptor.getEntityClass(), ShadowVariable.class.getSimpleName(),
variableMemberAccessor.getName(), sourceVariableDescriptor.getSimpleEntityAndVariableName(),
variableListenerClass, VariableListener.class.getSimpleName(),
variableListenerClass.getSimpleName(), VariableListener.class.getSimpleName()));
}
sourceVariableDescriptor.registerSinkVariableDescriptor(this);
listenerClassToSourceDescriptorListMap
.computeIfAbsent(variableListenerClass, k -> new ArrayList<>())
.add(sourceVariableDescriptor);
}
@Override
public List<VariableDescriptor<Solution_>> getSourceVariableDescriptorList() {
return listenerClassToSourceDescriptorListMap.values().stream()
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
}
@Override
public Collection<Class<? extends AbstractVariableListener>> getVariableListenerClasses() {
return listenerClassToSourceDescriptorListMap.keySet();
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Demand<?> getProvidedDemand() {
throw new UnsupportedOperationException("Custom shadow variable cannot be demanded.");
}
@Override
public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) {
return listenerClassToSourceDescriptorListMap.entrySet().stream().map(classListEntry -> {
AbstractVariableListener<Solution_, Object> variableListener =
ConfigUtils.newInstance(this::toString, "variableListenerClass", classListEntry.getKey());
return new VariableListenerWithSources<>(variableListener, classListEntry.getValue());
}).collect(Collectors.toList());
}
@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/custom/LegacyCustomShadowVariableDescriptor.java | package ai.timefold.solver.core.impl.domain.variable.custom;
import java.util.ArrayList;
import java.util.Arrays;
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.CustomShadowVariable;
import ai.timefold.solver.core.api.domain.variable.PlanningVariableReference;
import ai.timefold.solver.core.api.domain.variable.VariableListener;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy;
import ai.timefold.solver.core.impl.domain.variable.descriptor.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 LegacyCustomShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> {
private LegacyCustomShadowVariableDescriptor<Solution_> refVariableDescriptor;
private Class<? extends VariableListener> variableListenerClass;
private List<VariableDescriptor<Solution_>> sourceVariableDescriptorList;
public LegacyCustomShadowVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor,
MemberAccessor variableMemberAccessor) {
super(ordinal, entityDescriptor, variableMemberAccessor);
}
@Override
public void processAnnotations(DescriptorPolicy descriptorPolicy) {
processPropertyAnnotations(descriptorPolicy);
}
private void processPropertyAnnotations(DescriptorPolicy descriptorPolicy) {
CustomShadowVariable shadowVariableAnnotation = variableMemberAccessor
.getAnnotation(CustomShadowVariable.class);
PlanningVariableReference variableListenerRef = shadowVariableAnnotation.variableListenerRef();
if (variableListenerRef.variableName().equals("")) {
variableListenerRef = null;
}
variableListenerClass = shadowVariableAnnotation.variableListenerClass();
if (variableListenerClass == CustomShadowVariable.NullVariableListener.class) {
variableListenerClass = null;
}
PlanningVariableReference[] sources = shadowVariableAnnotation.sources();
if (variableListenerRef != null) {
if (variableListenerClass != null || sources.length > 0) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with a non-null variableListenerRef (" + variableListenerRef
+ "), so it cannot have a variableListenerClass (" + variableListenerClass
+ ") nor any sources (" + Arrays.toString(sources) + ").");
}
} else {
if (variableListenerClass == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") which lacks a variableListenerClass (" + variableListenerClass + ").");
}
if (sources.length < 1) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with sources (" + Arrays.toString(sources)
+ ") which is empty.");
}
}
}
public boolean isRef() {
// refVariableDescriptor might not be initialized yet, but variableListenerClass will
return variableListenerClass == null;
}
@Override
public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) {
linkShadowSources(descriptorPolicy);
}
private void linkShadowSources(DescriptorPolicy descriptorPolicy) {
CustomShadowVariable shadowVariableAnnotation = variableMemberAccessor
.getAnnotation(CustomShadowVariable.class);
PlanningVariableReference variableListenerRef = shadowVariableAnnotation.variableListenerRef();
if (variableListenerRef.variableName().equals("")) {
variableListenerRef = null;
}
if (variableListenerRef != null) {
EntityDescriptor<Solution_> refEntityDescriptor;
Class<?> refEntityClass = variableListenerRef.entityClass();
if (refEntityClass.equals(PlanningVariableReference.NullEntityClass.class)) {
refEntityDescriptor = entityDescriptor;
} else {
refEntityDescriptor = entityDescriptor.getSolutionDescriptor().findEntityDescriptor(refEntityClass);
if (refEntityDescriptor == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with a refEntityClass (" + refEntityClass
+ ") which is not a valid planning entity."
+ "\nMaybe check the annotations of the class (" + refEntityClass + ")."
+ "\nMaybe add the class (" + refEntityClass
+ ") among planning entities in the solver configuration.");
}
}
String refVariableName = variableListenerRef.variableName();
VariableDescriptor<Solution_> uncastRefVariableDescriptor = refEntityDescriptor
.getVariableDescriptor(refVariableName);
if (uncastRefVariableDescriptor == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with refVariableName (" + refVariableName
+ ") which is not a valid planning variable on entityClass ("
+ refEntityDescriptor.getEntityClass() + ").\n"
+ refEntityDescriptor.buildInvalidVariableNameExceptionMessage(refVariableName));
}
if (!(uncastRefVariableDescriptor instanceof LegacyCustomShadowVariableDescriptor)) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with refVariable (" + uncastRefVariableDescriptor.getSimpleEntityAndVariableName()
+ ") that lacks a @" + CustomShadowVariable.class.getSimpleName() + " annotation.");
}
refVariableDescriptor = (LegacyCustomShadowVariableDescriptor<Solution_>) uncastRefVariableDescriptor;
if (refVariableDescriptor.isRef()) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with refVariable (" + refVariableDescriptor + ") that is a reference itself too.");
}
refVariableDescriptor.registerSinkVariableDescriptor(this);
} else {
PlanningVariableReference[] sources = shadowVariableAnnotation.sources();
sourceVariableDescriptorList = new ArrayList<>(sources.length);
for (PlanningVariableReference source : sources) {
EntityDescriptor<Solution_> sourceEntityDescriptor;
Class<?> sourceEntityClass = source.entityClass();
if (sourceEntityClass.equals(PlanningVariableReference.NullEntityClass.class)) {
sourceEntityDescriptor = entityDescriptor;
} else {
sourceEntityDescriptor = entityDescriptor.getSolutionDescriptor()
.findEntityDescriptor(sourceEntityClass);
if (sourceEntityDescriptor == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with a sourceEntityClass (" + sourceEntityClass
+ ") which is not a valid planning entity."
+ "\nMaybe check the annotations of the class (" + sourceEntityClass + ")."
+ "\nMaybe add the class (" + sourceEntityClass
+ ") among planning entities in the solver configuration.");
}
}
String sourceVariableName = source.variableName();
VariableDescriptor<Solution_> sourceVariableDescriptor = sourceEntityDescriptor.getVariableDescriptor(
sourceVariableName);
if (sourceVariableDescriptor == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with sourceVariableName (" + sourceVariableName
+ ") which is not a valid planning variable on entityClass ("
+ sourceEntityDescriptor.getEntityClass() + ").\n"
+ sourceEntityDescriptor.buildInvalidVariableNameExceptionMessage(sourceVariableName));
}
if (sourceVariableDescriptor.isListVariable()) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with sourceVariableName (" + sourceVariableName
+ ") which is a list variable.\n"
+ "Custom shadow variables sourced on list variables are not yet supported.");
}
sourceVariableDescriptor.registerSinkVariableDescriptor(this);
sourceVariableDescriptorList.add(sourceVariableDescriptor);
}
}
}
@Override
public List<VariableDescriptor<Solution_>> getSourceVariableDescriptorList() {
if (refVariableDescriptor != null) {
return Collections.singletonList(refVariableDescriptor);
}
return sourceVariableDescriptorList;
}
@Override
public Collection<Class<? extends AbstractVariableListener>> getVariableListenerClasses() {
if (isRef()) {
return refVariableDescriptor.getVariableListenerClasses();
}
return Collections.singleton(variableListenerClass);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Demand<?> getProvidedDemand() {
throw new UnsupportedOperationException("Custom shadow variable cannot be demanded.");
}
@Override
public boolean hasVariableListener() {
return refVariableDescriptor == null;
}
@Override
public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) {
if (refVariableDescriptor != null) {
throw new IllegalStateException("The shadowVariableDescriptor (" + this
+ ") references another shadowVariableDescriptor (" + refVariableDescriptor
+ ") so it cannot build a " + VariableListener.class.getSimpleName() + ".");
}
VariableListener<Solution_, Object> variableListener =
ConfigUtils.newInstance(this::toString, "variableListenerClass", variableListenerClass);
return new VariableListenerWithSources<>(variableListener, sourceVariableDescriptorList).toCollection();
}
@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/custom/PiggybackShadowVariableDescriptor.java | package ai.timefold.solver.core.impl.domain.variable.custom;
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.PiggybackShadowVariable;
import ai.timefold.solver.core.api.domain.variable.ShadowVariable;
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;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public final class PiggybackShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> {
private CustomShadowVariableDescriptor<Solution_> shadowVariableDescriptor;
public PiggybackShadowVariableDescriptor(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);
}
private void linkShadowSources(DescriptorPolicy descriptorPolicy) {
PiggybackShadowVariable piggybackShadowVariable = variableMemberAccessor.getAnnotation(PiggybackShadowVariable.class);
EntityDescriptor<Solution_> shadowEntityDescriptor;
Class<?> shadowEntityClass = piggybackShadowVariable.shadowEntityClass();
if (shadowEntityClass.equals(PiggybackShadowVariable.NullEntityClass.class)) {
shadowEntityDescriptor = entityDescriptor;
} else {
shadowEntityDescriptor = entityDescriptor.getSolutionDescriptor().findEntityDescriptor(shadowEntityClass);
if (shadowEntityDescriptor == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + PiggybackShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with a shadowEntityClass (" + shadowEntityClass
+ ") which is not a valid planning entity."
+ "\nMaybe check the annotations of the class (" + shadowEntityClass + ")."
+ "\nMaybe add the class (" + shadowEntityClass
+ ") among planning entities in the solver configuration.");
}
}
String shadowVariableName = piggybackShadowVariable.shadowVariableName();
VariableDescriptor<Solution_> uncastShadowVariableDescriptor =
shadowEntityDescriptor.getVariableDescriptor(shadowVariableName);
if (uncastShadowVariableDescriptor == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + PiggybackShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with shadowVariableName (" + shadowVariableName
+ ") which is not a valid planning variable on entityClass ("
+ shadowEntityDescriptor.getEntityClass() + ").\n"
+ shadowEntityDescriptor.buildInvalidVariableNameExceptionMessage(shadowVariableName));
}
if (!(uncastShadowVariableDescriptor instanceof CustomShadowVariableDescriptor)) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + PiggybackShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with refVariable (" + uncastShadowVariableDescriptor.getSimpleEntityAndVariableName()
+ ") that lacks a @" + ShadowVariable.class.getSimpleName() + " annotation.");
}
shadowVariableDescriptor = (CustomShadowVariableDescriptor<Solution_>) uncastShadowVariableDescriptor;
shadowVariableDescriptor.registerSinkVariableDescriptor(this);
}
@Override
public List<VariableDescriptor<Solution_>> getSourceVariableDescriptorList() {
return Collections.singletonList(shadowVariableDescriptor);
}
@Override
public Collection<Class<? extends AbstractVariableListener>> getVariableListenerClasses() {
return shadowVariableDescriptor.getVariableListenerClasses();
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Demand<?> getProvidedDemand() {
throw new UnsupportedOperationException("Custom shadow variable cannot be demanded.");
}
@Override
public boolean hasVariableListener() {
return false;
}
@Override
public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) {
throw new UnsupportedOperationException("The piggybackShadowVariableDescriptor (" + this
+ ") cannot build a variable listener.");
}
@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/AbstractVariableReferenceGraph.java | package ai.timefold.solver.core.impl.domain.variable.declarative;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
import ai.timefold.solver.core.impl.util.DynamicIntArray;
import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;
public abstract sealed class AbstractVariableReferenceGraph<Solution_, ChangeSet_> implements VariableReferenceGraph
permits DefaultVariableReferenceGraph, FixedVariableReferenceGraph {
// These structures are immutable.
protected final List<GraphNode<Solution_>> nodeList;
protected final Map<VariableMetaModel<?, ?, ?>, Map<Object, GraphNode<Solution_>>> variableReferenceToContainingNodeMap;
protected final Map<VariableMetaModel<?, ?, ?>, List<BiConsumer<AbstractVariableReferenceGraph<Solution_, ?>, Object>>> variableReferenceToBeforeProcessor;
protected final Map<VariableMetaModel<?, ?, ?>, List<BiConsumer<AbstractVariableReferenceGraph<Solution_, ?>, Object>>> variableReferenceToAfterProcessor;
// These structures are mutable.
protected final DynamicIntArray[] edgeCount;
protected final ChangeSet_ changeSet;
protected final TopologicalOrderGraph graph;
AbstractVariableReferenceGraph(VariableReferenceGraphBuilder<Solution_> outerGraph,
IntFunction<TopologicalOrderGraph> graphCreator) {
nodeList = List.copyOf(outerGraph.nodeList);
var instanceCount = nodeList.size();
// Often the maps are a singleton; we improve performance by actually making it so.
variableReferenceToContainingNodeMap = mapOfMapsDeepCopyOf(outerGraph.variableReferenceToContainingNodeMap);
variableReferenceToBeforeProcessor = mapOfListsDeepCopyOf(outerGraph.variableReferenceToBeforeProcessor);
variableReferenceToAfterProcessor = mapOfListsDeepCopyOf(outerGraph.variableReferenceToAfterProcessor);
edgeCount = new DynamicIntArray[instanceCount];
for (int i = 0; i < instanceCount; i++) {
edgeCount[i] = new DynamicIntArray(instanceCount);
}
graph = graphCreator.apply(instanceCount);
graph.withNodeData(nodeList);
var visited = Collections.newSetFromMap(new IdentityHashMap<>());
changeSet = createChangeSet(instanceCount);
for (var instance : nodeList) {
var entity = instance.entity();
if (visited.add(entity)) {
for (var variableId : outerGraph.variableReferenceToAfterProcessor.keySet()) {
afterVariableChanged(variableId, entity);
}
}
}
for (var fixedEdgeEntry : outerGraph.fixedEdges.entrySet()) {
for (var toEdge : fixedEdgeEntry.getValue()) {
addEdge(fixedEdgeEntry.getKey(), toEdge);
}
}
}
protected abstract ChangeSet_ createChangeSet(int instanceCount);
public @Nullable GraphNode<Solution_> lookupOrNull(VariableMetaModel<?, ?, ?> variableId, Object entity) {
var map = variableReferenceToContainingNodeMap.get(variableId);
if (map == null) {
return null;
}
return map.get(entity);
}
public void addEdge(@NonNull GraphNode<Solution_> from, @NonNull GraphNode<Solution_> to) {
var fromNodeId = from.graphNodeId();
var toNodeId = to.graphNodeId();
if (fromNodeId == toNodeId) {
return;
}
var count = edgeCount[fromNodeId].get(toNodeId);
if (count == 0) {
graph.addEdge(fromNodeId, toNodeId);
}
edgeCount[fromNodeId].set(toNodeId, count + 1);
markChanged(to);
}
public void removeEdge(@NonNull GraphNode<Solution_> from, @NonNull GraphNode<Solution_> to) {
var fromNodeId = from.graphNodeId();
var toNodeId = to.graphNodeId();
if (fromNodeId == toNodeId) {
return;
}
var count = edgeCount[fromNodeId].get(toNodeId);
if (count == 1) {
graph.removeEdge(fromNodeId, toNodeId);
}
edgeCount[fromNodeId].set(toNodeId, count - 1);
markChanged(to);
}
abstract void markChanged(GraphNode<Solution_> changed);
@Override
public void beforeVariableChanged(VariableMetaModel<?, ?, ?> variableReference, Object entity) {
if (variableReference.entity().type().isInstance(entity)) {
processEntity(variableReferenceToBeforeProcessor.getOrDefault(variableReference, Collections.emptyList()), entity);
}
}
@SuppressWarnings("ForLoopReplaceableByForEach")
private void processEntity(List<BiConsumer<AbstractVariableReferenceGraph<Solution_, ?>, Object>> processorList,
Object entity) {
var processorCount = processorList.size();
// Avoid creation of iterators on the hot path.
// The short-lived instances were observed to cause considerable GC pressure.
for (int i = 0; i < processorCount; i++) {
processorList.get(i).accept(this, entity);
}
}
@Override
public void afterVariableChanged(VariableMetaModel<?, ?, ?> variableReference, Object entity) {
if (variableReference.entity().type().isInstance(entity)) {
var node = lookupOrNull(variableReference, entity);
if (node != null) {
markChanged(node);
}
processEntity(variableReferenceToAfterProcessor.getOrDefault(variableReference, Collections.emptyList()), entity);
}
}
@Override
public String toString() {
var edgeList = new LinkedHashMap<GraphNode<Solution_>, List<GraphNode<Solution_>>>();
graph.forEachEdge((from, to) -> edgeList.computeIfAbsent(nodeList.get(from), k -> new ArrayList<>())
.add(nodeList.get(to)));
return edgeList.entrySet()
.stream()
.map(e -> e.getKey() + "->" + e.getValue())
.collect(Collectors.joining(
"," + System.lineSeparator() + " ",
"{" + System.lineSeparator() + " ",
"}"));
}
@SuppressWarnings("unchecked")
static <K1, K2, V> Map<K1, Map<K2, V>> mapOfMapsDeepCopyOf(Map<K1, Map<K2, V>> map) {
var entryArray = map.entrySet()
.stream()
.map(e -> Map.entry(e.getKey(), Map.copyOf(e.getValue())))
.toArray(Map.Entry[]::new);
return Map.ofEntries(entryArray);
}
@SuppressWarnings("unchecked")
static <K1, V> Map<K1, List<V>> mapOfListsDeepCopyOf(Map<K1, List<V>> map) {
var entryArray = map.entrySet()
.stream()
.map(e -> Map.entry(e.getKey(), List.copyOf(e.getValue())))
.toArray(Map.Entry[]::new);
return Map.ofEntries(entryArray);
}
}
|
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/AffectedEntitiesUpdater.java | package ai.timefold.solver.core.impl.domain.variable.declarative;
import java.util.BitSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
final class AffectedEntitiesUpdater<Solution_>
implements Consumer<BitSet> {
// From WorkingReferenceGraph.
private final BaseTopologicalOrderGraph graph;
private final List<GraphNode<Solution_>> nodeList; // Immutable.
private final ChangedVariableNotifier<Solution_> changedVariableNotifier;
// Internal state; expensive to create, therefore we reuse.
private final LoopedTracker loopedTracker;
private final BitSet visited;
private final PriorityQueue<BaseTopologicalOrderGraph.NodeTopologicalOrder> changeQueue;
AffectedEntitiesUpdater(BaseTopologicalOrderGraph graph, List<GraphNode<Solution_>> nodeList,
Function<Object, List<GraphNode<Solution_>>> entityToContainingNode,
int entityCount, ChangedVariableNotifier<Solution_> changedVariableNotifier) {
this.graph = graph;
this.nodeList = nodeList;
this.changedVariableNotifier = changedVariableNotifier;
var instanceCount = nodeList.size();
this.loopedTracker = new LoopedTracker(instanceCount,
createNodeToEntityNodes(entityCount, nodeList, entityToContainingNode));
this.visited = new BitSet(instanceCount);
this.changeQueue = new PriorityQueue<>(instanceCount);
}
static <Solution_> int[][] createNodeToEntityNodes(int entityCount,
List<GraphNode<Solution_>> nodeList,
Function<Object, List<GraphNode<Solution_>>> entityToContainingNode) {
record EntityIdPair(Object entity, int entityId) {
@Override
public boolean equals(Object o) {
if (!(o instanceof EntityIdPair that))
return false;
return entityId == that.entityId;
}
@Override
public int hashCode() {
return Objects.hashCode(entityId);
}
}
int[][] out = new int[entityCount][];
var entityToNodes = new IdentityHashMap<Integer, int[]>();
var entityIdPairSet = nodeList.stream()
.map(node -> new EntityIdPair(node.entity(), node.entityId()))
.collect(Collectors.toSet());
for (var entityIdPair : entityIdPairSet) {
entityToNodes.put(entityIdPair.entityId(),
entityToContainingNode.apply(entityIdPair.entity).stream().mapToInt(GraphNode::graphNodeId)
.toArray());
}
for (var entry : entityToNodes.entrySet()) {
out[entry.getKey()] = entry.getValue();
}
return out;
}
@Override
public void accept(BitSet changed) {
initializeChangeQueue(changed);
while (!changeQueue.isEmpty()) {
var nextNode = changeQueue.poll().nodeId();
if (visited.get(nextNode)) {
continue;
}
visited.set(nextNode);
var shadowVariable = nodeList.get(nextNode);
var isChanged = updateEntityShadowVariables(shadowVariable, graph.isLooped(loopedTracker, nextNode));
if (isChanged) {
var iterator = graph.nodeForwardEdges(nextNode);
while (iterator.hasNext()) {
var nextNodeForwardEdge = iterator.nextInt();
if (!visited.get(nextNodeForwardEdge)) {
changeQueue.add(graph.getTopologicalOrder(nextNodeForwardEdge));
}
}
}
}
// Prepare for the next time updateChanged() is called.
// No need to clear changeQueue, as that already finishes empty.
loopedTracker.clear();
visited.clear();
}
private void initializeChangeQueue(BitSet changed) {
// BitSet iteration: get the first set bit at or after 0,
// then get the first set bit after that bit.
// Iteration ends when nextSetBit returns -1.
// This has the potential to overflow, since to do the
// test, we necessarily need to do nextSetBit(i + 1),
// and i + 1 can be negative if Integer.MAX_VALUE is set
// in the BitSet.
// This should never happen, since arrays in Java are limited
// to slightly less than Integer.MAX_VALUE.
for (var i = changed.nextSetBit(0); i >= 0; i = changed.nextSetBit(i + 1)) {
changeQueue.add(graph.getTopologicalOrder(i));
if (i == Integer.MAX_VALUE) {
break; // or (i+1) would overflow
}
}
changed.clear();
}
private boolean updateEntityShadowVariables(GraphNode<Solution_> entityVariable, boolean isVariableInconsistent) {
var entity = entityVariable.entity();
var shadowVariableReferences = entityVariable.variableReferences();
var entityConsistencyState = shadowVariableReferences.get(0).entityConsistencyState();
var anyChanged = false;
// Do not need to update anyChanged here; the graph already marked
// all nodes whose looped status changed for us
var groupEntities = shadowVariableReferences.get(0).groupEntities();
var groupEntityIds = entityVariable.groupEntityIds();
if (groupEntities != null) {
for (var i = 0; i < groupEntityIds.length; i++) {
var groupEntity = groupEntities[i];
var groupEntityId = groupEntityIds[i];
anyChanged |=
updateLoopedStatusOfEntity(groupEntity, groupEntityId, entityConsistencyState);
}
} else {
anyChanged |=
updateLoopedStatusOfEntity(entity, entityVariable.entityId(), entityConsistencyState);
}
for (var shadowVariableReference : shadowVariableReferences) {
anyChanged |= updateShadowVariable(isVariableInconsistent, shadowVariableReference, entity);
}
return anyChanged;
}
private <Entity_> boolean updateLoopedStatusOfEntity(Entity_ entity, int entityId,
EntityConsistencyState<Solution_, Entity_> entityConsistencyState) {
var oldLooped = entityConsistencyState.getEntityInconsistentValue(entity);
var isEntityLooped = loopedTracker.isEntityInconsistent(graph, entityId, oldLooped);
if (!Objects.equals(oldLooped, isEntityLooped)) {
entityConsistencyState.setEntityIsInconsistent(changedVariableNotifier, entity, isEntityLooped);
}
// We return true if the entity's loop status changed at any point;
// Since an entity might correspond to multiple nodes, we want all nodes
// for that entity to be marked as changed, not just the first node the
// updater encounters
return loopedTracker.didEntityInconsistentStatusChange(entityId);
}
private boolean updateShadowVariable(boolean isLooped,
VariableUpdaterInfo<Solution_> shadowVariableReference, Object entity) {
if (isLooped) {
return shadowVariableReference.updateIfChanged(entity, null, changedVariableNotifier);
} else {
return shadowVariableReference.updateIfChanged(entity, changedVariableNotifier);
}
}
/**
* See {@link ConsistencyTracker#setUnknownConsistencyFromEntityShadowVariablesInconsistent}
*/
void setUnknownInconsistencyValues() {
for (var node : nodeList) {
var entityConsistencyState = node.variableReferences().get(0).entityConsistencyState();
if (node.groupEntityIds() != null) {
for (var i = 0; i < node.groupEntityIds().length; i++) {
var groupEntity = node.variableReferences().get(0).groupEntities()[i];
var groupEntityId = node.groupEntityIds()[i];
updateLoopedStatusOfEntitySkippingProcessor(groupEntity, groupEntityId, entityConsistencyState);
}
} else {
updateLoopedStatusOfEntitySkippingProcessor(node.entity(), node.entityId(), entityConsistencyState);
}
}
}
private <Entity_> void updateLoopedStatusOfEntitySkippingProcessor(Entity_ entity, int entityId,
EntityConsistencyState<Solution_, Entity_> entityConsistencyState) {
var oldLooped = entityConsistencyState.getEntityInconsistentValueFromProcessorOrNull(entity);
if (oldLooped == null) {
var isEntityLooped = loopedTracker.isEntityInconsistent(graph, entityId, oldLooped);
entityConsistencyState.setEntityIsInconsistentSkippingProcessor(entity, isEntityLooped);
} else {
entityConsistencyState.setEntityIsInconsistentSkippingProcessor(entity, oldLooped);
}
}
}
|
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/BaseTopologicalOrderGraph.java | package ai.timefold.solver.core.impl.domain.variable.declarative;
import java.util.PrimitiveIterator;
/**
* Exists to expose read-only view of {@link TopologicalOrderGraph}.
*/
public interface BaseTopologicalOrderGraph {
/**
* Return an iterator of the nodes that have the `from` node as a predecessor.
*
* @param from The predecessor node.
* @return an iterator of nodes with from as a predecessor.
*/
PrimitiveIterator.OfInt nodeForwardEdges(int from);
/**
* Returns true if a given node is in a strongly connected component with a size
* greater than 1 (i.e. is in a loop) or is a transitive successor of a
* node with the above property.
*
* @param loopedTracker a tracker that can be used to record looped state to avoid
* recomputation.
* @param node The node being queried
* @return true if `node` is in a loop, false otherwise.
*/
boolean isLooped(LoopedTracker loopedTracker, int node);
/**
* Returns a tuple containing node ID and a number corresponding to its topological order.
* In particular, after {@link TopologicalOrderGraph#commitChanges(java.util.BitSet)} is called, the following
* must be true for any pair of nodes A, B where:
* <ul>
* <li>A is a predecessor of B</li>
* <li>`isLooped(A) == isLooped(B) == false`</li>
* </ul>
* getTopologicalOrder(A) < getTopologicalOrder(B)
* <p>
* Said number may not be unique.
*/
NodeTopologicalOrder getTopologicalOrder(int node);
/**
* Stores a graph node id along its topological order.
* Comparisons ignore node id and only use the topological order.
* For instance, for x = (0, 0) and y = (1, 5), x is before y, whereas for
* x = (0, 5) and y = (1, 0), y is before x. Note {@link BaseTopologicalOrderGraph}
* is not guaranteed to return every topological order index (i.e.
* it might be the case no nodes has order 0).
*/
record NodeTopologicalOrder(int nodeId, int order)
implements
Comparable<NodeTopologicalOrder> {
@Override
public int compareTo(NodeTopologicalOrder other) {
return order - other.order;
}
@Override
public boolean equals(Object o) {
if (o instanceof NodeTopologicalOrder other) {
return nodeId == other.nodeId;
}
return false;
}
@Override
public int hashCode() {
return nodeId;
}
}
} |
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/ChangedVariableNotifier.java | package ai.timefold.solver.core.impl.domain.variable.declarative;
import java.util.Collections;
import java.util.function.BiConsumer;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.CollectionInverseVariableDemand;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.CollectionInverseVariableSupply;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel;
import org.jspecify.annotations.Nullable;
public record ChangedVariableNotifier<Solution_>(BiConsumer<VariableDescriptor<Solution_>, Object> beforeVariableChanged,
BiConsumer<VariableDescriptor<Solution_>, Object> afterVariableChanged,
@Nullable InnerScoreDirector<Solution_, ?> innerScoreDirector) {
private static final ChangedVariableNotifier<?> EMPTY = new ChangedVariableNotifier<>((a, b) -> {
},
(a, b) -> {
},
null);
public CollectionInverseVariableSupply getCollectionInverseVariableSupply(VariableMetaModel<?, ?, ?> variableMetaModel) {
if (innerScoreDirector == null) {
return entity -> Collections.emptyList();
} else {
var solutionDescriptor = innerScoreDirector.getSolutionDescriptor();
var variableDescriptor = solutionDescriptor.getEntityDescriptorStrict(variableMetaModel.entity().type())
.getVariableDescriptor(variableMetaModel.name());
return innerScoreDirector.getSupplyManager().demand(new CollectionInverseVariableDemand<>(variableDescriptor));
}
}
@SuppressWarnings("unchecked")
public static <Solution_> ChangedVariableNotifier<Solution_> empty() {
return (ChangedVariableNotifier<Solution_>) EMPTY;
}
public static <Solution_> ChangedVariableNotifier<Solution_> of(InnerScoreDirector<Solution_, ?> scoreDirector) {
return new ChangedVariableNotifier<>(
scoreDirector::beforeVariableChanged,
scoreDirector::afterVariableChanged,
scoreDirector);
}
}
|
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/ConsistencyTracker.java | package ai.timefold.solver.core.impl.domain.variable.declarative;
import java.util.Arrays;
import java.util.HashMap;
import java.util.IdentityHashMap;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import org.jspecify.annotations.NullMarked;
@NullMarked
public record ConsistencyTracker<Solution_>(
IdentityHashMap<Object, Boolean> entityToIsInconsistentMap,
HashMap<Class<?>, EntityConsistencyState<Solution_, Object>> entityClassToConsistencyStateMap,
boolean isFrozen) {
public ConsistencyTracker() {
this(new IdentityHashMap<>(), new HashMap<>(), false);
}
private ConsistencyTracker(boolean isFrozen) {
this(new IdentityHashMap<>(), new HashMap<>(), isFrozen);
}
public static <Solution_> ConsistencyTracker<Solution_> frozen(SolutionDescriptor<Solution_> solutionDescriptor,
Object[] entityOrFacts) {
var out = new ConsistencyTracker<Solution_>(true);
out.setUnknownConsistencyFromEntityShadowVariablesInconsistent(solutionDescriptor, entityOrFacts);
return out;
}
public EntityConsistencyState<Solution_, Object>
getDeclarativeEntityConsistencyState(EntityDescriptor<Solution_> entityDescriptor) {
return entityClassToConsistencyStateMap.computeIfAbsent(entityDescriptor.getEntityClass(),
ignored -> new EntityConsistencyState<>(entityDescriptor, entityToIsInconsistentMap));
}
/**
* Used by ConstraintVerifier to set consistency of entities that either:
* <ul>
* <li>Do not have a {@link ai.timefold.solver.core.api.domain.variable.ShadowVariablesInconsistent} member.</li>
* <li>Have a {@link ai.timefold.solver.core.api.domain.variable.ShadowVariablesInconsistent} member that is null.</li>
* </ul>
* If an entity has a {@link ai.timefold.solver.core.api.domain.variable.ShadowVariablesInconsistent} member that is
* either true or false, then that value determines if the entity is consistent or not
* (regardless of its actual consistency in the graph).
*/
void setUnknownConsistencyFromEntityShadowVariablesInconsistent(SolutionDescriptor<Solution_> solutionDescriptor,
Object[] entityOrFacts) { // Not private so DefaultVariableReferenceGraph javadoc can reference it.
var entities = Arrays.stream(entityOrFacts)
.filter(maybeEntity -> solutionDescriptor.hasEntityDescriptor(maybeEntity.getClass()))
.toArray(Object[]::new);
var graph = DefaultShadowVariableSessionFactory
.buildGraphForStructureAndDirection(
// We want an ARBITRARY graph structure, since other structures can preemptively
// set inconsistency of entities, which ConstraintVerifier does not want
// if the user specified a specific inconsistency value.
new GraphStructure.GraphStructureAndDirection(GraphStructure.ARBITRARY, null, null),
new DefaultShadowVariableSessionFactory.GraphDescriptor<>(solutionDescriptor,
ChangedVariableNotifier.empty(),
entities).withConsistencyTracker(this));
// Graph will either be DefaultVariableReferenceGraph or EmptyVariableReferenceGraph
// If it is empty, we don't need to do anything.
if (graph instanceof DefaultVariableReferenceGraph<?> defaultVariableReferenceGraph) {
defaultVariableReferenceGraph.setUnknownInconsistencyValues();
}
}
/**
* If true, consistency and shadow variables are frozen and should not be updated.
* ConstraintVerifier creates a frozen instance via {@link #frozen(SolutionDescriptor, Object[])}.
*
* @return true if consistency and shadow variables are frozen and should not be updated
*/
public boolean isFrozen() {
return isFrozen;
}
}
|
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/DeclarativeShadowVariableDescriptor.java | package ai.timefold.solver.core.impl.domain.variable.declarative;
import java.lang.reflect.Member;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener;
import ai.timefold.solver.core.api.domain.variable.ShadowSources;
import ai.timefold.solver.core.api.domain.variable.ShadowVariable;
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.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;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningSolutionMetaModel;
import org.jspecify.annotations.Nullable;
public class DeclarativeShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> {
MemberAccessor calculator;
RootVariableSource<?, ?>[] sources;
String[] sourcePaths;
String alignmentKey;
Function<Object, Object> alignmentKeyMap;
public DeclarativeShadowVariableDescriptor(int ordinal,
EntityDescriptor<Solution_> entityDescriptor,
MemberAccessor variableMemberAccessor) {
super(ordinal, entityDescriptor, variableMemberAccessor);
}
@Override
public void processAnnotations(DescriptorPolicy descriptorPolicy) {
var annotation = variableMemberAccessor.getAnnotation(ShadowVariable.class);
var methodName = annotation.supplierName();
if (methodName.isEmpty()) {
throw new IllegalStateException("DeclarativeShadowVariableDescriptor was created when method is empty.");
}
var method = ReflectionHelper.getDeclaredMethod(variableMemberAccessor.getDeclaringClass(), methodName);
if (method == null) {
throw new IllegalArgumentException("""
@%s (%s) defines a supplierMethod (%s) that does not exist inside its declaring class (%s).
Maybe you misspelled the supplierMethod name?"""
.formatted(ShadowVariable.class.getSimpleName(), variableName, methodName,
variableMemberAccessor.getDeclaringClass().getCanonicalName()));
}
var shadowVariableUpdater = method.getAnnotation(ShadowSources.class);
if (shadowVariableUpdater == null) {
throw new IllegalArgumentException("""
Method "%s" referenced from @%s member %s is not annotated with @%s.
Maybe annotate the method %s with @%s?
""".formatted(methodName, ShadowVariable.class.getSimpleName(), variableMemberAccessor,
ShadowSources.class.getSimpleName(),
methodName, ShadowSources.class.getSimpleName()));
}
this.calculator =
entityDescriptor.getSolutionDescriptor().getMemberAccessorFactory().buildAndCacheMemberAccessor(method,
MemberAccessorFactory.MemberAccessorType.FIELD_OR_READ_METHOD, ShadowSources.class,
descriptorPolicy.getDomainAccessType());
sourcePaths = shadowVariableUpdater.value();
if (sourcePaths.length == 0) {
throw new IllegalArgumentException("""
Method "%s" referenced from @%s member %s has no sources.
A shadow variable must have at least one source (since otherwise it a constant).
Maybe add one source?
""".formatted(methodName, ShadowVariable.class.getSimpleName(), variableMemberAccessor));
}
if (shadowVariableUpdater.alignmentKey() != null && !shadowVariableUpdater.alignmentKey().isEmpty()) {
alignmentKey = shadowVariableUpdater.alignmentKey();
} else {
alignmentKey = null;
}
}
@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) {
sources = new RootVariableSource[sourcePaths.length];
var solutionMetamodel = entityDescriptor.getSolutionDescriptor().getMetaModel();
var memberAccessorFactory = entityDescriptor.getSolutionDescriptor().getMemberAccessorFactory();
for (int i = 0; i < sources.length; i++) {
sources[i] = RootVariableSource.from(
solutionMetamodel,
entityDescriptor.getEntityClass(),
variableMemberAccessor.getName(),
sourcePaths[i],
memberAccessorFactory,
descriptorPolicy);
}
var alignmentKeyMember = getAlignmentKeyMemberForEntityProperty(solutionMetamodel,
entityDescriptor.getEntityClass(),
calculator,
variableName,
alignmentKey);
if (alignmentKeyMember != null) {
alignmentKeyMap = memberAccessorFactory.buildAndCacheMemberAccessor(alignmentKeyMember,
MemberAccessorFactory.MemberAccessorType.FIELD_OR_GETTER_METHOD, ShadowSources.class,
descriptorPolicy.getDomainAccessType())::executeGetter;
} else {
alignmentKeyMap = null;
}
}
protected static Member getAlignmentKeyMemberForEntityProperty(
PlanningSolutionMetaModel<?> solutionMetamodel,
Class<?> entityClass,
MemberAccessor calculator,
String variableName,
String propertyName) {
if (propertyName == null) {
return null;
}
Member member = RootVariableSource.getMember(entityClass,
propertyName, entityClass,
propertyName);
if (RootVariableSource.isVariable(solutionMetamodel, member.getDeclaringClass(),
member.getName())) {
throw new IllegalArgumentException(
"""
The @%s-annotated supplier method (%s) for variable (%s) on class (%s) uses a alignmentKey (%s) that is a variable.
A alignmentKey must be a problem fact and cannot change during solving.
"""
.formatted(ShadowSources.class.getSimpleName(),
calculator.getName(),
variableName,
entityClass.getCanonicalName(),
propertyName));
}
return member;
}
@Override
public boolean isListVariableSource() {
return false;
}
public MemberAccessor getMemberAccessor() {
return variableMemberAccessor;
}
public MemberAccessor getCalculator() {
return calculator;
}
public Function<Object, Object> getAlignmentKeyMap() {
return alignmentKeyMap;
}
public @Nullable String getAlignmentKeyName() {
return alignmentKey;
}
public RootVariableSource<?, ?>[] getSources() {
return sources;
}
}
|
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/DefaultShadowVariableSession.java | package ai.timefold.solver.core.impl.domain.variable.declarative;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.supply.Supply;
import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel;
import org.jspecify.annotations.NullMarked;
@NullMarked
public final class DefaultShadowVariableSession<Solution_> implements Supply {
final VariableReferenceGraph graph;
public DefaultShadowVariableSession(VariableReferenceGraph graph) {
this.graph = graph;
}
public void beforeVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity) {
beforeVariableChanged(variableDescriptor.getVariableMetaModel(),
entity);
}
public void afterVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity) {
afterVariableChanged(variableDescriptor.getVariableMetaModel(),
entity);
}
public void beforeVariableChanged(VariableMetaModel<Solution_, ?, ?> variableMetaModel, Object entity) {
graph.beforeVariableChanged(variableMetaModel,
entity);
}
public void afterVariableChanged(VariableMetaModel<Solution_, ?, ?> variableMetaModel, Object entity) {
graph.afterVariableChanged(variableMetaModel,
entity);
}
public void updateVariables() {
graph.updateChanged();
}
}
|
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/DefaultShadowVariableSessionFactory.java | package ai.timefold.solver.core.impl.domain.variable.declarative;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.function.IntFunction;
import ai.timefold.solver.core.api.function.TriFunction;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
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 class DefaultShadowVariableSessionFactory<Solution_> {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultShadowVariableSessionFactory.class);
private final SolutionDescriptor<Solution_> solutionDescriptor;
private final InnerScoreDirector<Solution_, ?> scoreDirector;
private final IntFunction<TopologicalOrderGraph> graphCreator;
public DefaultShadowVariableSessionFactory(
SolutionDescriptor<Solution_> solutionDescriptor,
InnerScoreDirector<Solution_, ?> scoreDirector,
IntFunction<TopologicalOrderGraph> graphCreator) {
this.solutionDescriptor = solutionDescriptor;
this.scoreDirector = scoreDirector;
this.graphCreator = graphCreator;
}
public record GraphDescriptor<Solution_>(ConsistencyTracker<Solution_> consistencyTracker,
SolutionDescriptor<Solution_> solutionDescriptor,
VariableReferenceGraphBuilder<Solution_> variableReferenceGraphBuilder,
Object[] entities, IntFunction<TopologicalOrderGraph> graphCreator) {
public GraphDescriptor(SolutionDescriptor<Solution_> solutionDescriptor,
ChangedVariableNotifier<Solution_> changedVariableNotifier,
Object... entities) {
this(new ConsistencyTracker<>(), solutionDescriptor, new VariableReferenceGraphBuilder<>(changedVariableNotifier),
entities, DefaultTopologicalOrderGraph::new);
}
public GraphDescriptor<Solution_> withGraphCreator(IntFunction<TopologicalOrderGraph> graphCreator) {
return new GraphDescriptor<>(consistencyTracker, solutionDescriptor,
variableReferenceGraphBuilder, entities, graphCreator);
}
public GraphDescriptor<Solution_> withConsistencyTracker(ConsistencyTracker<Solution_> consistencyTracker) {
return new GraphDescriptor<>(consistencyTracker, solutionDescriptor,
variableReferenceGraphBuilder, entities, graphCreator);
}
public ChangedVariableNotifier<Solution_> changedVariableNotifier() {
return variableReferenceGraphBuilder.changedVariableNotifier;
}
}
public static <Solution_> VariableReferenceGraph buildGraph(GraphDescriptor<Solution_> graphDescriptor) {
var graphStructureAndDirection = GraphStructure.determineGraphStructure(graphDescriptor.solutionDescriptor(),
graphDescriptor.entities());
LOGGER.trace("Shadow variable graph structure: {}", graphStructureAndDirection);
return buildGraphForStructureAndDirection(graphStructureAndDirection, graphDescriptor);
}
static <Solution_> VariableReferenceGraph buildGraphForStructureAndDirection(
GraphStructure.GraphStructureAndDirection graphStructureAndDirection, GraphDescriptor<Solution_> graphDescriptor) {
return switch (graphStructureAndDirection.structure()) {
case EMPTY -> EmptyVariableReferenceGraph.INSTANCE;
case SINGLE_DIRECTIONAL_PARENT -> {
var scoreDirector =
graphDescriptor.variableReferenceGraphBuilder().changedVariableNotifier.innerScoreDirector();
if (scoreDirector == null) {
yield buildArbitraryGraph(graphDescriptor);
}
yield buildSingleDirectionalParentGraph(graphDescriptor, graphStructureAndDirection);
}
case ARBITRARY_SINGLE_ENTITY_AT_MOST_ONE_DIRECTIONAL_PARENT_TYPE ->
buildArbitrarySingleEntityGraph(graphDescriptor);
case NO_DYNAMIC_EDGES, ARBITRARY ->
buildArbitraryGraph(graphDescriptor);
};
}
static <Solution_> VariableReferenceGraph buildSingleDirectionalParentGraph(
GraphDescriptor<Solution_> graphDescriptor, GraphStructure.GraphStructureAndDirection graphStructureAndDirection) {
var declarativeShadowVariables = graphDescriptor.solutionDescriptor().getDeclarativeShadowVariableDescriptors();
var sortedDeclarativeVariables = topologicallySortedDeclarativeShadowVariables(declarativeShadowVariables);
var topologicalSorter =
getTopologicalSorter(graphDescriptor.solutionDescriptor(),
Objects.requireNonNull(graphDescriptor.changedVariableNotifier().innerScoreDirector()),
Objects.requireNonNull(graphStructureAndDirection.direction()));
return new SingleDirectionalParentVariableReferenceGraph<>(graphDescriptor.consistencyTracker(),
sortedDeclarativeVariables,
topologicalSorter, graphDescriptor.changedVariableNotifier(), graphDescriptor.entities());
}
private static <Solution_> List<DeclarativeShadowVariableDescriptor<Solution_>>
topologicallySortedDeclarativeShadowVariables(
List<DeclarativeShadowVariableDescriptor<Solution_>> declarativeShadowVariables) {
Map<String, Integer> nameToIndex = new LinkedHashMap<>();
for (var declarativeShadowVariable : declarativeShadowVariables) {
nameToIndex.put(declarativeShadowVariable.getVariableName(), nameToIndex.size());
}
var graph = new DefaultTopologicalOrderGraph(nameToIndex.size());
for (var declarativeShadowVariable : declarativeShadowVariables) {
var toIndex = nameToIndex.get(declarativeShadowVariable.getVariableName());
var visited = new HashSet<Integer>();
for (var source : declarativeShadowVariable.getSources()) {
var variableReferences = source.variableSourceReferences();
if (source.parentVariableType() != ParentVariableType.NO_PARENT) {
// We only look at direct usage; if we also added
// edges for groups/directional, we will end up creating a cycle
// which makes all topological orders valid
continue;
}
var variableReference = variableReferences.get(0);
var sourceDeclarativeVariable = variableReference.downstreamDeclarativeVariableMetamodel();
if (sourceDeclarativeVariable != null) {
var fromIndex = nameToIndex.get(sourceDeclarativeVariable.name());
if (visited.add(fromIndex)) {
graph.addEdge(fromIndex, toIndex);
}
}
}
}
graph.commitChanges(new BitSet());
var sortedDeclarativeVariables = new ArrayList<>(declarativeShadowVariables);
sortedDeclarativeVariables.sort(Comparator.<DeclarativeShadowVariableDescriptor<Solution_>> comparingInt(
variable -> graph.getTopologicalOrder(nameToIndex.get(variable.getVariableName())).order())
.thenComparing(VariableDescriptor::getVariableName));
return sortedDeclarativeVariables;
}
private static <Solution_> TopologicalSorter getTopologicalSorter(SolutionDescriptor<Solution_> solutionDescriptor,
InnerScoreDirector<Solution_, ?> scoreDirector, ParentVariableType parentVariableType) {
return switch (parentVariableType) {
case PREVIOUS -> {
var listStateSupply = scoreDirector.getListVariableStateSupply(solutionDescriptor.getListVariableDescriptor());
yield new TopologicalSorter(listStateSupply::getNextElement,
Comparator.comparingInt(entity -> Objects.requireNonNullElse(listStateSupply.getIndex(entity), 0)),
listStateSupply::getInverseSingleton);
}
case NEXT -> {
var listStateSupply = scoreDirector.getListVariableStateSupply(solutionDescriptor.getListVariableDescriptor());
yield new TopologicalSorter(listStateSupply::getPreviousElement,
Comparator.comparingInt(entity -> Objects.requireNonNullElse(listStateSupply.getIndex(entity), 0))
.reversed(),
listStateSupply::getInverseSingleton);
}
default -> throw new IllegalStateException(
"Impossible state: expected parentVariableType to be previous or next but was %s."
.formatted(parentVariableType));
};
}
private static <Solution_> VariableReferenceGraph buildArbitraryGraph(GraphDescriptor<Solution_> graphDescriptor) {
var declarativeShadowVariableDescriptors =
graphDescriptor.solutionDescriptor().getDeclarativeShadowVariableDescriptors();
var variableIdToUpdater = EntityVariableUpdaterLookup.<Solution_> entityIndependentLookup();
// Create graph node for each entity/declarative shadow variable pair.
// Maps a variable id to its source aliases;
// For instance, "previousVisit.startTime" is a source alias of "startTime"
// One way to view this concept is "previousVisit.startTime" is a pointer
// to "startTime" of some visit, and thus alias it.
var declarativeShadowVariableToAliasMap = createGraphNodes(
graphDescriptor,
declarativeShadowVariableDescriptors, variableIdToUpdater);
return buildVariableReferenceGraph(graphDescriptor, declarativeShadowVariableDescriptors,
declarativeShadowVariableToAliasMap);
}
private static <Solution_> VariableReferenceGraph buildVariableReferenceGraph(
GraphDescriptor<Solution_> graphDescriptor,
List<DeclarativeShadowVariableDescriptor<Solution_>> declarativeShadowVariableDescriptors,
Map<VariableMetaModel<?, ?, ?>, Set<VariableSourceReference>> declarativeShadowVariableToAliasMap) {
// Create variable processors for each declarative shadow variable descriptor
for (var declarativeShadowVariable : declarativeShadowVariableDescriptors) {
var fromVariableId = declarativeShadowVariable.getVariableMetaModel();
createSourceChangeProcessors(graphDescriptor, declarativeShadowVariable, fromVariableId);
var aliasSet = declarativeShadowVariableToAliasMap.get(fromVariableId);
if (aliasSet != null) {
createAliasToVariableChangeProcessors(graphDescriptor.variableReferenceGraphBuilder(), aliasSet,
fromVariableId);
}
}
// Create the fixed edges in the graph
createFixedVariableRelationEdges(graphDescriptor.variableReferenceGraphBuilder(), graphDescriptor.entities(),
declarativeShadowVariableDescriptors);
return graphDescriptor.variableReferenceGraphBuilder().build(graphDescriptor.graphCreator());
}
private record GroupVariableUpdaterInfo<Solution_>(
List<DeclarativeShadowVariableDescriptor<Solution_>> sortedDeclarativeVariableDescriptors,
List<VariableUpdaterInfo<Solution_>> allUpdaters,
List<VariableUpdaterInfo<Solution_>> groupedUpdaters,
Map<DeclarativeShadowVariableDescriptor<Solution_>, Map<Object, VariableUpdaterInfo<Solution_>>> variableToEntityToGroupUpdater) {
public List<VariableUpdaterInfo<Solution_>> getUpdatersForEntityVariable(Object entity,
DeclarativeShadowVariableDescriptor<Solution_> declarativeShadowVariableDescriptor) {
if (variableToEntityToGroupUpdater.containsKey(declarativeShadowVariableDescriptor)) {
var updater = variableToEntityToGroupUpdater.get(declarativeShadowVariableDescriptor).get(entity);
if (updater != null) {
return List.of(updater);
}
}
for (var shadowVariableDescriptor : sortedDeclarativeVariableDescriptors) {
for (var rootSource : shadowVariableDescriptor.getSources()) {
if (rootSource.parentVariableType() == ParentVariableType.GROUP) {
var visitedCount = new MutableInt();
rootSource.valueEntityFunction().accept(entity, ignored -> visitedCount.increment());
if (visitedCount.intValue() > 0) {
return groupedUpdaters;
}
}
}
}
return allUpdaters;
}
}
private static <Solution_> Map<VariableMetaModel<Solution_, ?, ?>, GroupVariableUpdaterInfo<Solution_>>
getGroupVariableUpdaterInfoMap(
ConsistencyTracker<Solution_> consistencyTracker,
List<DeclarativeShadowVariableDescriptor<Solution_>> declarativeShadowVariableDescriptors,
Object[] entities) {
var sortedDeclarativeVariableDescriptors =
topologicallySortedDeclarativeShadowVariables(declarativeShadowVariableDescriptors);
var groupIndexToVariables = new HashMap<Integer, List<DeclarativeShadowVariableDescriptor<Solution_>>>();
var groupVariables = new ArrayList<DeclarativeShadowVariableDescriptor<Solution_>>();
groupIndexToVariables.put(0, groupVariables);
for (var declarativeShadowVariableDescriptor : sortedDeclarativeVariableDescriptors) {
// If a @ShadowSources has a group source (i.e. "visitGroup[].arrivalTimes"),
// create a new group since it must wait until all members of that group are processed
var hasGroupSources = Arrays.stream(declarativeShadowVariableDescriptor.getSources())
.anyMatch(rootVariableSource -> rootVariableSource.parentVariableType() == ParentVariableType.GROUP);
// If a @ShadowSources has an alignment key,
// create a new group since multiple entities must be updated for this node
var hasAlignmentKey = declarativeShadowVariableDescriptor.getAlignmentKeyMap() != null;
// If the previous @ShadowSources has an alignment key,
// create a new group since we are updating a single entity again
// NOTE: Can potentially be optimized/share a node if VariableUpdaterInfo
// update each group member independently after the alignmentKey
var previousHasAlignmentKey = !groupVariables.isEmpty() && groupVariables.get(0).getAlignmentKeyMap() != null;
if (!groupVariables.isEmpty() && (hasGroupSources
|| hasAlignmentKey
|| previousHasAlignmentKey)) {
groupVariables = new ArrayList<>();
groupIndexToVariables.put(groupIndexToVariables.size(), groupVariables);
}
groupVariables.add(declarativeShadowVariableDescriptor);
}
var out = new HashMap<VariableMetaModel<Solution_, ?, ?>, GroupVariableUpdaterInfo<Solution_>>();
var allUpdaters = new ArrayList<VariableUpdaterInfo<Solution_>>();
var groupedUpdaters =
new HashMap<DeclarativeShadowVariableDescriptor<Solution_>, Map<Object, VariableUpdaterInfo<Solution_>>>();
var updaterKey = 0;
for (var entryKey = 0; entryKey < groupIndexToVariables.size(); entryKey++) {
var entryGroupVariables = groupIndexToVariables.get(entryKey);
var updaters = new ArrayList<VariableUpdaterInfo<Solution_>>();
for (var declarativeShadowVariableDescriptor : entryGroupVariables) {
var updater = new VariableUpdaterInfo<>(
declarativeShadowVariableDescriptor.getVariableMetaModel(),
updaterKey,
declarativeShadowVariableDescriptor,
consistencyTracker.getDeclarativeEntityConsistencyState(
declarativeShadowVariableDescriptor.getEntityDescriptor()),
declarativeShadowVariableDescriptor.getMemberAccessor(),
declarativeShadowVariableDescriptor.getCalculator()::executeGetter);
if (declarativeShadowVariableDescriptor.getAlignmentKeyMap() != null) {
var alignmentKeyFunction = declarativeShadowVariableDescriptor.getAlignmentKeyMap();
var alignmentKeyToAlignedEntitiesMap = new HashMap<Object, List<Object>>();
for (var entity : entities) {
if (declarativeShadowVariableDescriptor.getEntityDescriptor().getEntityClass().isInstance(entity)) {
var alignmentKey = alignmentKeyFunction.apply(entity);
alignmentKeyToAlignedEntitiesMap.computeIfAbsent(alignmentKey, k -> new ArrayList<>()).add(entity);
}
}
for (var alignmentGroup : alignmentKeyToAlignedEntitiesMap.entrySet()) {
var updaterCopy = updater.withGroupId(updaterKey);
if (alignmentGroup.getKey() == null) {
updaters.add(updaterCopy);
allUpdaters.add(updaterCopy);
} else {
updaterCopy = updaterCopy.withGroupEntities(alignmentGroup.getValue().toArray(new Object[0]));
var variableUpdaterMap = groupedUpdaters.computeIfAbsent(declarativeShadowVariableDescriptor,
ignored -> new IdentityHashMap<>());
for (var entity : alignmentGroup.getValue()) {
variableUpdaterMap.put(entity, updaterCopy);
}
}
updaterKey++;
}
updaterKey--; // it will be incremented again at end of the loop
} else {
updaters.add(updater);
allUpdaters.add(updater);
}
}
var groupVariableUpdaterInfo =
new GroupVariableUpdaterInfo<Solution_>(sortedDeclarativeVariableDescriptors, allUpdaters, updaters,
groupedUpdaters);
for (var declarativeShadowVariableDescriptor : entryGroupVariables) {
out.put(declarativeShadowVariableDescriptor.getVariableMetaModel(), groupVariableUpdaterInfo);
}
updaterKey++;
}
allUpdaters.replaceAll(updater -> updater.withGroupId(groupIndexToVariables.size()));
return out;
}
private static <Solution_> VariableReferenceGraph buildArbitrarySingleEntityGraph(
GraphDescriptor<Solution_> graphDescriptor) {
var declarativeShadowVariableDescriptors =
graphDescriptor.solutionDescriptor().getDeclarativeShadowVariableDescriptors();
// Use a dependent lookup; if an entity does not use groups, then all variables can share the same node.
// If the entity use groups, then variables must be grouped into their own nodes.
var alignmentKeyMappers = new HashMap<VariableMetaModel<Solution_, ?, ?>, Function<Object, @Nullable Object>>();
for (var declarativeShadowVariableDescriptor : declarativeShadowVariableDescriptors) {
if (declarativeShadowVariableDescriptor.getAlignmentKeyMap() != null) {
alignmentKeyMappers.put(declarativeShadowVariableDescriptor.getVariableMetaModel(),
declarativeShadowVariableDescriptor.getAlignmentKeyMap());
}
}
var variableIdToUpdater =
alignmentKeyMappers.isEmpty() ? EntityVariableUpdaterLookup.<Solution_> entityDependentLookup()
: EntityVariableUpdaterLookup.<Solution_> groupedEntityDependentLookup(alignmentKeyMappers::get);
// Create graph node for each entity/declarative shadow variable group pair.
// Maps a variable id to the source aliases of all variables in its group;
// If the variables are (in topological order)
// arrivalTime, readyTime, serviceStartTime, serviceFinishTime,
// where serviceStartTime depends on a group of readyTime, then
// the groups are [arrivalTime, readyTime] and [serviceStartTime, serviceFinishTime]
// this is because from arrivalTime, you can compute readyTime without knowing either
// serviceStartTime or serviceFinishTime.
var variableIdToGroupedUpdater =
getGroupVariableUpdaterInfoMap(graphDescriptor.consistencyTracker(), declarativeShadowVariableDescriptors,
graphDescriptor.entities());
var declarativeShadowVariableToAliasMap = createGraphNodes(
graphDescriptor, declarativeShadowVariableDescriptors, variableIdToUpdater,
(entity, declarativeShadowVariable, variableId) -> variableIdToGroupedUpdater.get(variableId)
.getUpdatersForEntityVariable(entity, declarativeShadowVariable));
return buildVariableReferenceGraph(graphDescriptor, declarativeShadowVariableDescriptors,
declarativeShadowVariableToAliasMap);
}
private static <Solution_> Map<VariableMetaModel<?, ?, ?>, Set<VariableSourceReference>> createGraphNodes(
GraphDescriptor<Solution_> graphDescriptor,
List<DeclarativeShadowVariableDescriptor<Solution_>> declarativeShadowVariableDescriptors,
EntityVariableUpdaterLookup<Solution_> variableIdToUpdaters) {
return createGraphNodes(graphDescriptor,
declarativeShadowVariableDescriptors, variableIdToUpdaters,
(entity, declarativeShadowVariableDescriptor,
variableId) -> Collections.singletonList(new VariableUpdaterInfo<>(
variableId,
variableIdToUpdaters.getNextId(),
declarativeShadowVariableDescriptor,
graphDescriptor.consistencyTracker().getDeclarativeEntityConsistencyState(
declarativeShadowVariableDescriptor.getEntityDescriptor()),
declarativeShadowVariableDescriptor.getMemberAccessor(),
declarativeShadowVariableDescriptor.getCalculator()::executeGetter)));
}
private static <Solution_> Map<VariableMetaModel<?, ?, ?>, Set<VariableSourceReference>> createGraphNodes(
GraphDescriptor<Solution_> graphDescriptor,
List<DeclarativeShadowVariableDescriptor<Solution_>> declarativeShadowVariableDescriptors,
EntityVariableUpdaterLookup<Solution_> variableIdToUpdaters,
TriFunction<Object, DeclarativeShadowVariableDescriptor<Solution_>, VariableMetaModel<Solution_, ?, ?>, List<VariableUpdaterInfo<Solution_>>> entityVariableToUpdatersMapper) {
var result = new HashMap<VariableMetaModel<?, ?, ?>, Set<VariableSourceReference>>();
for (var entity : graphDescriptor.entities()) {
for (var declarativeShadowVariableDescriptor : declarativeShadowVariableDescriptors) {
var entityClass = declarativeShadowVariableDescriptor.getEntityDescriptor().getEntityClass();
if (entityClass.isInstance(entity)) {
var variableId = declarativeShadowVariableDescriptor.getVariableMetaModel();
var updaters = variableIdToUpdaters.computeUpdatersForVariableOnEntity(variableId,
entity,
() -> entityVariableToUpdatersMapper.apply(entity, declarativeShadowVariableDescriptor,
variableId));
graphDescriptor.variableReferenceGraphBuilder.addVariableReferenceEntity(entity, updaters);
for (var sourceRoot : declarativeShadowVariableDescriptor.getSources()) {
for (var source : sourceRoot.variableSourceReferences()) {
if (source.downstreamDeclarativeVariableMetamodel() != null) {
result.computeIfAbsent(source.downstreamDeclarativeVariableMetamodel(),
ignored -> new LinkedHashSet<>())
.add(source);
}
}
}
}
}
}
return result;
}
private static <Solution_> void createSourceChangeProcessors(
GraphDescriptor<Solution_> graphDescriptor,
DeclarativeShadowVariableDescriptor<Solution_> declarativeShadowVariable,
VariableMetaModel<Solution_, ?, ?> fromVariableId) {
for (var source : declarativeShadowVariable.getSources()) {
var parentVariableList = new ArrayList<VariableSourceReference>();
var parentInverseFunctionList = new ArrayList<Function<Object, Collection<Object>>>();
var parentIsOnRootEntity = false;
for (var sourcePart : source.variableSourceReferences()) {
var toVariableId = sourcePart.variableMetaModel();
// declarative variables have edges to each other in the graph,
// and will mark dependent variable as changed.
// non-declarative variables are not in the graph and must have their
// own processor
if (!sourcePart.isDeclarative()) {
if (sourcePart.onRootEntity()) {
// No need for inverse set; source and target entity are the same.
graphDescriptor.variableReferenceGraphBuilder()
.addAfterProcessor(GraphChangeType.NO_CHANGE, toVariableId,
(graph, entity) -> {
var changed = graph.lookupOrNull(fromVariableId, entity);
if (changed != null) {
graph.markChanged(changed);
}
});
parentInverseFunctionList.add(Collections::singletonList);
parentIsOnRootEntity = true;
} else {
Function<Object, Collection<Object>> inverseFunction;
if (parentVariableList.isEmpty()) {
// Need to create an inverse set from source to target
var inverseMap = new IdentityHashMap<Object, List<Object>>();
var visitor = source.getEntityVisitor(sourcePart.chainFromRootEntityToVariableEntity());
for (var rootEntity : graphDescriptor.entities()) {
if (declarativeShadowVariable.getEntityDescriptor().getEntityClass().isInstance(rootEntity)) {
visitor.accept(rootEntity, shadowEntity -> inverseMap
.computeIfAbsent(shadowEntity, ignored -> new ArrayList<>())
.add(rootEntity));
}
}
inverseFunction = entity -> inverseMap.getOrDefault(entity, Collections.emptyList());
} else {
var parentIndex = parentVariableList.size() - 1;
var parentVariable = parentVariableList.get(parentIndex).variableMetaModel();
var inverseSupply = graphDescriptor.variableReferenceGraphBuilder().changedVariableNotifier
.getCollectionInverseVariableSupply(parentVariable);
if (parentIsOnRootEntity) {
inverseFunction = (Function) inverseSupply::getInverseCollection;
} else {
inverseFunction = entity -> {
var inverses = inverseSupply.getInverseCollection(entity);
var parentInverseFunction = parentInverseFunctionList.get(parentIndex);
var out = new ArrayList<>(inverses.size());
for (var inverse : inverses) {
out.addAll(parentInverseFunction.apply(inverse));
}
return out;
};
}
}
graphDescriptor.variableReferenceGraphBuilder()
.addAfterProcessor(GraphChangeType.NO_CHANGE, toVariableId,
(graph, entity) -> {
for (var item : inverseFunction.apply(entity)) {
var changed = graph.lookupOrNull(fromVariableId, item);
if (changed != null) {
graph.markChanged(changed);
}
}
});
parentInverseFunctionList.add(inverseFunction);
parentIsOnRootEntity = false;
}
}
parentVariableList.add(sourcePart);
}
}
}
private static <Solution_> void createAliasToVariableChangeProcessors(
VariableReferenceGraphBuilder<Solution_> variableReferenceGraphBuilder, Set<VariableSourceReference> aliasSet,
VariableMetaModel<Solution_, ?, ?> fromVariableId) {
for (var alias : aliasSet) {
var toVariableId = alias.targetVariableMetamodel();
var sourceVariableId = alias.variableMetaModel();
if (!alias.isDeclarative() && alias.affectGraphEdges()) {
// Exploit the same fact as above
variableReferenceGraphBuilder.addBeforeProcessor(GraphChangeType.REMOVE_EDGE, sourceVariableId,
(graph, toEntity) -> {
// from/to can be null in extended models
// ex: previous is used as a source, but only an extended class
// has the to variable
var to = graph.lookupOrNull(toVariableId, toEntity);
if (to == null) {
return;
}
var fromEntity = alias.targetEntityFunctionStartingFromVariableEntity()
.apply(toEntity);
if (fromEntity == null) {
return;
}
var from = graph.lookupOrNull(fromVariableId, fromEntity);
if (from == null) {
return;
}
graph.removeEdge(from, to);
});
variableReferenceGraphBuilder.addAfterProcessor(GraphChangeType.ADD_EDGE, sourceVariableId,
(graph, toEntity) -> {
var to = graph.lookupOrNull(toVariableId, toEntity);
if (to == null) {
return;
}
var fromEntity = alias.findTargetEntity(toEntity);
if (fromEntity == null) {
return;
}
var from = graph.lookupOrNull(fromVariableId, fromEntity);
if (from == null) {
return;
}
graph.addEdge(from, to);
});
}
// Note: it is impossible to have a declarative variable affect graph edges,
// since accessing a declarative variable from another declarative variable is prohibited.
}
}
private static <Solution_> void createFixedVariableRelationEdges(
VariableReferenceGraphBuilder<Solution_> variableReferenceGraphBuilder,
Object[] entities,
List<DeclarativeShadowVariableDescriptor<Solution_>> declarativeShadowVariableDescriptors) {
for (var entity : entities) {
for (var declarativeShadowVariableDescriptor : declarativeShadowVariableDescriptors) {
var entityClass = declarativeShadowVariableDescriptor.getEntityDescriptor().getEntityClass();
if (!entityClass.isInstance(entity)) {
continue;
}
var toVariableId = declarativeShadowVariableDescriptor.getVariableMetaModel();
var to = variableReferenceGraphBuilder.lookupOrError(toVariableId, entity);
for (var sourceRoot : declarativeShadowVariableDescriptor.getSources()) {
for (var source : sourceRoot.variableSourceReferences()) {
if (source.isTopLevel() && source.isDeclarative()) {
var fromVariableId = source.variableMetaModel();
sourceRoot.valueEntityFunction()
.accept(entity, fromEntity -> {
var from = variableReferenceGraphBuilder.lookupOrError(fromVariableId, fromEntity);
variableReferenceGraphBuilder.addFixedEdge(from, to);
});
break;
}
}
}
}
}
}
public DefaultShadowVariableSession<Solution_> forSolution(ConsistencyTracker<Solution_> consistencyTracker,
Solution_ solution) {
var entities = new ArrayList<>();
solutionDescriptor.visitAllEntities(solution, entities::add);
return forEntities(consistencyTracker, entities.toArray());
}
public DefaultShadowVariableSession<Solution_> forEntities(ConsistencyTracker<Solution_> consistencyTracker,
Object... entities) {
var graph = buildGraph(
new GraphDescriptor<>(solutionDescriptor, ChangedVariableNotifier.of(scoreDirector), entities)
.withConsistencyTracker(consistencyTracker)
.withGraphCreator(graphCreator));
return new DefaultShadowVariableSession<>(graph);
}
}
|
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/DefaultTopologicalOrderGraph.java | package ai.timefold.solver.core.impl.domain.variable.declarative;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PrimitiveIterator;
import java.util.Set;
import java.util.stream.Collectors;
import ai.timefold.solver.core.impl.util.CollectionUtils;
import ai.timefold.solver.core.impl.util.MutableInt;
public class DefaultTopologicalOrderGraph implements TopologicalOrderGraph {
private final NodeTopologicalOrder[] nodeIdToTopologicalOrderMap;
private final Map<Integer, List<Integer>> componentMap;
private final Set<Integer>[] forwardEdges;
private final Set<Integer>[] backEdges;
private final boolean[] isNodeInLoopedComponent;
@SuppressWarnings({ "unchecked" })
public DefaultTopologicalOrderGraph(final int size) {
this.nodeIdToTopologicalOrderMap = new NodeTopologicalOrder[size];
this.componentMap = CollectionUtils.newLinkedHashMap(size);
this.forwardEdges = new Set[size];
this.backEdges = new Set[size];
this.isNodeInLoopedComponent = new boolean[size];
for (var i = 0; i < size; i++) {
forwardEdges[i] = new HashSet<>();
backEdges[i] = new HashSet<>();
isNodeInLoopedComponent[i] = false;
nodeIdToTopologicalOrderMap[i] = new NodeTopologicalOrder(i, i);
}
}
List<Integer> getComponent(int node) {
return componentMap.get(node);
}
List<List<Integer>> getLoopedComponentList() {
var out = new ArrayList<List<Integer>>(componentMap.size());
var visited = new boolean[forwardEdges.length];
for (var component : componentMap.values()) {
if (component.size() < 2) {
// all looped components have at least 2 members.
// non-looped components have exactly one member.
continue;
}
if (visited[component.get(0)]) {
// already visited this component
continue;
}
// Only need to set first node of a component, since the same
// list is shared for each node in the component
visited[component.get(0)] = true;
out.add(component);
}
return out;
}
@Override
public void addEdge(int fromNode, int toNode) {
forwardEdges[fromNode].add(toNode);
backEdges[toNode].add(fromNode);
}
@Override
public void removeEdge(int fromNode, int toNode) {
forwardEdges[fromNode].remove(toNode);
backEdges[toNode].remove(fromNode);
}
@Override
public void forEachEdge(EdgeConsumer edgeConsumer) {
for (var fromNode = 0; fromNode < forwardEdges.length; fromNode++) {
for (var toNode : forwardEdges[fromNode]) {
edgeConsumer.accept(fromNode, toNode);
}
}
}
@Override
public PrimitiveIterator.OfInt nodeForwardEdges(int fromNode) {
return componentMap.get(fromNode).stream()
.flatMap(member -> forwardEdges[member].stream())
.mapToInt(Integer::intValue)
.distinct().iterator();
}
@Override
public boolean isLooped(LoopedTracker loopedTracker, int node) {
return switch (loopedTracker.status(node)) {
case UNKNOWN -> {
if (componentMap.get(node).size() > 1) {
loopedTracker.mark(node, LoopedStatus.LOOPED);
yield true;
}
for (var backEdge : backEdges[node]) {
if (isLooped(loopedTracker, backEdge)) {
loopedTracker.mark(node, LoopedStatus.LOOPED);
yield true;
}
}
loopedTracker.mark(node, LoopedStatus.NOT_LOOPED);
yield false;
}
case NOT_LOOPED -> false;
case LOOPED -> true;
};
}
@Override
public NodeTopologicalOrder getTopologicalOrder(int node) {
return nodeIdToTopologicalOrderMap[node];
}
@Override
public void commitChanges(BitSet changed) {
var index = new MutableInt(1);
var stackIndex = new MutableInt(0);
var size = forwardEdges.length;
var stack = new int[size];
var indexMap = new int[size];
var lowMap = new int[size];
var onStackSet = new boolean[size];
var components = new ArrayList<BitSet>();
componentMap.clear();
for (var node = 0; node < size; node++) {
if (indexMap[node] == 0) {
strongConnect(node, index, stackIndex, stack, indexMap, lowMap, onStackSet, components);
}
}
var ordIndex = 0;
for (var i = components.size() - 1; i >= 0; i--) {
var component = components.get(i);
var componentSize = component.cardinality();
var isComponentLooped = componentSize != 1;
var componentNodes = new ArrayList<Integer>(componentSize);
for (var node = component.nextSetBit(0); node >= 0; node = component.nextSetBit(node + 1)) {
nodeIdToTopologicalOrderMap[node] = new NodeTopologicalOrder(node, ordIndex);
componentNodes.add(node);
componentMap.put(node, componentNodes);
if (isComponentLooped != isNodeInLoopedComponent[node]) {
// It is enough to only mark nodes whose component
// status changed; the updater will notify descendants
// since a looped status change force updates descendants.
isNodeInLoopedComponent[node] = isComponentLooped;
changed.set(node);
}
ordIndex++;
if (node == Integer.MAX_VALUE) {
break;
}
}
}
}
private void strongConnect(int node, MutableInt index, MutableInt stackIndex, int[] stack,
int[] indexMap,
int[] lowMap, boolean[] onStackSet, List<BitSet> components) {
// Set the depth index for node to the smallest unused index
indexMap[node] = index.intValue();
lowMap[node] = index.intValue();
index.increment();
stack[stackIndex.intValue()] = node;
onStackSet[node] = true;
stackIndex.increment();
// Consider successors of node
for (var successor : forwardEdges[node]) {
if (indexMap[successor] == 0) {
// Successor has not yet been visited; recurse on it
strongConnect(successor, index, stackIndex, stack, indexMap, lowMap, onStackSet, components);
lowMap[node] = Math.min(lowMap[node], lowMap[successor]);
} else if (onStackSet[successor]) {
// Successor is in stack S and hence in the current SCC
// If successor is not on stack, then (node, successor) is an edge pointing to an SCC already found and must be ignored
// The next line may look odd - but is correct.
// It says successor.index not successor.low; that is deliberate and from the original paper
lowMap[node] = Math.min(lowMap[node], indexMap[successor]);
}
}
// If node is a root node, pop the stack and generate an SCC
if (onStackSet[node] && lowMap[node] == indexMap[node]) {
var out = new BitSet();
int current;
do {
current = stack[stackIndex.decrement()];
onStackSet[current] = false;
out.set(current);
} while (node != current);
components.add(out);
}
}
@Override
public String toString() {
var out = new StringBuilder();
out.append("DefaultTopologicalOrderGraph{\n");
for (var node = 0; node < forwardEdges.length; node++) {
out.append(" ").append(node).append("(").append(nodeIdToTopologicalOrderMap[node].order()).append(") -> ")
.append(forwardEdges[node].stream()
.sorted()
.map(Object::toString)
.collect(Collectors.joining(",", "[", "]\n")));
}
out.append("}");
return 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/DefaultVariableReferenceGraph.java | package ai.timefold.solver.core.impl.domain.variable.declarative;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.function.IntFunction;
import org.jspecify.annotations.NonNull;
final class DefaultVariableReferenceGraph<Solution_> extends AbstractVariableReferenceGraph<Solution_, BitSet> {
// These structures are mutable.
private final AffectedEntitiesUpdater<Solution_> affectedEntitiesUpdater;
public DefaultVariableReferenceGraph(VariableReferenceGraphBuilder<Solution_> outerGraph,
IntFunction<TopologicalOrderGraph> graphCreator) {
super(outerGraph, graphCreator);
var entityToVariableReferenceMap = new IdentityHashMap<Object, List<GraphNode<Solution_>>>();
for (var instance : nodeList) {
if (instance.groupEntityIds() == null) {
var entity = instance.entity();
entityToVariableReferenceMap.computeIfAbsent(entity, ignored -> new ArrayList<>())
.add(instance);
} else {
for (var groupEntity : instance.variableReferences().get(0).groupEntities()) {
entityToVariableReferenceMap.computeIfAbsent(groupEntity, ignored -> new ArrayList<>())
.add(instance);
}
}
}
// Immutable optimized version of the map, now that it won't be updated anymore.
var immutableEntityToVariableReferenceMap = mapOfListsDeepCopyOf(entityToVariableReferenceMap);
// This mutable structure is created once, and reused from there on.
// Otherwise its internal collections were observed being re-created so often
// that the allocation of arrays would become a major bottleneck.
affectedEntitiesUpdater =
new AffectedEntitiesUpdater<>(graph, nodeList, immutableEntityToVariableReferenceMap::get,
outerGraph.entityToEntityId.size(), outerGraph.changedVariableNotifier);
}
@Override
protected BitSet createChangeSet(int instanceCount) {
return new BitSet(instanceCount);
}
@Override
public void markChanged(@NonNull GraphNode<Solution_> node) {
changeSet.set(node.graphNodeId());
}
@Override
public void updateChanged() {
if (changeSet.isEmpty()) {
return;
}
graph.commitChanges(changeSet);
affectedEntitiesUpdater.accept(changeSet);
}
/**
* See {@link ConsistencyTracker#setUnknownConsistencyFromEntityShadowVariablesInconsistent}
*/
public void setUnknownInconsistencyValues() {
graph.commitChanges(changeSet);
affectedEntitiesUpdater.setUnknownInconsistencyValues();
}
}
|
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/EmptyVariableReferenceGraph.java | package ai.timefold.solver.core.impl.domain.variable.declarative;
import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel;
final class EmptyVariableReferenceGraph implements VariableReferenceGraph {
public static final EmptyVariableReferenceGraph INSTANCE = new EmptyVariableReferenceGraph();
@Override
public void updateChanged() {
// No need to do anything.
}
@Override
public void beforeVariableChanged(VariableMetaModel<?, ?, ?> variableReference, Object entity) {
// No need to do anything.
}
@Override
public void afterVariableChanged(VariableMetaModel<?, ?, ?> variableReference, Object entity) {
// No need to do anything.
}
@Override
public String toString() {
return "{}";
}
}
|
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/EntityConsistencyState.java | package ai.timefold.solver.core.impl.domain.variable.declarative;
import java.util.IdentityHashMap;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
public final class EntityConsistencyState<Solution_, Entity_> {
private final IdentityHashMap<Entity_, Boolean> entityToIsInconsistentMap;
@Nullable
private final ExternalizedShadowVariableInconsistentProcessor<Solution_> externalizedShadowVariableInconsistentProcessor;
private final VariableDescriptor<Solution_> arbitraryDeclarativeVariableDescriptor;
EntityConsistencyState(EntityDescriptor<Solution_> entityDescriptor,
IdentityHashMap<Entity_, Boolean> entityToIsInconsistentMap) {
this.entityToIsInconsistentMap = entityToIsInconsistentMap;
var entityIsInconsistentDescriptor = entityDescriptor.getShadowVariablesInconsistentDescriptor();
if (entityIsInconsistentDescriptor == null) {
externalizedShadowVariableInconsistentProcessor = null;
arbitraryDeclarativeVariableDescriptor = entityDescriptor.getShadowVariableDescriptors()
.stream()
.filter(variableDescriptor -> variableDescriptor instanceof DeclarativeShadowVariableDescriptor<?>)
.findFirst()
.orElseThrow(() -> new IllegalArgumentException(
"Impossible state: Entity class (%s) does not have any declarative variable descriptors."
.formatted(entityDescriptor.getEntityClass())));
} else {
externalizedShadowVariableInconsistentProcessor =
new ExternalizedShadowVariableInconsistentProcessor<>(entityIsInconsistentDescriptor);
arbitraryDeclarativeVariableDescriptor = entityIsInconsistentDescriptor;
}
}
public boolean isEntityConsistent(Entity_ entity) {
return Boolean.FALSE.equals(entityToIsInconsistentMap.get(entity));
}
@Nullable
Boolean getEntityInconsistentValue(Entity_ entity) {
return entityToIsInconsistentMap.get(entity);
}
public void setEntityIsInconsistent(ChangedVariableNotifier<Solution_> changedVariableNotifier,
Entity_ entity,
boolean isInconsistent) {
if (externalizedShadowVariableInconsistentProcessor != null) {
externalizedShadowVariableInconsistentProcessor.setIsEntityInconsistent(changedVariableNotifier, entity,
isInconsistent);
}
// There may be no ShadowVariablesInconsistent shadow variable,
// so we use an arbitrary declarative shadow variable on the entity to notify the score director
// that the entity changed.
//
// This is needed because null is a valid return value for a supplier, so there
// is no guarantee any declarative would actually change when the entity
// changes from inconsistent to consistent (or vice versa).
// `forEach` checks consistency, and thus must be notified.
//
// Since declarative shadow variables cannot be used as sources for legacy variable listeners,
// this does not cause any issues/additional recalculation of shadow variables.
changedVariableNotifier.beforeVariableChanged().accept(arbitraryDeclarativeVariableDescriptor, entity);
entityToIsInconsistentMap.put(entity, isInconsistent);
changedVariableNotifier.afterVariableChanged().accept(arbitraryDeclarativeVariableDescriptor, entity);
}
@Nullable
Boolean getEntityInconsistentValueFromProcessorOrNull(Entity_ entity) {
if (externalizedShadowVariableInconsistentProcessor != null) {
return externalizedShadowVariableInconsistentProcessor.getIsEntityInconsistent(entity);
}
return null;
}
public void setEntityIsInconsistentSkippingProcessor(Entity_ entity,
boolean isInconsistent) {
entityToIsInconsistentMap.put(entity, isInconsistent);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.