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/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination.java
package ai.timefold.solver.core.impl.solver.termination; import java.time.Clock; import java.util.ArrayDeque; import java.util.Queue; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicPhaseScope; import ai.timefold.solver.core.impl.phase.custom.scope.CustomPhaseScope; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope; import ai.timefold.solver.core.impl.score.director.InnerScore; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import ai.timefold.solver.core.impl.solver.thread.ChildThreadType; import ai.timefold.solver.core.impl.util.Pair; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked final class UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination<Solution_> extends AbstractUniversalTermination<Solution_> implements ChildThreadSupportingTermination<Solution_, SolverScope<Solution_>> { private final long unimprovedTimeMillisSpentLimit; private final Score<?> unimprovedScoreDifferenceThreshold; private final Clock clock; private @Nullable Queue<Pair<Long, InnerScore<?>>> bestScoreImprovementHistoryQueue; // safeTimeMillis is until when we're safe from termination private long solverSafeTimeMillis = -1L; private long phaseSafeTimeMillis = -1L; private boolean currentPhaseSendsBestSolutionEvents = false; public UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination(long unimprovedTimeMillisSpentLimit, Score<?> unimprovedScoreDifferenceThreshold) { this(unimprovedTimeMillisSpentLimit, unimprovedScoreDifferenceThreshold, Clock.systemUTC()); } UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination(long unimprovedTimeMillisSpentLimit, Score<?> unimprovedScoreDifferenceThreshold, Clock clock) { this.unimprovedTimeMillisSpentLimit = unimprovedTimeMillisSpentLimit; if (unimprovedTimeMillisSpentLimit < 0L) { throw new IllegalArgumentException("The unimprovedTimeMillisSpentLimit (%d) cannot be negative." .formatted(unimprovedTimeMillisSpentLimit)); } this.unimprovedScoreDifferenceThreshold = unimprovedScoreDifferenceThreshold; this.clock = clock; } @Override public void solvingStarted(SolverScope<Solution_> solverScope) { resetState(); } void resetState() { bestScoreImprovementHistoryQueue = new ArrayDeque<>(); solverSafeTimeMillis = clock.millis() + unimprovedTimeMillisSpentLimit; } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { bestScoreImprovementHistoryQueue = null; solverSafeTimeMillis = -1L; } @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { phaseSafeTimeMillis = phaseScope.getStartingSystemTimeMillis() + unimprovedTimeMillisSpentLimit; /* * Construction heuristics and similar phases only trigger best solution events at the end. * This means that these phases only provide a meaningful result at their end. * Unimproved time spent termination is not useful for these phases, * as it would terminate the solver prematurely, * skipping any useful phases that follow it, such as local search. * We avoid that by never terminating during these phases, * and resetting the counter to zero when the next phase starts. */ currentPhaseSendsBestSolutionEvents = phaseScope.isPhaseSendingBestSolutionEvents(); } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { phaseSafeTimeMillis = -1L; if (!currentPhaseSendsBestSolutionEvents) { // The next phase starts all over. resetState(); } } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void stepEnded(AbstractStepScope<Solution_> stepScope) { if (stepScope.getBestScoreImproved()) { var solverScope = stepScope.getPhaseScope().getSolverScope(); var bestSolutionTimeMillis = solverScope.getBestSolutionTimeMillis(); var bestScore = solverScope.getBestScore(); var bestScoreValue = (Score) bestScore.raw(); for (var it = bestScoreImprovementHistoryQueue.iterator(); it.hasNext();) { var bestScoreImprovement = it.next(); var bestScoreImprovementValue = bestScoreImprovement.value().raw(); var scoreDifference = bestScoreValue.subtract(bestScoreImprovementValue); var timeLimitNotYetReached = bestScoreImprovement.key() + unimprovedTimeMillisSpentLimit >= bestSolutionTimeMillis; var scoreImprovedOverThreshold = scoreDifference.compareTo(unimprovedScoreDifferenceThreshold) >= 0; if (scoreImprovedOverThreshold && timeLimitNotYetReached) { it.remove(); var safeTimeMillis = bestSolutionTimeMillis + unimprovedTimeMillisSpentLimit; solverSafeTimeMillis = safeTimeMillis; phaseSafeTimeMillis = safeTimeMillis; } else { break; } } bestScoreImprovementHistoryQueue.add(new Pair<>(bestSolutionTimeMillis, bestScore)); } } @Override public boolean isSolverTerminated(SolverScope<Solution_> solverScope) { return isTerminated(solverSafeTimeMillis); } @Override public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) { return isTerminated(phaseSafeTimeMillis); } private boolean isTerminated(long safeTimeMillis) { if (!currentPhaseSendsBestSolutionEvents) { // This phase never terminates early. return false; } // It's possible that there is already an improving move in the forager // that will end up pushing the safeTimeMillis further // but that doesn't change the fact that the best score didn't improve enough in the specified time interval. // It just looks weird because it terminates even though the final step is a high enough score improvement. var now = clock.millis(); return now > safeTimeMillis; } @Override public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) { return calculateTimeGradient(solverSafeTimeMillis); } @Override public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) { return calculateTimeGradient(phaseSafeTimeMillis); } private double calculateTimeGradient(long safeTimeMillis) { if (!currentPhaseSendsBestSolutionEvents) { return 0.0; } var now = clock.millis(); var unimprovedTimeMillisSpent = now - (safeTimeMillis - unimprovedTimeMillisSpentLimit); var timeGradient = unimprovedTimeMillisSpent / ((double) unimprovedTimeMillisSpentLimit); return Math.min(timeGradient, 1.0); } @Override public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope, ChildThreadType childThreadType) { return new UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination<>(unimprovedTimeMillisSpentLimit, unimprovedScoreDifferenceThreshold); } @Override public boolean isApplicableTo(Class<? extends AbstractPhaseScope> phaseScopeClass) { return !(phaseScopeClass == ConstructionHeuristicPhaseScope.class || phaseScopeClass == CustomPhaseScope.class); } @Override public String toString() { return "UnimprovedTimeMillisSpent(" + unimprovedTimeMillisSpentLimit + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/UnimprovedTimeMillisSpentTermination.java
package ai.timefold.solver.core.impl.solver.termination; import java.time.Clock; import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicPhaseScope; import ai.timefold.solver.core.impl.phase.custom.scope.CustomPhaseScope; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import ai.timefold.solver.core.impl.solver.thread.ChildThreadType; import org.jspecify.annotations.NullMarked; @NullMarked final class UnimprovedTimeMillisSpentTermination<Solution_> extends AbstractUniversalTermination<Solution_> implements ChildThreadSupportingTermination<Solution_, SolverScope<Solution_>> { private final long unimprovedTimeMillisSpentLimit; private final Clock clock; private boolean isCounterStarted = false; private boolean currentPhaseSendsBestSolutionEvents = false; private long phaseStartedTimeMillis = -1L; public UnimprovedTimeMillisSpentTermination(long unimprovedTimeMillisSpentLimit) { this(unimprovedTimeMillisSpentLimit, Clock.systemUTC()); } UnimprovedTimeMillisSpentTermination(long unimprovedTimeMillisSpentLimit, Clock clock) { this.unimprovedTimeMillisSpentLimit = unimprovedTimeMillisSpentLimit; if (unimprovedTimeMillisSpentLimit < 0L) { throw new IllegalArgumentException("The unimprovedTimeMillisSpentLimit (%d) cannot be negative." .formatted(unimprovedTimeMillisSpentLimit)); } this.clock = clock; } public long getUnimprovedTimeMillisSpentLimit() { return unimprovedTimeMillisSpentLimit; } @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { /* * Construction heuristics and similar phases only trigger best solution events at the end. * This means that these phases only provide a meaningful result at their end. * Unimproved time spent termination is not useful for these phases, * as it would terminate the solver prematurely, * skipping any useful phases that follow it, such as local search. * We avoid that by never terminating during these phases, * and resetting the counter to zero when the next phase starts. */ currentPhaseSendsBestSolutionEvents = phaseScope.isPhaseSendingBestSolutionEvents(); } @Override public void stepStarted(AbstractStepScope<Solution_> stepScope) { // We reset the count only when the first step begins, // as all necessary resources are loaded, and the phase is ready for execution if (!isCounterStarted) { phaseStartedTimeMillis = clock.millis(); isCounterStarted = true; } } @Override public boolean isSolverTerminated(SolverScope<Solution_> solverScope) { long bestSolutionTimeMillis = solverScope.getBestSolutionTimeMillis(); return isTerminated(bestSolutionTimeMillis); } @Override public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) { if (!isCounterStarted) { return false; } var bestSolutionTimeMillis = phaseScope.getPhaseBestSolutionTimeMillis(); return isTerminated(bestSolutionTimeMillis); } private boolean isTerminated(long bestSolutionTimeMillis) { if (!currentPhaseSendsBestSolutionEvents) { // This phase never terminates early. return false; } return getUnimprovedTimeMillisSpent(bestSolutionTimeMillis) >= unimprovedTimeMillisSpentLimit; } private long getUnimprovedTimeMillisSpent(long bestSolutionTimeMillis) { var now = clock.millis(); return now - Math.max(bestSolutionTimeMillis, phaseStartedTimeMillis); } @Override public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) { long bestSolutionTimeMillis = solverScope.getBestSolutionTimeMillis(); return calculateTimeGradient(bestSolutionTimeMillis); } @Override public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) { var bestSolutionTimeMillis = phaseScope.getPhaseBestSolutionTimeMillis(); return calculateTimeGradient(bestSolutionTimeMillis); } private double calculateTimeGradient(long bestSolutionTimeMillis) { if (!currentPhaseSendsBestSolutionEvents) { return 0.0; } var timeGradient = getUnimprovedTimeMillisSpent(bestSolutionTimeMillis) / ((double) unimprovedTimeMillisSpentLimit); return Math.min(timeGradient, 1.0); } @Override public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope, ChildThreadType childThreadType) { return new UnimprovedTimeMillisSpentTermination<>(unimprovedTimeMillisSpentLimit); } @Override public boolean isApplicableTo(Class<? extends AbstractPhaseScope> phaseScopeClass) { return !(phaseScopeClass == ConstructionHeuristicPhaseScope.class || phaseScopeClass == CustomPhaseScope.class); } @Override public String toString() { return "UnimprovedTimeMillisSpent(" + unimprovedTimeMillisSpentLimit + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/UniversalTermination.java
package ai.timefold.solver.core.impl.solver.termination; import java.util.Collections; import java.util.List; import ai.timefold.solver.core.api.solver.Solver; import ai.timefold.solver.core.impl.phase.Phase; import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleListener; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; /** * Determines when a {@link Solver} or a {@link Phase} should stop. */ @NullMarked public sealed interface UniversalTermination<Solution_> extends PhaseTermination<Solution_>, SolverTermination<Solution_>, PhaseLifecycleListener<Solution_> permits AbstractUniversalTermination { /** * @return Unmodifiable list of {@link PhaseTermination}s that are part of this termination. * If this termination is not a {@link AbstractCompositeTermination}, it returns an empty list. */ default List<PhaseTermination<Solution_>> getPhaseTerminationList() { return Collections.emptyList(); } /** * @return Unmodifiable list of {@link Termination}s that are part of this termination, * which are not applicable to the given phase type * as defined by {@link PhaseTermination#isApplicableTo(Class)}. * If this termination is not a {@link AbstractCompositeTermination}, it returns an empty list. */ @SuppressWarnings("rawtypes") default List<Termination<Solution_>> getPhaseTerminationsInapplicableTo(Class<? extends AbstractPhaseScope> phaseScopeClass) { return getPhaseTerminationList().stream() .filter(f -> !f.isApplicableTo(phaseScopeClass)) .map(t -> (Termination<Solution_>) t) .toList(); } @SafeVarargs static <Solution_> @Nullable UniversalTermination<Solution_> or(Termination<Solution_>... terminations) { if (terminations.length == 0) { return null; } return new OrCompositeTermination<>(terminations); } @SafeVarargs static <Solution_> @Nullable UniversalTermination<Solution_> and(Termination<Solution_>... terminations) { if (terminations.length == 0) { return null; } return new AndCompositeTermination<>(terminations); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/thread/ChildThreadType.java
package ai.timefold.solver.core.impl.solver.thread; import ai.timefold.solver.core.impl.partitionedsearch.PartitionedSearchPhase; public enum ChildThreadType { /** * Used by {@link PartitionedSearchPhase}. */ PART_THREAD, /** * Used by multithreaded incremental solving. */ MOVE_THREAD; }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/thread/DefaultSolverThreadFactory.java
package ai.timefold.solver.core.impl.solver.thread; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * Similar to {@link Executors}'s DefaultThreadFactory, but allows settings a namePrefix. */ public class DefaultSolverThreadFactory implements ThreadFactory { private static final AtomicInteger poolNumber = new AtomicInteger(1); private final ThreadGroup group; private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; public DefaultSolverThreadFactory() { this("Solver"); } public DefaultSolverThreadFactory(String threadPrefix) { SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = "Timefold-" + poolNumber.getAndIncrement() + "-" + threadPrefix + "-"; } @Override public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) { t.setDaemon(false); } if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/thread/ThreadUtils.java
package ai.timefold.solver.core.impl.solver.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ThreadUtils { private static final Logger LOGGER = LoggerFactory.getLogger(ThreadUtils.class); public static void shutdownAwaitOrKill(ExecutorService executor, String logIndentation, String name) { // Intentionally clearing the interrupted flag so that awaitTermination() in step 3 works. if (Thread.interrupted()) { // 2a. If the current thread is interrupted, propagate interrupt signal to children by initiating // an abrupt shutdown. executor.shutdownNow(); } else { // 2b. Otherwise, initiate an orderly shutdown of the executor. This allows partition solvers to finish // solving upon detecting the termination issued previously (step 1). Shutting down the executor // service is important because the JVM cannot exit until all non-daemon threads have terminated. executor.shutdown(); } // 3. Finally, wait until the executor finishes shutting down. try { final int awaitingSeconds = 1; if (!executor.awaitTermination(awaitingSeconds, TimeUnit.SECONDS)) { // Some solvers refused to complete. Busy threads will be interrupted in the finally block. // We're only logging the error instead throwing an exception to prevent eating the original // exception. LOGGER.error( "{}{}'s ExecutorService didn't terminate within timeout ({} seconds).", logIndentation, name, awaitingSeconds); } } catch (InterruptedException e) { // Interrupted while waiting for thread pool termination. Busy threads will be interrupted // in the finally block. Thread.currentThread().interrupt(); // If there is an original exception it will be eaten by this. throw new IllegalStateException("Thread pool termination was interrupted.", e); } finally { // Initiate an abrupt shutdown for the case when any of the previous measures failed. executor.shutdownNow(); } } // ************************************************************************ // Private constructor // ************************************************************************ private ThreadUtils() { } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/util/CollectionUtils.java
package ai.timefold.solver.core.impl.util; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; 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.Set; public final class CollectionUtils { /** * Creates a copy of the list, optionally in reverse order. * * @param originalList the list to copy, preferably {@link ArrayList} * @param reverse true if the resulting list should have its order reversed * @return mutable list, never null * @param <E> the type of elements in the list */ public static <E> List<E> copy(List<E> originalList, boolean reverse) { if (!reverse) { return new ArrayList<>(originalList); } /* * Some move implementations on the hot path rely heavily on list reversal. * As such, the following implementation was benchmarked to perform as well as possible for lists of all sizes. * See PLANNER-2808 for details. */ switch (originalList.size()) { case 0 -> { return new ArrayList<>(0); } case 1 -> { List<E> singletonList = new ArrayList<>(1); singletonList.add(originalList.get(0)); return singletonList; } case 2 -> { List<E> smallList = new ArrayList<>(2); smallList.add(originalList.get(1)); smallList.add(originalList.get(0)); return smallList; } default -> { List<E> largeList = new ArrayList<>(originalList); Collections.reverse(largeList); return largeList; } } } public static <T> List<T> concat(List<T> left, List<T> right) { List<T> result = new ArrayList<>(left.size() + right.size()); result.addAll(left); result.addAll(right); return result; } public static <T> List<T> toDistinctList(Collection<T> collection) { int size = collection.size(); switch (size) { case 0 -> { return Collections.emptyList(); } case 1 -> { if (collection instanceof List<T> list) { return list; // Optimization: not making a defensive copy. } else { return Collections.singletonList(collection.iterator().next()); } } default -> { if (collection instanceof Set<T> set) { return new ArrayList<>(set); } /* * The following is better than ArrayList(LinkedHashSet) because HashSet is cheaper, * while still maintaining the original order of the collection. */ var resultList = new ArrayList<T>(size); var set = newHashSet(size); for (T element : collection) { if (set.add(element)) { resultList.add(element); } } resultList.trimToSize(); return resultList; } } } public static <T> Set<T> newHashSet(int size) { return new HashSet<>(calculateCapacityForDefaultLoadFactor(size)); } private static int calculateCapacityForDefaultLoadFactor(int numElements) { // This guarantees the set/map will never need to grow. return (int) Math.min(Math.ceil(numElements / 0.75d), Integer.MAX_VALUE); } public static <T> Set<T> newIdentityHashSet(int size) { return Collections.newSetFromMap(CollectionUtils.newIdentityHashMap(size)); } public static <T> Set<T> newLinkedHashSet(int size) { return new LinkedHashSet<>(calculateCapacityForDefaultLoadFactor(size)); } public static <K, V> Map<K, V> newHashMap(int size) { return new HashMap<>(calculateCapacityForDefaultLoadFactor(size)); } public static <K, V> Map<K, V> newIdentityHashMap(int size) { return new IdentityHashMap<>(calculateCapacityForDefaultLoadFactor(size)); } public static <K, V> Map<K, V> newLinkedHashMap(int size) { return new LinkedHashMap<>(calculateCapacityForDefaultLoadFactor(size)); } private CollectionUtils() { // No external instances. } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/util/ConcurrentMemoization.java
package ai.timefold.solver.core.impl.util; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; /** * A thread-safe memoization that caches a calculation. * * @param <K> the parameter of the calculation * @param <V> the result of the calculation */ public final class ConcurrentMemoization<K, V> extends ConcurrentHashMap<K, V> { /** * An overridden implementation that heavily favors read access over write access speed. * This is thread-safe. * <p> * {@inheritDoc} */ @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { V value = get(key); if (value != null) { return value; } return super.computeIfAbsent(key, mappingFunction); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/util/ConstantLambdaUtils.java
package ai.timefold.solver.core.impl.util; import java.math.BigDecimal; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Function; import java.util.function.ToIntBiFunction; import java.util.function.ToIntFunction; import java.util.function.ToLongBiFunction; import java.util.function.ToLongFunction; import ai.timefold.solver.core.api.function.QuadFunction; import ai.timefold.solver.core.api.function.ToIntQuadFunction; import ai.timefold.solver.core.api.function.ToIntTriFunction; import ai.timefold.solver.core.api.function.ToLongQuadFunction; import ai.timefold.solver.core.api.function.ToLongTriFunction; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.impl.move.streams.maybeapi.BiDataFilter; /** * A class that holds common lambdas that are guaranteed to be the same across method calls. * In most JDK's, * stateless lambdas are bound to a {@link java.lang.invoke.ConstantCallSite} inside the method that defined them, * but that {@link java.lang.invoke.ConstantCallSite} is not shared across methods, * even for methods in the same class. * Thus, when lambda reference equality is important (such as for node sharing in Constraint Streams), * the lambdas in this class should be used. */ public final class ConstantLambdaUtils { private static final Runnable NO_OP = () -> { }; @SuppressWarnings("rawtypes") private static final Function IDENTITY = Function.identity(); @SuppressWarnings("rawtypes") private static final BiPredicate NOT_EQUALS = (a, b) -> !Objects.equals(a, b); @SuppressWarnings("rawtypes") private static final BiDataFilter NOT_EQUALS_FOR_DATA_STREAMS = (BiDataFilter<Object, Object, Object>) (solutionView, a, b) -> !Objects.equals(a, b); @SuppressWarnings("rawtypes") private static final BiFunction BI_PICK_FIRST = (a, b) -> a; @SuppressWarnings("rawtypes") private static final TriFunction TRI_PICK_FIRST = (a, b, c) -> a; @SuppressWarnings("rawtypes") private static final QuadFunction QUAD_PICK_FIRST = (a, b, c, d) -> a; @SuppressWarnings("rawtypes") private static final BiFunction BI_PICK_SECOND = (a, b) -> b; @SuppressWarnings("rawtypes") private static final TriFunction TRI_PICK_SECOND = (a, b, c) -> b; @SuppressWarnings("rawtypes") private static final QuadFunction QUAD_PICK_SECOND = (a, b, c, d) -> b; @SuppressWarnings("rawtypes") private static final TriFunction TRI_PICK_THIRD = (a, b, c) -> c; @SuppressWarnings("rawtypes") private static final QuadFunction QUAD_PICK_THIRD = (a, b, c, d) -> c; @SuppressWarnings("rawtypes") private static final QuadFunction QUAD_PICK_FOURTH = (a, b, c, d) -> d; @SuppressWarnings("rawtypes") private static final Function UNI_CONSTANT_NULL = a -> null; @SuppressWarnings("rawtypes") private static final ToLongFunction UNI_CONSTANT_ZERO_LONG = a -> 0L; @SuppressWarnings("rawtypes") private static final ToIntFunction UNI_CONSTANT_ONE = a -> 1; @SuppressWarnings("rawtypes") private static final ToLongFunction UNI_CONSTANT_ONE_LONG = a -> 1L; @SuppressWarnings("rawtypes") private static final Function UNI_CONSTANT_ONE_BIG_DECIMAL = a -> BigDecimal.ONE; @SuppressWarnings("rawtypes") private static final BiFunction BI_CONSTANT_NULL = (a, b) -> null; @SuppressWarnings("rawtypes") private static final ToLongBiFunction BI_CONSTANT_ZERO_LONG = (a, b) -> 0L; @SuppressWarnings("rawtypes") private static final ToIntBiFunction BI_CONSTANT_ONE = (a, b) -> 1; @SuppressWarnings("rawtypes") private static final ToLongBiFunction BI_CONSTANT_ONE_LONG = (a, b) -> 1L; @SuppressWarnings("rawtypes") private static final BiFunction BI_CONSTANT_ONE_BIG_DECIMAL = (a, b) -> BigDecimal.ONE; @SuppressWarnings("rawtypes") private static final TriFunction TRI_CONSTANT_NULL = (a, b, c) -> null; @SuppressWarnings("rawtypes") private static final ToLongTriFunction TRI_CONSTANT_ZERO_LONG = (a, b, c) -> 0L; @SuppressWarnings("rawtypes") private static final ToIntTriFunction TRI_CONSTANT_ONE = (a, b, c) -> 1; @SuppressWarnings("rawtypes") private static final ToLongTriFunction TRI_CONSTANT_ONE_LONG = (a, b, c) -> 1L; @SuppressWarnings("rawtypes") private static final TriFunction TRI_CONSTANT_ONE_BIG_DECIMAL = (a, b, c) -> BigDecimal.ONE; @SuppressWarnings("rawtypes") private static final ToLongQuadFunction QUAD_CONSTANT_ZERO_LONG = (a, b, c, d) -> 0L; @SuppressWarnings("rawtypes") private static final ToIntQuadFunction QUAD_CONSTANT_ONE = (a, b, c, d) -> 1; @SuppressWarnings("rawtypes") private static final ToLongQuadFunction QUAD_CONSTANT_ONE_LONG = (a, b, c, d) -> 1L; @SuppressWarnings("rawtypes") private static final QuadFunction QUAD_CONSTANT_ONE_BIG_DECiMAL = (a, b, c, d) -> BigDecimal.ONE; /** * Returns a {@link Runnable} that does nothing. * * @return never null */ public static Runnable noop() { return NO_OP; } /** * Returns a {@link Function} that returns its only input. * * @return never null */ @SuppressWarnings("unchecked") public static <A> Function<A, A> identity() { return IDENTITY; } /** * Returns a {@link BiPredicate} that return true if and only if its inputs are not equal according to * {@link Objects#equals(Object, Object)}. * * @return never null */ @SuppressWarnings("unchecked") public static <A> BiPredicate<A, A> notEquals() { return NOT_EQUALS; } /** * Returns a {@link BiDataFilter} that return true if and only if its inputs are not equal according to * {@link Objects#equals(Object, Object)}. * * @return never null */ @SuppressWarnings("unchecked") public static <Solution_, A> BiDataFilter<Solution_, A, A> notEqualsForDataStreams() { return NOT_EQUALS_FOR_DATA_STREAMS; } /** * Returns a {@link BiFunction} that returns its first input. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B> BiFunction<A, B, A> biPickFirst() { return BI_PICK_FIRST; } /** * Returns a {@link TriFunction} that returns its first input. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B, C> TriFunction<A, B, C, A> triPickFirst() { return TRI_PICK_FIRST; } /** * Returns a {@link QuadFunction} that returns its first input. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B, C, D> QuadFunction<A, B, C, D, A> quadPickFirst() { return QUAD_PICK_FIRST; } /** * Returns a {@link BiFunction} that returns its second input. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B> BiFunction<A, B, B> biPickSecond() { return BI_PICK_SECOND; } /** * Returns a {@link TriFunction} that returns its second input. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B, C> TriFunction<A, B, C, B> triPickSecond() { return TRI_PICK_SECOND; } /** * Returns a {@link QuadFunction} that returns its second input. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B, C, D> QuadFunction<A, B, C, D, B> quadPickSecond() { return QUAD_PICK_SECOND; } /** * Returns a {@link TriFunction} that returns its third input. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B, C> TriFunction<A, B, C, C> triPickThird() { return TRI_PICK_THIRD; } /** * Returns a {@link TriFunction} that returns its third input. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B, C, D> QuadFunction<A, B, C, D, C> quadPickThird() { return QUAD_PICK_THIRD; } /** * Returns a {@link QuadFunction} that returns its fourth input. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B, C, D> QuadFunction<A, B, C, D, D> quadPickFourth() { return QUAD_PICK_FOURTH; } /** * Returns a {@link Function} that returns null. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B> Function<A, B> uniConstantNull() { return UNI_CONSTANT_NULL; } /** * Returns a {@link ToIntFunction} that returns the constant 1. * * @return never null */ @SuppressWarnings("unchecked") public static <A> ToIntFunction<A> uniConstantOne() { return UNI_CONSTANT_ONE; } /** * Returns a {@link ToLongFunction} that returns the constant 0. * * @return never null */ @SuppressWarnings("unchecked") public static <A> ToLongFunction<A> uniConstantZeroLong() { return UNI_CONSTANT_ZERO_LONG; } /** * Returns a {@link ToLongFunction} that returns the constant 1. * * @return never null */ @SuppressWarnings("unchecked") public static <A> ToLongFunction<A> uniConstantOneLong() { return UNI_CONSTANT_ONE_LONG; } /** * Returns a {@link Function} that returns the constant 1. * * @return never null */ @SuppressWarnings("unchecked") public static <A> Function<A, BigDecimal> uniConstantOneBigDecimal() { return UNI_CONSTANT_ONE_BIG_DECIMAL; } /** * Returns a {@link BiFunction} that returns null. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B, C> BiFunction<A, B, C> biConstantNull() { return BI_CONSTANT_NULL; } /** * Returns a {@link ToLongBiFunction} that returns the constant 0. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B> ToLongBiFunction<A, B> biConstantZeroLong() { return BI_CONSTANT_ZERO_LONG; } /** * Returns a {@link ToIntBiFunction} that returns the constant 1. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B> ToIntBiFunction<A, B> biConstantOne() { return BI_CONSTANT_ONE; } /** * Returns a {@link ToLongBiFunction} that returns the constant 1. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B> ToLongBiFunction<A, B> biConstantOneLong() { return BI_CONSTANT_ONE_LONG; } /** * Returns a {@link BiFunction} that returns the constant 1. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B> BiFunction<A, B, BigDecimal> biConstantOneBigDecimal() { return BI_CONSTANT_ONE_BIG_DECIMAL; } /** * Returns a {@link TriFunction} that returns null. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B, C, D> TriFunction<A, B, C, D> triConstantNull() { return TRI_CONSTANT_NULL; } /** * Returns a {@link ToLongTriFunction} that returns the constant 0. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B, C> ToLongTriFunction<A, B, C> triConstantZeroLong() { return TRI_CONSTANT_ZERO_LONG; } /** * Returns a {@link ToIntTriFunction} that returns the constant 1. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B, C> ToIntTriFunction<A, B, C> triConstantOne() { return TRI_CONSTANT_ONE; } /** * Returns a {@link ToLongTriFunction} that returns the constant 1. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B, C> ToLongTriFunction<A, B, C> triConstantOneLong() { return TRI_CONSTANT_ONE_LONG; } /** * Returns a {@link TriFunction} that returns the constant 1. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B, C> TriFunction<A, B, C, BigDecimal> triConstantOneBigDecimal() { return TRI_CONSTANT_ONE_BIG_DECIMAL; } /** * Returns a {@link ToLongQuadFunction} that returns the constant 0. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B, C, D> ToLongQuadFunction<A, B, C, D> quadConstantZeroLong() { return QUAD_CONSTANT_ZERO_LONG; } /** * Returns a {@link ToIntQuadFunction} that returns the constant 1. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B, C, D> ToIntQuadFunction<A, B, C, D> quadConstantOne() { return QUAD_CONSTANT_ONE; } /** * Returns a {@link ToLongQuadFunction} that returns the constant 1. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B, C, D> ToLongQuadFunction<A, B, C, D> quadConstantOneLong() { return QUAD_CONSTANT_ONE_LONG; } /** * Returns a {@link QuadFunction} that returns the constant 1. * * @return never null */ @SuppressWarnings("unchecked") public static <A, B, C, D> QuadFunction<A, B, C, D, BigDecimal> quadConstantOneBigDecimal() { return QUAD_CONSTANT_ONE_BIG_DECiMAL; } private ConstantLambdaUtils() { // No external instances. } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/util/DynamicIntArray.java
package ai.timefold.solver.core.impl.util; import java.util.Arrays; /** * A class representing an int array that is dynamically allocated based on the first set index. * The array is only created when the first element is set and is reallocated as needed * when lower indices are accessed. */ public final class DynamicIntArray { // Growth factor for array expansion; not too much, the point of this class is to avoid excessive memory use. private static final double GROWTH_FACTOR = 1.2; // Minimum capacity increment to avoid small incremental growth private static final int MIN_CAPACITY_INCREMENT = 10; private final ClearingStrategy clearingStrategy; private final int maxLength; private int[] array; private int firstIndex; private int lastIndex; public DynamicIntArray() { this(Integer.MAX_VALUE); } public DynamicIntArray(ClearingStrategy clearingStrategy) { this(Integer.MAX_VALUE, clearingStrategy); } public DynamicIntArray(int maxLength) { this(maxLength, ClearingStrategy.FULL); } public DynamicIntArray(int maxLength, ClearingStrategy clearingStrategy) { this.maxLength = maxLength; this.clearingStrategy = clearingStrategy; initializeArray(); } /** * Sets the value at the specified index. * If this is the first element, the array is created. * If the index is lower than the current firstIndex or higher than the current lastIndex, * the array is reallocated with a growth strategy to reduce frequent reallocations. * * @param index the index at which to set the value * @param value the value to set */ public void set(int index, int value) { if (index < 0 || index >= maxLength) { throw new ArrayIndexOutOfBoundsException(index); } if (array == null) { // First element, create the array with initial capacity var initialCapacity = Math.min(MIN_CAPACITY_INCREMENT, maxLength); array = new int[initialCapacity]; firstIndex = index; lastIndex = index; array[0] = value; } else if (index < firstIndex) { // New index is lower than first index, need to reallocate var currentSize = lastIndex - firstIndex + 1; var offset = firstIndex - index; // Calculate new capacity with growth strategy var requiredCapacity = currentSize + offset; var newCapacity = calculateNewCapacity(requiredCapacity); // Copy existing elements to new array with offset var newArray = new int[newCapacity]; System.arraycopy(array, 0, newArray, offset, currentSize); array = newArray; firstIndex = index; array[0] = value; } else if (index > lastIndex) { // New index is higher than last index, need to expand var currentSize = lastIndex - firstIndex + 1; var newSize = index - firstIndex + 1; if (newSize > array.length) { // Calculate new capacity with growth strategy var newCapacity = calculateNewCapacity(newSize); // Copy existing elements to new array var newArray = new int[newCapacity]; System.arraycopy(array, 0, newArray, 0, currentSize); array = newArray; } // Update last index lastIndex = index; array[index - firstIndex] = value; } else { // Index is within existing range array[index - firstIndex] = value; } } /** * Calculates the new capacity based on the required capacity and growth strategy. * * @param requiredCapacity the minimum capacity needed * @return the new capacity */ private int calculateNewCapacity(int requiredCapacity) { var currentCapacity = array != null ? array.length : 0; if (requiredCapacity <= currentCapacity) { return currentCapacity; } // Calculate new capacity using growth factor var newCapacity = (int) (currentCapacity * GROWTH_FACTOR); // Ensure minimum increment if (newCapacity - currentCapacity < MIN_CAPACITY_INCREMENT) { newCapacity = currentCapacity + MIN_CAPACITY_INCREMENT; } // Ensure new capacity is at least the required capacity if (newCapacity < requiredCapacity) { newCapacity = requiredCapacity; } // Ensure new capacity doesn't exceed maxLength return Math.min(newCapacity, maxLength); } /** * Gets the value at the specified index. * * @param index the index from which to get the value * @return the value at the index * @throws IndexOutOfBoundsException if the index is out of bounds */ public int get(int index) { if (index < 0 || index >= maxLength) { throw new ArrayIndexOutOfBoundsException(index); } if (array == null || index < firstIndex || index > lastIndex) { return 0; } return array[index - firstIndex]; } /** * Checks if the array contains the specified index. * * @param index the index to check * @return true if the index is within bounds, false otherwise */ boolean containsIndex(int index) { return array != null && index >= firstIndex && index <= lastIndex; } /** * Gets the first index of the array. * * @return the first index * @throws IllegalStateException if the array is empty */ int getFirstIndex() { if (array == null) { throw new IllegalStateException("Array is empty"); } return firstIndex; } /** * Gets the last index of the array. * * @return the last index * @throws IllegalStateException if the array is empty */ int getLastIndex() { if (array == null) { throw new IllegalStateException("Array is empty"); } return lastIndex; } /** * Clears the array by setting all values to 0. * The array structure is preserved, only the values are reset. */ public void clear() { if (clearingStrategy == ClearingStrategy.FULL) { initializeArray(); } else { // If array is null, there's nothing to clear if (array == null) { return; } // Only clear the used portion of the array (from firstIndex to lastIndex) // This is more efficient for large arrays with sparse indices Arrays.fill(array, 0, lastIndex - firstIndex + 1, 0); } } private void initializeArray() { this.array = null; this.firstIndex = Integer.MAX_VALUE; this.lastIndex = Integer.MIN_VALUE; } public enum ClearingStrategy { /** * The GC will be allowed to reclaim the array. * This means that, on next access, the array will have to be reallocated and gradually resized, * possibly leading to excessive GC pressure. * * This is the default. */ FULL, /** * The array will not be returned to GC and will be filled with zeros instead. * This has no impact on GC, but may result in greater at-rest heap usage than strictly necessary. */ PARTIAL } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/util/ElementAwareList.java
package ai.timefold.solver.core.impl.util; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Random; import java.util.function.Consumer; /** * Linked list that allows to add and remove an element in O(1) time. * Ideal for incremental operations with frequent undo. * * @param <T> The element type. Often a tuple. */ public final class ElementAwareList<T> implements Iterable<T> { private int size = 0; private ElementAwareListEntry<T> first = null; private ElementAwareListEntry<T> last = null; public ElementAwareListEntry<T> add(T tuple) { ElementAwareListEntry<T> entry = new ElementAwareListEntry<>(this, tuple, last); if (first == null) { first = entry; } else { last.next = entry; } last = entry; size++; return entry; } public ElementAwareListEntry<T> addFirst(T tuple) { if (first != null) { ElementAwareListEntry<T> entry = new ElementAwareListEntry<>(this, tuple, null); first.previous = entry; entry.next = first; first = entry; size++; return entry; } else { return add(tuple); } } public ElementAwareListEntry<T> addAfter(T tuple, ElementAwareListEntry<T> previous) { Objects.requireNonNull(previous); if (first == null || previous == last) { return add(tuple); } else { ElementAwareListEntry<T> entry = new ElementAwareListEntry<>(this, tuple, previous); ElementAwareListEntry<T> currentNext = previous.next; if (currentNext != null) { currentNext.previous = entry; } else { last = entry; } previous.next = entry; entry.next = currentNext; size++; return entry; } } public void remove(ElementAwareListEntry<T> entry) { if (first == entry) { first = entry.next; } else { entry.previous.next = entry.next; } if (last == entry) { last = entry.previous; } else { entry.next.previous = entry.previous; } entry.previous = null; entry.next = null; size--; } public ElementAwareListEntry<T> first() { return first; } public ElementAwareListEntry<T> last() { return last; } public int size() { return size; } /** * Convenience method for where it is easy to use a non-capturing lambda. * If a capturing lambda consumer were to be created for this method, use {@link #iterator()} instead, * which will consume less memory. * <p> * * For example, the following code is perfectly fine: * * <code> * for (int i = 0; i &lt; 3; i++) { * elementAwareList.forEach(entry -&gt; doSomething(entry)); * } * </code> * * It will create only one lambda instance, regardless of the number of iterations; * it doesn't need to capture any state. * On the contrary, the following code will create three instances of a capturing lambda, * one for each iteration of the for loop: * * <code> * for (int a: List.of(1, 2, 3)) { * elementAwareList.forEach(entry -&gt; doSomething(entry, a)); * } * </code> * * In this case, the lambda would need to capture "a" which is different in every iteration. * Therefore, it will generally be better to use the iterator variant, * as that will only ever create one instance of the iterator, * regardless of the number of iterations: * * <code> * for (int a: List.of(1, 2, 3)) { * for (var entry: elementAwareList) { * doSomething(entry, a); * } * } * </code> * * This is only an issue on the hot path, * where this method can create quite a large garbage collector pressure * on account of creating throw-away instances of capturing lambdas. * * @param tupleConsumer The action to be performed for each element */ @Override public void forEach(Consumer<? super T> tupleConsumer) { ElementAwareListEntry<T> entry = first; while (entry != null) { // Extract next before processing it, in case the entry is removed and entry.next becomes null ElementAwareListEntry<T> next = entry.next; tupleConsumer.accept(entry.getElement()); entry = next; } } /** * See {@link #forEach(Consumer)} for a discussion on the correct use of this method. * * @return never null */ @Override public Iterator<T> iterator() { if (size == 0) { return Collections.emptyIterator(); } return new ElementAwareListIterator<>(first); } public void clear() { first = null; last = null; size = 0; } /** * Returns an iterator that will randomly iterate over the elements. * This iterator is exhaustive; once every element has been once iterated over, * the iterator returns false for every subsequent {@link Iterator#hasNext()}. * The iterator does not support the {@link Iterator#remove()} operation. * * @param random The random instance to use for shuffling. * @return never null */ public Iterator<T> randomizedIterator(Random random) { return switch (size) { case 0 -> Collections.emptyIterator(); case 1 -> Collections.singleton(first.getElement()).iterator(); case 2 -> { var list = random.nextBoolean() ? List.of(first.getElement(), last.getElement()) : List.of(last.getElement(), first.getElement()); yield list.iterator(); } default -> { var copy = new ArrayList<T>(size); var indexList = new ArrayList<Integer>(size); forEach(e -> { // Two lists, single iteration. copy.add(e); indexList.add(copy.size() - 1); }); yield new RandomElementAwareListIterator<>(copy, indexList, random); } }; } @Override public String toString() { switch (size) { case 0 -> { return "[]"; } case 1 -> { return "[" + first.getElement() + "]"; } default -> { StringBuilder builder = new StringBuilder("["); for (T entry : this) { builder.append(entry).append(", "); } builder.replace(builder.length() - 2, builder.length(), ""); return builder.append("]").toString(); } } } private static final class ElementAwareListIterator<T> implements Iterator<T> { private ElementAwareListEntry<T> nextEntry; public ElementAwareListIterator(ElementAwareListEntry<T> nextEntry) { this.nextEntry = nextEntry; } @Override public boolean hasNext() { return nextEntry != null; } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } T element = nextEntry.getElement(); nextEntry = nextEntry.next; return element; } } /** * The idea of this iterator is that the list will rarely ever be iterated over in its entirety. * In fact, move streams are likely to only use the first few elements. * Therefore, shuffling the entire list would be a waste of time. * Instead, we pick random index every time and keep a list of unused indexes. * * @param <T> The element type. Often a tuple. */ private static final class RandomElementAwareListIterator<T> implements Iterator<T> { private final List<T> elementList; private final List<Integer> unusedIndexList; private final Random random; public RandomElementAwareListIterator(List<T> copiedList, List<Integer> unusedIndexList, Random random) { this.random = random; this.elementList = copiedList; this.unusedIndexList = unusedIndexList; } @Override public boolean hasNext() { return !unusedIndexList.isEmpty(); } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } var randomUnusedIndex = random.nextInt(unusedIndexList.size()); var elementIndex = unusedIndexList.remove(randomUnusedIndex); return elementList.get(elementIndex); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/util/ElementAwareListEntry.java
package ai.timefold.solver.core.impl.util; /** * An entry of {@link ElementAwareList} * * @param <T> The element type. Often a tuple. */ public final class ElementAwareListEntry<T> { private ElementAwareList<T> list; private final T element; ElementAwareListEntry<T> previous; ElementAwareListEntry<T> next; ElementAwareListEntry(ElementAwareList<T> list, T element, ElementAwareListEntry<T> previous) { this.list = list; this.element = element; this.previous = previous; this.next = null; } public ElementAwareListEntry<T> previous() { return previous; } public ElementAwareListEntry<T> next() { return next; } public void remove() { if (list == null) { throw new IllegalStateException("The element (" + element + ") was already removed."); } list.remove(this); list = null; } public T getElement() { return element; } public ElementAwareList<T> getList() { return list; } @Override public String toString() { return element.toString(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/util/LinkedIdentityHashSet.java
package ai.timefold.solver.core.impl.util; import java.util.AbstractSet; import java.util.IdentityHashMap; import java.util.Iterator; import org.jspecify.annotations.NullMarked; /** * This set does not support null keys. * * @param <V> */ @NullMarked public final class LinkedIdentityHashSet<V> extends AbstractSet<V> { private final ElementAwareList<V> delegate; private final IdentityHashMap<V, ElementAwareListEntry<V>> identityMap; private int size = 0; // Avoid method calls to underlying collections. public LinkedIdentityHashSet() { this.delegate = new ElementAwareList<>(); this.identityMap = new IdentityHashMap<>(); } @Override public Iterator<V> iterator() { return delegate.iterator(); } @Override public int size() { return size; } @Override public boolean contains(Object o) { if (size == 0) { // Micro-optimization; contains() on an empty map is not entirely free. return false; } return identityMap.containsKey(o); } @Override public boolean add(V v) { var entry = identityMap.get(v); if (entry == null) { identityMap.put(v, delegate.add(v)); size += 1; return true; } return false; } @Override public boolean remove(Object o) { if (size == 0) { // Micro-optimization; remove() on an empty map is not entirely free. return false; } var entry = identityMap.remove(o); if (entry == null) { return false; } entry.remove(); size -= 1; return true; } @Override public void clear() { if (size == 0) { // Micro-optimization; clearing empty maps is not entirely free. return; } this.identityMap.clear(); this.delegate.clear(); size = 0; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/util/ListBasedScalingOrderedSet.java
package ai.timefold.solver.core.impl.util; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * An ordered {@link Set} which is implemented as a {@link ArrayList} for a small {@link Set#size()} * and a {@link LinkedHashSet} for a big {@link Set#size()}. * <p> * This speeds up {@link #add(Object)} performance (in some cases by 20%) if most instances have a small size * because no {@link Object#hashCode()} need to be calculated. * * @param <E> */ public final class ListBasedScalingOrderedSet<E> implements Set<E> { protected static final int LIST_SIZE_THRESHOLD = 16; private boolean belowThreshold; private List<E> list; private Set<E> set; public ListBasedScalingOrderedSet() { belowThreshold = true; list = new ArrayList<>(LIST_SIZE_THRESHOLD); set = null; } @Override public int size() { return belowThreshold ? list.size() : set.size(); } @Override public boolean isEmpty() { return belowThreshold ? list.isEmpty() : set.isEmpty(); } @Override public boolean contains(Object o) { return belowThreshold ? list.contains(o) : set.contains(o); } @Override public boolean containsAll(Collection<?> c) { return belowThreshold ? list.containsAll(c) : set.containsAll(c); } @Override public Iterator<E> iterator() { final Iterator<E> childIterator = belowThreshold ? list.iterator() : set.iterator(); return new Iterator<E>() { @Override public boolean hasNext() { return childIterator.hasNext(); } @Override public E next() { return childIterator.next(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public Object[] toArray() { return belowThreshold ? list.toArray() : set.toArray(); } @Override public <T> T[] toArray(T[] a) { return belowThreshold ? list.toArray(a) : set.toArray(a); } @Override public boolean add(E e) { if (belowThreshold) { int newSize = list.size() + 1; if (newSize > LIST_SIZE_THRESHOLD) { set = new LinkedHashSet<>(list); list = null; belowThreshold = false; return set.add(e); } else { if (list.contains(e)) { return false; } return list.add(e); } } else { return set.add(e); } } @Override public boolean addAll(Collection<? extends E> c) { if (belowThreshold) { int newSize = list.size() + c.size(); if (newSize > LIST_SIZE_THRESHOLD) { set = new LinkedHashSet<>(newSize); set.addAll(list); list = null; belowThreshold = false; return set.addAll(c); } else { boolean changed = false; for (E e : c) { if (!list.contains(e)) { changed = true; list.add(e); } } return changed; } } else { return set.addAll(c); } } @Override public boolean remove(Object o) { if (belowThreshold) { return list.remove(o); } else { if (!set.remove(o)) { return false; } int newSize = set.size(); if (newSize <= LIST_SIZE_THRESHOLD) { list = new ArrayList<>(set); set = null; belowThreshold = true; } return true; } } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException("retainAll() not yet implemented"); } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException("removeAll() not yet implemented"); } @Override public void clear() { if (belowThreshold) { list.clear(); } else { list = new ArrayList<>(LIST_SIZE_THRESHOLD); set = null; belowThreshold = true; } } @Override public String toString() { return belowThreshold ? list.toString() : set.toString(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/util/MathUtils.java
package ai.timefold.solver.core.impl.util; import org.apache.commons.math3.util.CombinatoricsUtils; public class MathUtils { public static final long LOG_PRECISION = 1_000_000L; private MathUtils() { } public static long getPossibleArrangementsScaledApproximateLog(long scale, long base, int listSize, int partitions) { double result; if (listSize == 0 || partitions == 0) { // Only one way to divide an empty list, and the log of 1 is 0 // Likewise, there is only 1 way to divide a list into 0 partitions // (since it impossible to do) result = 0L; } else if (partitions <= 2) { // If it a single partition, it the same as the number of permutations. // If it two partitions, it the same as the number of permutations of a list of size // n + 1 (where we add an element to seperate the two partitions) result = CombinatoricsUtils.factorialLog(listSize + partitions - 1); } else { // If it n > 2 partitions, (listSize + partitions - 1)! will overcount by // a multiple of (partitions - 1)! result = CombinatoricsUtils.factorialLog(listSize + partitions - 1) - CombinatoricsUtils.factorialLog(partitions - 1); } // Need to change base to use the given base return Math.round(scale * result / Math.log(base)); } /** * Returns a scaled approximation of a log * * @param scale What to scale the result by. Typically, a power of 10. * @param base The base of the log * @param value The parameter to the log function * @return A value approximately equal to {@code scale * log_base(value)}, rounded * to the nearest integer. */ public static long getScaledApproximateLog(long scale, long base, long value) { return Math.round(scale * getLogInBase(base, value)); } public static double getLogInBase(double base, double value) { return Math.log(value) / Math.log(base); } public static long getSpeed(long count, long timeMillisSpent) { // Avoid divide by zero exception on a fast CPU return count * 1000L / (timeMillisSpent == 0L ? 1L : timeMillisSpent); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/util/MemoizingSupply.java
package ai.timefold.solver.core.impl.util; import java.util.Objects; import java.util.function.Supplier; import ai.timefold.solver.core.impl.domain.variable.supply.Supply; /** * Supply whose value is pre-computed and cached the first time {@link #read()} is called. * * @param <T> */ public final class MemoizingSupply<T> implements Supply { private final Supplier<T> valueSupplier; private boolean cached = false; private T memoizedValue; public MemoizingSupply(Supplier<T> supplier) { this.valueSupplier = Objects.requireNonNull(supplier); } public T read() { if (!cached) { cached = true; // Don't re-compute the supply even if the value was null. memoizedValue = valueSupplier.get(); } return memoizedValue; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/util/MutableInt.java
package ai.timefold.solver.core.impl.util; import java.util.Objects; public final class MutableInt extends Number implements Comparable<MutableInt> { private int value; public MutableInt() { this(0); } public MutableInt(int value) { this.value = value; } public void setValue(int value) { this.value = value; } public int increment() { return add(1); } public int decrement() { return subtract(1); } public int add(int addend) { value += addend; return value; } public int subtract(int subtrahend) { value -= subtrahend; return value; } @Override public int intValue() { return value; } @Override public long longValue() { return value; } @Override public float floatValue() { return value; } @Override public double doubleValue() { return value; } @Override public boolean equals(Object o) { if (o instanceof MutableInt other) { return value == other.value; } return false; } @Override public int hashCode() { return Objects.hash(value); } @Override public int compareTo(MutableInt other) { return Integer.compare(value, other.value); } @Override public String toString() { return Integer.toString(value); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/util/MutableLong.java
package ai.timefold.solver.core.impl.util; import java.util.Objects; public final class MutableLong extends Number implements Comparable<MutableLong> { private long value; public MutableLong() { this(0L); } public MutableLong(long value) { this.value = value; } public void setValue(long value) { this.value = value; } public long increment() { return add(1L); } public long decrement() { return subtract(1L); } public long add(long addend) { value += addend; return value; } public long subtract(long subtrahend) { value -= subtrahend; return value; } @Override public int intValue() { return (int) value; } @Override public long longValue() { return value; } @Override public float floatValue() { return value; } @Override public double doubleValue() { return value; } @Override public boolean equals(Object o) { if (o instanceof MutableLong other) { return value == other.value; } return false; } @Override public int hashCode() { return Objects.hash(value); } @Override public int compareTo(MutableLong other) { return Long.compare(value, other.value); } @Override public String toString() { return Long.toString(value); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/util/MutablePair.java
package ai.timefold.solver.core.impl.util; import java.util.Objects; /** * A mutable key-value tuple. * Two instances {@link Object#equals(Object) are equal} if both values in the first instance * are equal to their counterpart in the other instance. * * @param <A> * @param <B> */ public final class MutablePair<A, B> { public static <A, B> MutablePair<A, B> of(A key, B value) { return new MutablePair<>(key, value); } private A key; private B value; private MutablePair(A key, B value) { this.key = key; this.value = value; } public A getKey() { return key; } public MutablePair<A, B> setKey(A key) { this.key = key; return this; } public B getValue() { return value; } public MutablePair<A, B> setValue(B value) { this.value = value; return this; } @Override public boolean equals(Object o) { if (o instanceof MutablePair<?, ?> other) { return Objects.equals(key, other.key) && Objects.equals(value, other.value); } return false; } @Override public int hashCode() { // Not using Objects.hash(Object...) as that would create an array on the hot path. int result = Objects.hashCode(key); result = 31 * result + Objects.hashCode(value); return result; } @Override public String toString() { return "(" + key + ", " + value + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/util/MutableReference.java
package ai.timefold.solver.core.impl.util; import java.util.Objects; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked public final class MutableReference<Value_> { private @Nullable Value_ value; public MutableReference(@Nullable Value_ value) { this.value = value; } public @Nullable Value_ getValue() { return value; } public void setValue(@Nullable Value_ value) { this.value = value; } @Override public boolean equals(Object o) { if (o instanceof MutableReference<?> other) { return Objects.equals(value, other.value); } return false; } @Override public int hashCode() { return Objects.hash(value); } @Override public String toString() { return value == null ? "null" : value.toString(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/util/Pair.java
package ai.timefold.solver.core.impl.util; /** * An immutable key-value tuple. * Two instances {@link Object#equals(Object) are equal} if both values in the first instance * are equal to their counterpart in the other instance. * * @param <Key_> * @param <Value_> */ public record Pair<Key_, Value_>(Key_ key, Value_ value) { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/util/Quadruple.java
package ai.timefold.solver.core.impl.util; /** * An immutable tuple of four values. * Two instances {@link Object#equals(Object) are equal} if all four values in the first instance * are equal to their counterpart in the other instance. * * @param <A> * @param <B> * @param <C> * @param <D> */ public record Quadruple<A, B, C, D>(A a, B b, C c, D d) { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/util/Triple.java
package ai.timefold.solver.core.impl.util; /** * An immutable tuple of three values. * Two instances {@link Object#equals(Object) are equal} if all three values in the first instance * are equal to their counterpart in the other instance. * * @param <A> * @param <B> * @param <C> */ public record Triple<A, B, C>(A a, B b, C c) { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/package-info.java
/** * <strong>This package and all of its subpackages are only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. */ package ai.timefold.solver.core.preview.api;
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/metamodel/DefaultPositionInList.java
package ai.timefold.solver.core.preview.api.domain.metamodel; import java.util.Objects; import java.util.function.Supplier; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; /** * Points to a list variable position specified by an entity and an index. */ @NullMarked record DefaultPositionInList(Object entity, int index) implements PositionInList { public DefaultPositionInList { Objects.requireNonNull(entity); if (index < 0) { throw new IllegalArgumentException("Impossible state: index (%d) not positive." .formatted(index)); } } @Override public PositionInList ensureAssigned(Supplier<String> messageSupplier) { return this; } @Override public boolean equals(@Nullable Object element) { if (!(element instanceof DefaultPositionInList that)) { return false; } return index == that.index && entity == that.entity; } @Override public int hashCode() { var result = 1; result = 31 * result + (System.identityHashCode(entity)); result = 31 * result + (Integer.hashCode(index)); return result; } @Override public String toString() { return entity + "[" + index + "]"; } @Override public int compareTo(PositionInList other) { return Integer.compare(index, other.index()); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/metamodel/DefaultUnassignedElement.java
package ai.timefold.solver.core.preview.api.domain.metamodel; import java.util.function.Supplier; import org.jspecify.annotations.NullMarked; @NullMarked record DefaultUnassignedElement() implements UnassignedElement { public static final DefaultUnassignedElement INSTANCE = new DefaultUnassignedElement(); @Override public PositionInList ensureAssigned(Supplier<String> messageSupplier) { throw new IllegalStateException(messageSupplier.get()); } @Override public String toString() { return "UnassignedLocation"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/metamodel/ElementPosition.java
package ai.timefold.solver.core.preview.api.domain.metamodel; import java.util.function.Supplier; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import org.jspecify.annotations.NullMarked; /** * A supertype for {@link PositionInList} and {@link UnassignedElement}. * <p> * {@link PlanningListVariable#allowsUnassignedValues()} allows for a value to not be part of any entity's list. * This introduces null into user code, and makes it harder to reason about the code. * Therefore, we introduce {@link UnassignedElement} to represent this null value, * and user code must explicitly decide how to handle this case. * This prevents accidental use of {@link UnassignedElement} in places where {@link PositionInList} is expected, * catching this error as early as possible. * <p> * <strong>This package and all of its contents are part of the Move Streams API, * which is under development and is only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. * <p> * We encourage you to try the API and give us feedback on your experience with it, * before we finalize the API. * Please direct your feedback to * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>. */ @NullMarked public sealed interface ElementPosition permits PositionInList, UnassignedElement { /** * Create a new instance of {@link PositionInList}. * User code should never need to call this method. * * @param entity Entity whose {@link PlanningListVariable} contains the value. * @param index 0 or higher * @return never null */ static PositionInList of(Object entity, int index) { return new DefaultPositionInList(entity, index); } /** * Returns a singleton instance of {@link UnassignedElement}. * User code should never need to call this method. * * @return never null */ static UnassignedElement unassigned() { return DefaultUnassignedElement.INSTANCE; } /** * Returns {@link PositionInList} if this position is assigned, otherwise throws an exception. * * @return Position of the value in an entity's {@link PlanningListVariable}. * @throws IllegalStateException If this position is unassigned. */ default PositionInList ensureAssigned() { return ensureAssigned(() -> "Unexpected unassigned position."); } /** * Returns {@link PositionInList} if this position is assigned, otherwise throws an exception. * * @param messageSupplier The message to give the exception. * @return Position of the value in an entity's {@link PlanningListVariable}. * @throws IllegalStateException If this position is unassigned. */ PositionInList ensureAssigned(Supplier<String> messageSupplier); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/metamodel/GenuineVariableMetaModel.java
package ai.timefold.solver.core.preview.api.domain.metamodel; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import org.jspecify.annotations.NullMarked; /** * A {@link VariableMetaModel} that represents a @{@link PlanningVariable basic planning variable}. * * <p> * <strong>This package and all of its contents are part of the Move Streams API, * which is under development and is only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. * <p> * We encourage you to try the API and give us feedback on your experience with it, * before we finalize the API. * Please direct your feedback to * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>. * * @param <Solution_> the solution type * @param <Entity_> the entity type * @param <Value_> the value type */ @NullMarked public sealed interface GenuineVariableMetaModel<Solution_, Entity_, Value_> extends VariableMetaModel<Solution_, Entity_, Value_> permits PlanningVariableMetaModel, PlanningListVariableMetaModel { @Override default boolean isGenuine() { return true; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/metamodel/PlanningEntityMetaModel.java
package ai.timefold.solver.core.preview.api.domain.metamodel; import java.util.List; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import org.jspecify.annotations.NullMarked; /** * Represents the meta-model of an entity. * Gives access to the entity's variable meta-models. * <p> * <strong>This package and all of its contents are part of the Move Streams API, * which is under development and is only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. * <p> * We encourage you to try the API and give us feedback on your experience with it, * before we finalize the API. * Please direct your feedback to * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>. * * @param <Solution_> The solution type. * @param <Entity_> The entity type. */ @NullMarked public interface PlanningEntityMetaModel<Solution_, Entity_> { /** * Describes the {@link PlanningSolution} that owns this entity. * * @return never null, the solution meta-model. */ PlanningSolutionMetaModel<Solution_> solution(); /** * Returns the most specific class of the entity. * * @return The entity type. */ Class<Entity_> type(); /** * Returns the variables declared by the entity, both genuine and shadow. * * @return Variables declared by the entity. */ List<VariableMetaModel<Solution_, Entity_, ?>> variables(); /** * Returns the genuine variables declared by the entity. * * @return Genuine variables declared by the entity. */ @SuppressWarnings({ "unchecked", "rawtypes" }) default List<GenuineVariableMetaModel<Solution_, Entity_, ?>> genuineVariables() { return (List) variables().stream() .filter(VariableMetaModel::isGenuine) .map(v -> (GenuineVariableMetaModel<Solution_, Entity_, ?>) v) .toList(); } /** * Returns a single genuine variable declared by the entity. * * @param <Value_> The type of the value of the variable. * @return The single genuine variable declared by the entity. * @throws IllegalStateException if the entity declares multiple genuine variables, or none. */ @SuppressWarnings("unchecked") default <Value_> GenuineVariableMetaModel<Solution_, Entity_, Value_> genuineVariable() { var genuineVariables = genuineVariables(); return switch (genuineVariables.size()) { case 0 -> throw new IllegalStateException("The entity class (%s) has no genuine variables." .formatted(type().getCanonicalName())); case 1 -> (GenuineVariableMetaModel<Solution_, Entity_, Value_>) genuineVariables.get(0); default -> throw new IllegalStateException("The entity class (%s) has multiple genuine variables (%s)." .formatted(type().getCanonicalName(), genuineVariables)); }; } /** * Returns a {@link PlanningVariableMetaModel} for a variable with the given name. * * @return A genuine variable declared by the entity. * @throws IllegalArgumentException if the variable does not exist on the entity, or is not genuine */ @SuppressWarnings("unchecked") default <Value_> GenuineVariableMetaModel<Solution_, Entity_, Value_> genuineVariable(String variableName) { var variable = variable(variableName); if (!variable.isGenuine()) { throw new IllegalArgumentException( "The variableName (%s) exists among variables (%s) but is not genuine.".formatted(variableName, variables())); } return (GenuineVariableMetaModel<Solution_, Entity_, Value_>) variable; } /** * Returns a {@link VariableMetaModel} for a variable with the given name. * * @return A variable declared by the entity. * @throws IllegalArgumentException where {@link #hasVariable(String)} would have returned false. */ @SuppressWarnings("unchecked") default <Value_> VariableMetaModel<Solution_, Entity_, Value_> variable(String variableName) { for (var variableMetaModel : variables()) { if (variableMetaModel.name().equals(variableName)) { return (VariableMetaModel<Solution_, Entity_, Value_>) variableMetaModel; } } throw new IllegalArgumentException( "The variableName (%s) does not exist in the variables (%s).".formatted(variableName, variables())); } /** * Checks whether a variable is present on the entity. * * @return True if present, false otherwise. * @see #variable(String) Method to retrieve the variable's meta-model, or fail if it is not present. */ default boolean hasVariable(String variableName) { for (var variableMetaModel : variables()) { if (variableMetaModel.name().equals(variableName)) { return true; } } return false; } /** * As defined by {@link #genuineVariable()} ()}, * but only succeeds if the variable is a {@link PlanningVariable basic planning variable}. */ @SuppressWarnings("unchecked") default <Value_> PlanningVariableMetaModel<Solution_, Entity_, Value_> planningVariable() { return (PlanningVariableMetaModel<Solution_, Entity_, Value_>) genuineVariable(); } /** * As defined by {@link #variable(String)}, * but only succeeds if the variable is a {@link PlanningVariable basic planning variable}. */ @SuppressWarnings("unchecked") default <Value_> PlanningVariableMetaModel<Solution_, Entity_, Value_> planningVariable(String variableName) { return (PlanningVariableMetaModel<Solution_, Entity_, Value_>) variable(variableName); } /** * As defined by {@link #genuineVariable()}, * but only succeeds if the variable is a {@link PlanningListVariable planning list variable}. */ @SuppressWarnings("unchecked") default <Value_> PlanningListVariableMetaModel<Solution_, Entity_, Value_> planningListVariable() { return (PlanningListVariableMetaModel<Solution_, Entity_, Value_>) genuineVariable(); } /** * As defined by {@link #variable(String)}, * but only succeeds if the variable is a {@link PlanningListVariable planning list variable}. */ @SuppressWarnings("unchecked") default <Value_> PlanningListVariableMetaModel<Solution_, Entity_, Value_> planningListVariable(String variableName) { return (PlanningListVariableMetaModel<Solution_, Entity_, Value_>) variable(variableName); } /** * As defined by {@link #variable(String)}, * but only succeeds if the variable is a shadow variable}. */ @SuppressWarnings("unchecked") default <Value_> ShadowVariableMetaModel<Solution_, Entity_, Value_> shadowVariable(String variableName) { return (ShadowVariableMetaModel<Solution_, Entity_, Value_>) variable(variableName); } /** * Returns whether the entity declares any genuine variables. * * @return true if the entity declares any genuine variables, false otherwise. */ default boolean isGenuine() { for (var variableMetaModel : variables()) { if (variableMetaModel.isGenuine()) { return true; } } return false; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/metamodel/PlanningListVariableMetaModel.java
package ai.timefold.solver.core.preview.api.domain.metamodel; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import org.jspecify.annotations.NullMarked; /** * A {@link VariableMetaModel} that represents a @{@link PlanningVariable list planning variable}. * <p> * <strong>This package and all of its contents are part of the Move Streams API, * which is under development and is only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. * <p> * We encourage you to try the API and give us feedback on your experience with it, * before we finalize the API. * Please direct your feedback to * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>. * * @param <Solution_> the solution type * @param <Entity_> the entity type * @param <Value_> the value type */ @NullMarked public non-sealed interface PlanningListVariableMetaModel<Solution_, Entity_, Value_> extends GenuineVariableMetaModel<Solution_, Entity_, Value_> { @Override default boolean isList() { return true; } /** * Returns whether the planning variable allows values not to be assigned to any entity's list variable. * * @return {@code true} if the planning variable allows unassigned values, {@code false} otherwise. */ boolean allowsUnassignedValues(); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/metamodel/PlanningSolutionMetaModel.java
package ai.timefold.solver.core.preview.api.domain.metamodel; import java.util.List; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import org.jspecify.annotations.NullMarked; /** * Represents the meta-model of a {@link PlanningSolution}. * Allows access to information about all the entities and variables. * <p> * <strong>This package and all of its contents are part of the Move Streams API, * which is under development and is only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. * <p> * We encourage you to try the API and give us feedback on your experience with it, * before we finalize the API. * Please direct your feedback to * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>. * * @param <Solution_> the type of the solution */ @NullMarked public interface PlanningSolutionMetaModel<Solution_> { /** * Returns the class of the solution. * * @return never null, the type of the solution */ Class<Solution_> type(); /** * Returns the meta-models of @{@link PlanningEntity planning entities} known to the solution, genuine or shadow. * * @return Entities declared by the solution. */ List<PlanningEntityMetaModel<Solution_, ?>> entities(); /** * Returns the meta-models of genuine @{@link PlanningEntity planning entities} known to the solution. * * @return Entities declared by the solution, which declare some genuine variables. */ default List<PlanningEntityMetaModel<Solution_, ?>> genuineEntities() { return entities().stream() .filter(PlanningEntityMetaModel::isGenuine) .toList(); } /** * Returns the meta-model of the @{@link PlanningEntity planning entity} with the given class. * * @param entityClass Expected class of the entity. * @return An entity declared by the solution. * @throws IllegalArgumentException where {@link #hasEntity(Class)} would have returned false. */ @SuppressWarnings("unchecked") default <Entity_> PlanningEntityMetaModel<Solution_, Entity_> entity(Class<Entity_> entityClass) { for (var entityMetaModel : entities()) { if (entityMetaModel.type().equals(entityClass)) { return (PlanningEntityMetaModel<Solution_, Entity_>) entityMetaModel; } } throw new IllegalArgumentException( "The type (%s) is not among known entities (%s).".formatted(entityClass, entities())); } /** * Checks whether an {@link PlanningEntity}-annotated class is known by the solution. * * @return True if known, false otherwise. * @see #entity(Class) Method to retrieve the entity's meta-model, or fail if it is not present. */ default boolean hasEntity(Class<?> entityClass) { for (var entityMetaModel : entities()) { if (entityMetaModel.type().equals(entityClass)) { return true; } } return false; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/metamodel/PlanningVariableMetaModel.java
package ai.timefold.solver.core.preview.api.domain.metamodel; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import org.jspecify.annotations.NullMarked; /** * A {@link VariableMetaModel} that represents a @{@link PlanningVariable basic planning variable}. * * <p> * <strong>This package and all of its contents are part of the Move Streams API, * which is under development and is only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. * <p> * We encourage you to try the API and give us feedback on your experience with it, * before we finalize the API. * Please direct your feedback to * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>. * * @param <Solution_> the solution type * @param <Entity_> the entity type * @param <Value_> the value type */ @NullMarked public non-sealed interface PlanningVariableMetaModel<Solution_, Entity_, Value_> extends GenuineVariableMetaModel<Solution_, Entity_, Value_> { @Override default boolean isList() { return false; } /** * Returns whether the planning variable allows null values. * * @return {@code true} if the planning variable allows null values, {@code false} otherwise. */ boolean allowsUnassigned(); /** * Returns whether the planning variable is chained. * * @return {@code true} if the planning variable is chained, {@code false} otherwise. */ boolean isChained(); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/metamodel/PositionInList.java
package ai.timefold.solver.core.preview.api.domain.metamodel; import org.jspecify.annotations.NullMarked; /** * Uniquely identifies the position of a value in a list variable. * Instances can be created by {@link ElementPosition#of(Object, int)}. * <p> * Within that one list, the index is unique for each value and therefore the instances are comparable. * Comparing them between different lists has no meaning. * <p> * <strong>This package and all of its contents are part of the Move Streams API, * which is under development and is only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. * <p> * We encourage you to try the API and give us feedback on your experience with it, * before we finalize the API. * Please direct your feedback to * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>. * */ @NullMarked public sealed interface PositionInList extends ElementPosition, Comparable<PositionInList> permits DefaultPositionInList { <Entity_> Entity_ entity(); int index(); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/metamodel/ShadowVariableMetaModel.java
package ai.timefold.solver.core.preview.api.domain.metamodel; import ai.timefold.solver.core.api.domain.variable.VariableListener; import org.jspecify.annotations.NullMarked; /** * A {@link VariableMetaModel} that represents a shadow planning variable. * The solver doesn't directly modify a shadow variable; * its value is derived from genuine variables * (see {@link PlanningVariableMetaModel} and {@link PlanningListVariableMetaModel}) * using a {@link VariableListener} provided either internally or by the user. * <p> * <strong>This package and all of its contents are part of the Move Streams API, * which is under development and is only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. * <p> * We encourage you to try the API and give us feedback on your experience with it, * before we finalize the API. * Please direct your feedback to * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>. * * @param <Solution_> the solution type * @param <Entity_> the entity type * @param <Value_> the value type */ @NullMarked public non-sealed interface ShadowVariableMetaModel<Solution_, Entity_, Value_> extends VariableMetaModel<Solution_, Entity_, Value_> { @Override default boolean isList() { return false; } @Override default boolean isGenuine() { return false; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/metamodel/UnassignedElement.java
package ai.timefold.solver.core.preview.api.domain.metamodel; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import org.jspecify.annotations.NullMarked; /** * Identifies that a given value was not found in any {@link PlanningEntity}'s list variables. * Singleton instance can be accessed by {@link ElementPosition#unassigned()}. * <p> * <strong>This package and all of its contents are part of the Move Streams API, * which is under development and is only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. * <p> * We encourage you to try the API and give us feedback on your experience with it, * before we finalize the API. * Please direct your feedback to * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>. */ @NullMarked public sealed interface UnassignedElement extends ElementPosition permits DefaultUnassignedElement { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/metamodel/VariableMetaModel.java
package ai.timefold.solver.core.preview.api.domain.metamodel; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import org.jspecify.annotations.NullMarked; /** * Describes a variable in the domain model. * See extending interfaces for more specific types of variables. * <p> * <strong>This package and all of its contents are part of the Move Streams API, * which is under development and is only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. * <p> * We encourage you to try the API and give us feedback on your experience with it, * before we finalize the API. * Please direct your feedback to * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>. * * @param <Solution_> * @param <Entity_> * @param <Value_> */ @NullMarked public sealed interface VariableMetaModel<Solution_, Entity_, Value_> permits GenuineVariableMetaModel, ShadowVariableMetaModel { /** * Describes the entity that owns this variable. * * @return never null */ PlanningEntityMetaModel<Solution_, Entity_> entity(); /** * Describes the type of the value that this variable can hold. * * @return never null */ Class<Value_> type(); /** * Describes the name of this variable, which is typically a field name in the entity. * * @return never null */ String name(); /** * Whether this variable is a @{@link PlanningListVariable} or a {@link PlanningVariable}. * If list, this is guaranteed to extend {@link PlanningListVariableMetaModel}. * Otherwise it is guaranteed to extend either {@link PlanningVariableMetaModel} or {@link ShadowVariableMetaModel}. * * @return true if this variable is a genuine @{@link PlanningListVariable}, false otherwise */ boolean isList(); /** * Whether this variable is a genuine variable. * If genuine, this is guaranteed to extend either {@link PlanningVariableMetaModel} or * {@link PlanningListVariableMetaModel}. * Otherwise it is guaranteed to extend {@link ShadowVariableMetaModel}. * * @return true if this variable is genuine, false otherwise */ boolean isGenuine(); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/metamodel/package-info.java
/** * This package contains classes and interfaces that represent the metamodel of the domain. * This meta-model describes the planning solution, its entities and their variables, * typically for use within {@link ai.timefold.solver.core.preview.api.move.Move}s * * <p> * <strong>This package and all of its contents are part of the Move Streams API, * which is under development and is only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. * <p> * We encourage you to try the API and give us feedback on your experience with it, * before we finalize the API. * Please direct your feedback to * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>. */ package ai.timefold.solver.core.preview.api.domain.metamodel;
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/solution
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/solution/diff/PlanningEntityDiff.java
package ai.timefold.solver.core.preview.api.domain.solution.diff; import java.util.Collection; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningEntityMetaModel; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; /** * A diff between two instances of a {@link PlanningEntity}, * where at least one variable of that entity (genuine or shadow) changed. * Obtain from {@link PlanningSolutionDiff}. * <p> * This interface is not intended to be implemented by users. * The default implementation has a default {@code toString()} method that prints a summary of the differences. * Do not attempt to parse that string - it is subject to change in the future. * * @param <Solution_> * @param <Entity_> */ @NullMarked public interface PlanningEntityDiff<Solution_, Entity_> { /** * The diff between the two solutions that this is part of. */ PlanningSolutionDiff<Solution_> solutionDiff(); /** * The entity that this diff is of. */ Entity_ entity(); /** * Describes the {@link PlanningEntity} class. */ PlanningEntityMetaModel<Solution_, Entity_> entityMetaModel(); /** * Returns a single diff for the entity's variables. * It is a convenience method for {@link #variableDiff(String)} - * if the entity provided more than one diff, which may happen for multi-variate entities, this method will throw. * * @throws IllegalStateException if {@link #variableDiffs()} returns more than one diff. */ <Value_> PlanningVariableDiff<Solution_, Entity_, Value_> variableDiff(); /** * Returns the diff for the variable with the given name, or null if the variable is not present in the diff. * * @param variableName Name of the variable to check for. * @return Null if the entity does not declare a variable of that name. * @param <Value_> Expected type of the variable. */ @Nullable <Value_> PlanningVariableDiff<Solution_, Entity_, Value_> variableDiff(String variableName); /** * Returns the diffs of all variables of a single changed entity. */ Collection<PlanningVariableDiff<Solution_, Entity_, ?>> variableDiffs(); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/solution
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/solution/diff/PlanningSolutionDiff.java
package ai.timefold.solver.core.preview.api.domain.solution.diff; import java.util.Set; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.solver.SolutionManager; import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningSolutionMetaModel; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; /** * A diff between two instances of a {@link PlanningSolution}. * Obtain using {@link SolutionManager#diff(Object, Object)}. * The first argument to that method is called the "old" solution, * and the second argument is called the "new" solution. * See the Javadoc of {@link SolutionManager#diff(Object, Object)} for more information. * <p> * This interface is not intended to be implemented by users. * The default implementation has a default {@code toString()} method that prints a summary of the differences. * Do not attempt to parse that string - it is subject to change in the future. * * @param <Solution_> */ @NullMarked public interface PlanningSolutionDiff<Solution_> { /** * Describes the {@link PlanningSolution} class. */ PlanningSolutionMetaModel<Solution_> solutionMetaModel(); /** * Returns the diff for the given entity, or null if the entity is not present in the diff. * * @param entity Entity to check for. * @return Null if the entity is not present in the diff (= did not change.) */ @Nullable <Entity_> PlanningEntityDiff<Solution_, Entity_> entityDiff(Entity_ entity); /** * Returns the diffs of all entities that can be found in both the old and new solution, * where at least one variable (genuine or shadow) of that entity changed. */ Set<PlanningEntityDiff<Solution_, ?>> entityDiffs(); /** * As defined by {@link #entityDiffs()}, but only for entities of the given class. * * @param entityClass Entity class to filter on. */ <Entity_> Set<PlanningEntityDiff<Solution_, Entity_>> entityDiffs(Class<Entity_> entityClass); /** * Returns all entities that were present in the old solution, but are not in the new. */ Set<Object> removedEntities(); /** * Returns all entities that are present in the new solution, but were not in the old. */ Set<Object> addedEntities(); /** * Returns the old solution. */ Solution_ oldSolution(); /** * Returns the new solution. */ Solution_ newSolution(); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/solution
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/solution/diff/PlanningVariableDiff.java
package ai.timefold.solver.core.preview.api.domain.solution.diff; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; /** * A diff between two values of a single planning variable of a single {@link PlanningEntity}, * Obtain from {@link PlanningEntityDiff}. * <p> * This interface is not intended to be implemented by users. * The default implementation has a default {@code toString()} method that prints a summary of the differences. * Do not attempt to parse that string - it is subject to change in the future. * * @param <Solution_> * @param <Entity_> * @param <Value_> */ @NullMarked public interface PlanningVariableDiff<Solution_, Entity_, Value_> { /** * The parent diff between the two entities, where this diff comes from. */ PlanningEntityDiff<Solution_, Entity_> entityDiff(); /** * Describes the variable that this diff is of. */ VariableMetaModel<Solution_, Entity_, Value_> variableMetaModel(); /** * The entity that this diff is about. */ default Entity_ entity() { return entityDiff().entity(); } /** * The old value of the variable. * * @return Null if the variable was null. */ @Nullable Value_ oldValue(); /** * The new value of the variable. * * @return Null if the variable is null. */ @Nullable Value_ newValue(); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/solution
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/domain/solution/diff/package-info.java
/** * This package contains classes and interfaces that support * the diffing of {@link ai.timefold.solver.core.api.domain.solution.PlanningSolution}s. * using the {@link ai.timefold.solver.core.api.solver.SolutionManager#diff(java.lang.Object, java.lang.Object)}. * * <p> * <strong>This package and all of its contents is only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. * <p> * We encourage you to try the API and give us feedback on your experience with it, * before we finalize it. * Please direct your feedback to * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>. */ package ai.timefold.solver.core.preview.api.domain.solution.diff;
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/move/Move.java
package ai.timefold.solver.core.preview.api.move; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.domain.lookup.PlanningId; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.solution.ProblemFactProperty; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import ai.timefold.solver.core.api.score.director.ScoreDirector; import org.jspecify.annotations.NullMarked; /** * A Move represents a change of 1 or more {@link PlanningVariable}s of 1 or more {@link PlanningEntity}s * in the working {@link PlanningSolution}. * <p> * Usually the move holds a direct reference to each {@link PlanningEntity} of the {@link PlanningSolution} * which it will change when {@link #execute(MutableSolutionView)} is called. * It is recommended for the moves to not touch shadow variables, * the solver will update shadow variables after move execution is complete. * If the move has to touch shadow variables, it is responsible for updating them * consistently across the entire dependency graph. * <p> * For tabu search, a Move should implement {@link Object#equals(Object)} and {@link Object#hashCode()}, * {@link #extractPlanningEntities()} and {@link #extractPlanningValues()}. * <p> * <strong>This package and all of its contents are part of the Move Streams API, * which is under development and is only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. * <p> * We encourage you to try the API and give us feedback on your experience with it, * before we finalize the API. * Please direct your feedback to * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>. * * @param <Solution_> */ @NullMarked public interface Move<Solution_> { /** * Runs the move and optionally records the changes done, * so that they can be undone later. * * @param solutionView Exposes all possible mutative operations on the variables. * Remembers those mutative operations and can replay them in reverse order * when the solver needs to undo the move. * Do not store this parameter in a field. */ void execute(MutableSolutionView<Solution_> solutionView); /** * Rebases a move from an origin {@link ScoreDirector} to another destination {@link ScoreDirector} * which is usually on another {@link Thread}. * It is necessary for multithreaded solving to function. * <p> * The new move returned by this method translates the entities and problem facts * to the destination {@link PlanningSolution} of the destination {@link ScoreDirector}, * That destination {@link PlanningSolution} is a deep planning clone (or an even deeper clone) * of the origin {@link PlanningSolution} that this move has been generated from. * <p> * That new move does the exact same change as this move, * resulting in the same {@link PlanningSolution} state, * presuming that destination {@link PlanningSolution} was in the same state * as the original {@link PlanningSolution} to begin with. * <p> * An implementation of this method typically iterates through every entity and fact instance in this move, * translates each one to the destination {@link ScoreDirector} with {@link Rebaser#rebase(Object)} * and creates a new move instance of the same move type, using those translated instances. * <p> * The destination {@link PlanningSolution} can be in a different state than the original {@link PlanningSolution}. * So, rebasing can only depend on the identity of {@link PlanningEntity planning entities} * and {@link ProblemFactProperty problem facts}, * which are usually declared by a {@link PlanningId} on those classes. * It must not depend on the state of the {@link PlanningVariable planning variables}. * One thread might rebase a move before, amid or after another thread does that same move instance. * <p> * This method is thread-safe. * * @param rebaser Do not store this parameter in a field * @return New move that does the same change as this move on another solution instance */ Move<Solution_> rebase(Rebaser rebaser); /** * Returns all planning entities that this move is changing. * Required for entity tabu. * <p> * This method is only called after {@link #execute(MutableSolutionView)}, which might affect the return values. * <p> * Duplicate entries in the returned {@link Collection} are best avoided. * The returned {@link Collection} is recommended to be in a stable order. * For example, use {@link List} or {@link LinkedHashSet}, but not {@link HashSet}. * * @return Each entity only once. * TODO convert to SequencedCollection when on Java 21. */ default Collection<?> extractPlanningEntities() { throw new UnsupportedOperationException("The move (" + this + ") does not support tabu search."); } /** * Returns all planning values that this move is assigning to entity variables. * Required for value tabu. * <p> * This method is only called after {@link #execute(MutableSolutionView)}, which might affect the return values. * <p> * Duplicate entries in the returned {@link Collection} are best avoided. * The returned {@link Collection} is recommended to be in a stable order. * For example, use {@link List} or {@link LinkedHashSet}, but not {@link HashSet}. * * @return Each value only once. May contain null. * TODO convert to SequencedCollection when on Java 21. */ default Collection<?> extractPlanningValues() { throw new UnsupportedOperationException("The move (" + this + ") does not support tabu search."); } /** * TODO this probably needs a better API, * as move implementations are now expected to be primarily produced by users * and the solver is thus expected to encounter custom moves significantly more. * * Describes the move type for statistical purposes. * For example, a move which changes a variable "computer" on a class "Process" could be described as * "ChangeMove(Process.computer)". * <p> * The format is not formalized. * Never parse the {@link String} returned by this method, * it is only intended to be used by the solver. * * @return Non-empty {@link String} that describes the move type. * */ default String describe() { return getClass().getSimpleName(); } /** * The solver will make sure to only call this when the move is actually printed out during debug logging. * * @return A description of the move, ideally including the state of the planning entities being changed. */ @Override String toString(); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/move/MutableSolutionView.java
package ai.timefold.solver.core.preview.api.move; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningListVariableMetaModel; import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningVariableMetaModel; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; /** * Contains all reading and mutating methods available to a {@link Move} * in order to change the state of a {@link PlanningSolution planning solution}. * <p> * <strong>This package and all of its contents are part of the Move Streams API, * which is under development and is only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. * <p> * We encourage you to try the API and give us feedback on your experience with it, * before we finalize the API. * Please direct your feedback to * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>. * * @param <Solution_> */ @NullMarked public interface MutableSolutionView<Solution_> extends SolutionView<Solution_> { /** * Puts a given value at a particular index in a given entity's {@link PlanningListVariable planning list variable}. * Moves all values at or after the index to the right. * * @param variableMetaModel Describes the variable to be changed. * @param value The value to be assigned to a list variable. * @param destinationEntity The entity whose list variable is to be changed. * @param destinationIndex The index in the list variable at which the value is to be assigned, * moving the pre-existing value at that index and all subsequent values to the right. */ <Entity_, Value_> void assignValue(PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Value_ value, Entity_ destinationEntity, int destinationIndex); /** * Removes a given value from the {@link PlanningListVariable planning list variable} that it's part of. * Shifts any later values to the left. * * @param variableMetaModel Describes the variable to be changed. * @param value The value to be removed from a list variable. * @throws IllegalStateException if the value is not assigned to a list variable */ <Entity_, Value_> void unassignValue(PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Value_ value); /** * Removes a value from a given entity's {@link PlanningListVariable planning list variable} at a given index. * Shifts any later values to the left. * * @param variableMetaModel Describes the variable to be changed. * @param entity The entity whose element is to be removed from a list variable. * @param index The index in entity's list variable which contains the value to be removed; * Acceptable values range from zero to one less than list size. * All values after the index are shifted to the left. * @return the removed value * @throws IllegalArgumentException if the index is out of bounds */ <Entity_, Value_> Value_ unassignValue(PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Entity_ entity, int index); /** * Reads the value of a @{@link PlanningVariable basic planning variable} of a given entity. * * @param variableMetaModel Describes the variable to be changed. * @param entity The entity whose variable value is to be changed. * @param newValue maybe null, if unassigning the variable */ <Entity_, Value_> void changeVariable(PlanningVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Entity_ entity, @Nullable Value_ newValue); /** * Moves a value from one entity's {@link PlanningListVariable planning list variable} to another. * * @param variableMetaModel Describes the variable to be changed. * @param sourceEntity The entity from which the value will be removed. * @param sourceIndex The index in the source entity's list variable which contains the value to be moved; * Acceptable values range from zero to one less than list size. * All values after the index are shifted to the left. * @param destinationEntity The entity to which the value will be added. * @param destinationIndex The index in the destination entity's list variable to which the value will be moved; * Acceptable values range from zero to one less than list size. * All values at or after the index are shifted to the right. * @return the value that was moved; null if nothing was moved * @throws IndexOutOfBoundsException if the index is out of bounds */ <Entity_, Value_> @Nullable Value_ moveValueBetweenLists( PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Entity_ sourceEntity, int sourceIndex, Entity_ destinationEntity, int destinationIndex); /** * Moves a value within one entity's {@link PlanningListVariable planning list variable}. * * @param variableMetaModel Describes the variable to be changed. * @param sourceEntity The entity whose variable value is to be changed. * @param sourceIndex The index in the source entity's list variable which contains the value to be moved; * Acceptable values range from zero to one less than list size. * All values after the index are shifted to the left. * @param destinationIndex The index in the source entity's list variable to which the value will be moved; * Acceptable values range from zero to one less than list size. * All values at or after the index are shifted to the right. * @return the value that was moved; null if nothing was moved * @throws IndexOutOfBoundsException if the index is out of bounds */ <Entity_, Value_> @Nullable Value_ moveValueInList( PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Entity_ sourceEntity, int sourceIndex, int destinationIndex); /** * Swaps two values between two entities' {@link PlanningListVariable planning list variable}. * * @param variableMetaModel Describes the variable to be changed. * @param leftEntity The first entity whose variable value is to be swapped. * @param leftIndex The index in the left entity's list variable which contains the value to be swapped; * Acceptable values range from zero to one less than list size. * @param rightEntity The second entity whose variable value is to be swapped. * @param rightIndex The index in the right entity's list variable which contains the other value to be swapped; * Acceptable values range from zero to one less than list size. * @throws IndexOutOfBoundsException if the index is out of bounds */ <Entity_, Value_> void swapValuesBetweenLists( PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Entity_ leftEntity, int leftIndex, Entity_ rightEntity, int rightIndex); /** * Swaps two values within one entity's {@link PlanningListVariable planning list variable}. * * @param variableMetaModel Describes the variable to be changed. * @param entity The entity whose variable values are to be swapped. * @param leftIndex The index in the entity's list variable which contains the value to be swapped; * Acceptable values range from zero to one less than list size. * @param rightIndex The index in the entity's list variable which contains the other value to be swapped; * Acceptable values range from zero to one less than list size. * @throws IndexOutOfBoundsException if the index is out of bounds */ <Entity_, Value_> void swapValuesInList( PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Entity_ entity, int leftIndex, int rightIndex); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/move/Rebaser.java
package ai.timefold.solver.core.preview.api.move; 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.score.director.ScoreDirector; import ai.timefold.solver.core.api.solver.change.ProblemChange; import org.jspecify.annotations.Nullable; /** * Allows to transfer an entity or fact instance (often from another {@link Thread}) * to another {@link ScoreDirector}'s internal working instance. * <p> * <strong>This package and all of its contents are part of the Move Streams API, * which is under development and is only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. * <p> * We encourage you to try the API and give us feedback on your experience with it, * before we finalize the API. * Please direct your feedback to * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>. */ public interface Rebaser { /** * Translates an entity or fact instance (often from another {@link Thread}) * to another {@link ScoreDirector}'s internal working instance. * Useful for move rebasing and in a {@link ProblemChange} and for multi-threaded solving. * <p> * Matching is determined by the {@link LookUpStrategyType} on {@link PlanningSolution}. * Matching uses a {@link PlanningId} by default. * * @param problemFactOrPlanningEntity The fact or entity to rebase. * @return null if problemFactOrPlanningEntity is null * @throws IllegalArgumentException if there is no working object for the fact or entity, * if it cannot be looked up, * or if its class is not supported. * @throws IllegalStateException if it cannot be looked up * @param <T> */ <T> @Nullable T rebase(@Nullable T problemFactOrPlanningEntity); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/move/SolutionView.java
package ai.timefold.solver.core.preview.api.move; 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.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import ai.timefold.solver.core.preview.api.domain.metamodel.ElementPosition; import ai.timefold.solver.core.preview.api.domain.metamodel.GenuineVariableMetaModel; import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningListVariableMetaModel; import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningVariableMetaModel; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; /** * Allows read-only access to the state of the solution that is being operated on by the {@link Move}. * <p> * <strong>This package and all of its contents are part of the Move Streams API, * which is under development and is only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. * <p> * We encourage you to try the API and give us feedback on your experience with it, * before we finalize the API. * Please direct your feedback to * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>. * * @param <Solution_> */ @NullMarked public interface SolutionView<Solution_> { /** * Reads the value of a @{@link PlanningVariable basic planning variable} of a given entity. * * @param variableMetaModel Describes the variable whose value is to be read. * @param entity The entity whose variable is to be read. * @return The value of the variable on the entity. */ <Entity_, Value_> @Nullable Value_ getValue(PlanningVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Entity_ entity); /** * Reads the value of a {@link PlanningListVariable list planning variable} and returns its length. * * @param variableMetaModel Describes the variable whose value is to be read. * @param entity The entity whose variable is to be read. * @return The number of values in the list variable. * @throws NullPointerException if the value of the list variable is null * @throws IndexOutOfBoundsException if the index is out of bounds */ <Entity_, Value_> int countValues(PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Entity_ entity); /** * Reads the value of a @{@link PlanningListVariable list planning variable} of a given entity at a specific index. * * @param variableMetaModel Describes the variable whose value is to be read. * @param entity The entity whose variable is to be read. * @param index >= 0 * @return The value at the given index in the list variable. * @throws NullPointerException if the value of the list variable is null * @throws IndexOutOfBoundsException if the index is out of bounds */ <Entity_, Value_> Value_ getValueAtIndex(PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Entity_ entity, int index); /** * Locates a given value in any @{@link PlanningListVariable list planning variable}. * * @param variableMetaModel Describes the variable whose value is to be read. * @param value The value to locate. * @return the location of the value in the variable */ <Entity_, Value_> ElementPosition getPositionOf(PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Value_ value); /** * Checks if a {@link PlanningEntity} with a basic {@link PlanningVariable} is pinned. * * @param variableMetaModel Describes the variable whose value is to be read. * @param entity The entity to check if it is pinned. * @return boolean indicating if the value is pinned in the variable */ <Entity_, Value_> boolean isPinned(PlanningVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, @Nullable Entity_ entity); /** * Checking if a {@link PlanningListVariable}'s value is pinned requires checking: * <ul> * <li>the entity's {@link PlanningPin} field,</li> * <li>the entity's {@link PlanningPinToIndex} field,</li> * <li>and the value's position in the list variable.</li> * </ul> * As this is complex, this method is provided as a convenience. * * @param variableMetaModel Describes the variable whose value is to be read. * @param value The value to check if it is pinned; may be null, in which case the method returns false. * @return boolean indicating if the value is pinned in the variable */ <Entity_, Value_> boolean isPinned(PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, @Nullable Value_ value); /** * Checks if a given value is present in the value range of a genuine planning variable, * when the value range is defined on {@link PlanningSolution}. * * @param variableMetaModel variable in question * @param value value to check * @return true if the value is acceptable for the variable * @param <Entity_> generic type of the entity that the variable is defined on * @param <Value_> generic type of the value that the variable can take * @throws IllegalArgumentException if the value range is on an entity as opposed to a solution; * use {@link #isValueInRange(GenuineVariableMetaModel, Object, Object)} to provide the entity instance. */ default <Entity_, Value_> boolean isValueInRange(GenuineVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, @Nullable Value_ value) { return isValueInRange(variableMetaModel, null, value); } /** * Checks if a given value is present in the value range of a genuine planning variable. * If the value range is defined on {@link PlanningEntity entity}, * the {@code entity} argument must not be null. * * @param variableMetaModel variable in question * @param entity entity that the value would be applied to; * must be of a type that the variable is defined on * @param value value to check * @return true if the value is acceptable for the variable * @param <Entity_> generic type of the entity that the variable is defined on * @param <Value_> generic type of the value that the variable can take * @throws IllegalArgumentException if the value range is on an entity as opposed to a solution, and the entity is null */ <Entity_, Value_> boolean isValueInRange(GenuineVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, @Nullable Entity_ entity, @Nullable Value_ value); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/preview/api/move/package-info.java
/** * This package contains classes and interfaces that are used to write moves to explore the neighborhood of a * {@link ai.timefold.solver.core.api.domain.solution.PlanningSolution}. * It will eventually replace the move selector framework. * * <p> * <strong>This package and all of its contents are part of the Move Streams API, * which is under development and is only offered as a preview feature.</strong> * There are no guarantees for backward compatibility; * any class, method, or field may change or be removed without prior notice, * although we will strive to avoid this as much as possible. * <p> * We encourage you to try the API and give us feedback on your experience with it, * before we finalize the API. * Please direct your feedback to * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>. */ package ai.timefold.solver.core.preview.api.move;
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/autodiscover/AutoDiscoverMemberType.java
package ai.timefold.solver.core.api.domain.autodiscover; import ai.timefold.solver.core.api.domain.constraintweight.ConstraintConfigurationProvider; 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; /** * Determines if and how to automatically presume * {@link ConstraintConfigurationProvider}, {@link ProblemFactCollectionProperty}, {@link ProblemFactProperty}, * {@link PlanningEntityCollectionProperty}, {@link PlanningEntityProperty} and {@link PlanningScore} annotations * on {@link PlanningSolution} members based from the member type. */ public enum AutoDiscoverMemberType { /** * Do not reflect. */ NONE, /** * Reflect over the fields and automatically behave as the appropriate annotation is there * based on the field type. */ FIELD, /** * Reflect over the getter methods and automatically behave as the appropriate annotation is there * based on the return type. */ GETTER; }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/constraintweight/ConstraintConfiguration.java
package ai.timefold.solver.core.api.domain.constraintweight; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; /** * Allows end users to change the constraint weights, by not hard coding them. * This annotation specifies that the class holds a number of {@link ConstraintWeight} annotated members. * That class must also have a {@link ConstraintWeight weight} for each of the constraints. * <p> * A {@link PlanningSolution} has at most one field or property annotated with {@link ConstraintConfigurationProvider} * with returns a type of the {@link ConstraintConfiguration} annotated class. */ @Target({ TYPE }) @Retention(RUNTIME) public @interface ConstraintConfiguration { /** * The namespace of the constraints. * <p> * This is the default for every {@link ConstraintWeight#constraintPackage()} in the annotated class. * * @return defaults to the annotated class's package. */ String constraintPackage() default ""; }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/constraintweight/ConstraintConfigurationProvider.java
package ai.timefold.solver.core.api.domain.constraintweight; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.solution.ProblemFactProperty; /** * Specifies that a property (or a field) on a {@link PlanningSolution} class is a {@link ConstraintConfiguration}. * This property is automatically a {@link ProblemFactProperty} too, so no need to declare that explicitly. * <p> * The type of this property (or field) must have a {@link ConstraintConfiguration} annotation. */ @Target({ METHOD, FIELD }) @Retention(RUNTIME) public @interface ConstraintConfigurationProvider { }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/constraintweight/ConstraintWeight.java
package ai.timefold.solver.core.api.domain.constraintweight; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import ai.timefold.solver.core.api.score.Score; /** * Specifies that a bean property (or a field) set the constraint weight and score level of a constraint. * For example, with a constraint weight of {@code 2soft}, * a constraint match penalization with weightMultiplier {@code 3} * will result in a {@link Score} of {@code -6soft}. * <p> * It is specified on a getter of a java bean property (or directly on a field) of a {@link ConstraintConfiguration} class. */ @Target({ FIELD, METHOD }) @Retention(RUNTIME) public @interface ConstraintWeight { /** * The constraint package is the namespace of the constraint. * <p> * The constraint id is this constraint package * concatenated with "/" and {@link #value() the constraint name}. * * @return defaults to {@link ConstraintConfiguration#constraintPackage()} */ String constraintPackage() default ""; /** * The constraint name. * <p> * The constraint id is {@link #constraintPackage() the constraint package} * concatenated with "/" and this constraint name. * * @return never null, often a constant that is used by the constraints too, because they need to match. */ String value(); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/entity/PinningFilter.java
package ai.timefold.solver.core.api.domain.entity; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; /** * Decides on accepting or discarding a {@link PlanningEntity}. * A pinned {@link PlanningEntity}'s planning variables are never changed. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <Entity_> the entity type, the class with the {@link PlanningEntity} annotation */ public interface PinningFilter<Solution_, Entity_> { /** * @param solution working solution to which the entity belongs * @param entity never null, a {@link PlanningEntity} * @return true if the entity it is pinned, false if the entity is movable. */ boolean accept(Solution_ solution, Entity_ entity); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/entity/PlanningEntity.java
package ai.timefold.solver.core.api.domain.entity; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.Comparator; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionSorterWeightFactory; /** * Specifies that the class is a planning entity. * There are two types of entities: * * <dl> * <dt>Genuine entity</dt> * <dd>Must have at least 1 genuine {@link PlanningVariable planning variable}, * and 0 or more shadow variables.</dd> * <dt>Shadow entity</dt> * <dd>Must have at least 1 shadow variable, and no genuine variables.</dd> * </dl> * * If a planning entity has neither a genuine nor a shadow variable, * it is not a planning entity and the solver will fail fast. * * <p> * The class should have a public no-arg constructor, so it can be cloned * (unless the {@link PlanningSolution#solutionCloner()} is specified). */ @Target({ TYPE }) @Retention(RUNTIME) public @interface PlanningEntity { /** * A pinned planning entity is never changed during planning, * this is useful in repeated planning use cases (such as continuous planning and real-time planning). * <p> * This applies to all the planning variables of this planning entity. * To pin individual variables, see https://issues.redhat.com/browse/PLANNER-124 * <p> * The method {@link PinningFilter#accept(Object, Object)} returns false if the selection entity is pinned * and it returns true if the selection entity is movable * * @return {@link NullPinningFilter} when it is null (workaround for annotation limitation) */ Class<? extends PinningFilter> pinningFilter() default NullPinningFilter.class; /** Workaround for annotation limitation in {@link #pinningFilter()} ()}. */ interface NullPinningFilter extends PinningFilter { } /** * Allows a collection of planning entities to be sorted by difficulty. * A difficultyWeight estimates how hard is to plan a certain PlanningEntity. * Some algorithms benefit from planning on more difficult planning entities first/last or from focusing on them. * <p> * The {@link Comparator} should sort in ascending difficulty * (even though many optimization algorithms will reverse it). * For example: sorting 3 processes on difficultly based on their RAM usage requirement: * Process B (1GB RAM), Process A (2GB RAM), Process C (7GB RAM), * <p> * Do not use together with {@link #difficultyWeightFactoryClass()}. * * @return {@link NullDifficultyComparator} when it is null (workaround for annotation limitation) * @see #difficultyWeightFactoryClass() */ Class<? extends Comparator> difficultyComparatorClass() default NullDifficultyComparator.class; /** Workaround for annotation limitation in {@link #difficultyComparatorClass()}. */ interface NullDifficultyComparator extends Comparator { } /** * The {@link SelectionSorterWeightFactory} alternative for {@link #difficultyComparatorClass()}. * <p> * Do not use together with {@link #difficultyComparatorClass()}. * * @return {@link NullDifficultyWeightFactory} when it is null (workaround for annotation limitation) * @see #difficultyComparatorClass() */ Class<? extends SelectionSorterWeightFactory> difficultyWeightFactoryClass() default NullDifficultyWeightFactory.class; /** Workaround for annotation limitation in {@link #difficultyWeightFactoryClass()}. */ interface NullDifficultyWeightFactory extends SelectionSorterWeightFactory { } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/entity/PlanningPin.java
package ai.timefold.solver.core.api.domain.entity; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; /** * Specifies that a boolean property (or field) of a {@link PlanningEntity} determines if the planning entity is pinned. * A pinned planning entity is never changed during planning. * For example, it allows the user to pin a shift to a specific employee before solving * and the solver will not undo that, regardless of the constraints. * <p> * The boolean is false if the planning entity is movable and true if the planning entity is pinned. * <p> * It applies to all the planning variables of that planning entity. * If set on an entity with {@link PlanningListVariable}, * this will pin the entire list of planning values as well. * <p> * This is syntactic sugar for {@link PlanningEntity#pinningFilter()}, * which is a more flexible and verbose way to pin a planning entity. */ @Target({ METHOD, FIELD }) @Retention(RUNTIME) public @interface PlanningPin { }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/entity/PlanningPinToIndex.java
package ai.timefold.solver.core.api.domain.entity; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; /** * Specifies that an {@code int} property (or field) of a {@link PlanningEntity} determines * how far a {@link PlanningListVariable} is pinned. * <p> * This annotation can only be specified on a field of the same entity, * which also specifies a {@link PlanningListVariable}. * The annotated int field has the following semantics: * * <ul> * <li>0: Pinning is disabled. * All the values in the list can be removed, * new values may be added anywhere in the list, * values in the list may be reordered.</li> * <li>Positive int: Values before this index in the list are pinned. * No value can be added at those indexes, * removed from them, or shuffled between them. * Values on or after this index are not pinned * and can be added, removed or shuffled freely.</li> * <li>Positive int that exceeds the lists size: fail fast.</li> * <li>Negative int: fail fast.</li> * </ul> * * To pin the entire list and disallow any changes, use {@link PlanningPin} instead. * * <p> * Example: Assuming a list of values {@code [A, B, C]}: * * <ul> * <li>0 or null allows the entire list to be modified.</li> * <li>1 pins {@code A}; rest of the list may be modified or added to.</li> * <li>2 pins {@code A, B}; rest of the list may be modified or added to.</li> * <li>3 pins {@code A, B, C}; the list can only be added to.</li> * <li>4 fails fast as there is no such index in the list.</li> * </ul> * * If the same entity also specifies a {@link PlanningPin} and the pin is enabled, * any value of {@link PlanningPinToIndex} is ignored. * In other words, enabling {@link PlanningPin} pins the entire list without exception. */ @Target({ METHOD, FIELD }) @Retention(RUNTIME) public @interface PlanningPinToIndex { }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/lookup/LookUpStrategyType.java
package ai.timefold.solver.core.api.domain.lookup; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty; import ai.timefold.solver.core.api.score.director.ScoreDirector; /** * Determines how {@link ScoreDirector#lookUpWorkingObject(Object)} maps * a {@link ProblemFactCollectionProperty problem fact} or a {@link PlanningEntity planning entity} * from an external copy to the internal one. */ public enum LookUpStrategyType { /** * Map by the same {@link PlanningId} field or method. * If there is no such field or method, * there is no mapping and {@link ScoreDirector#lookUpWorkingObject(Object)} must not be used. * If there is such a field or method, but it returns null, it fails fast. * <p> * This is the default. */ PLANNING_ID_OR_NONE, /** * Map by the same {@link PlanningId} field or method. * If there is no such field or method, it fails fast. */ PLANNING_ID_OR_FAIL_FAST, /** * Map by {@link Object#equals(Object) equals(Object)} and {@link Object#hashCode() hashCode()}. * If any of these two methods is not overridden by the working object's class or some of its superclasses, * {@link ScoreDirector#lookUpWorkingObject(Object)} must not be used because it cannot work correctly with * {@link Object}'s equals and hashCode implementations. */ EQUALITY, /** * There is no mapping and {@link ScoreDirector#lookUpWorkingObject(Object)} must not be used. */ NONE; }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/solution/PlanningEntityCollectionProperty.java
package ai.timefold.solver.core.api.domain.solution; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.Collection; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.score.director.ScoreDirector; /** * Specifies that a property (or a field) on a {@link PlanningSolution} class is a {@link Collection} of planning entities. * <p> * Every element in the planning entity collection should have the {@link PlanningEntity} annotation. * Every element in the planning entity collection will be added to the {@link ScoreDirector}. */ @Target({ METHOD, FIELD }) @Retention(RUNTIME) public @interface PlanningEntityCollectionProperty { }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/solution/PlanningSolution.java
package ai.timefold.solver.core.api.domain.solution; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import ai.timefold.solver.core.api.domain.autodiscover.AutoDiscoverMemberType; import ai.timefold.solver.core.api.domain.constraintweight.ConstraintConfigurationProvider; import ai.timefold.solver.core.api.domain.lookup.LookUpStrategyType; import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner; /** * Specifies that the class is a planning solution. * A solution represents a problem and a possible solution of that problem. * A possible solution does not need to be optimal or even feasible. * A solution's planning variables might not be initialized (especially when delivered as a problem). * <p> * A solution is mutable. * For scalability reasons (to facilitate incremental score calculation), * the same solution instance (called the working solution per move thread) is continuously modified. * It's cloned to recall the best solution. * <p> * Each planning solution must have exactly 1 {@link PlanningScore} property. * <p> * Each planning solution must have at least 1 {@link PlanningEntityCollectionProperty} * or {@link PlanningEntityProperty} property. * <p> * Each planning solution is recommended to have 1 {@link ConstraintConfigurationProvider} property too. * <p> * Each planning solution used with ConstraintStream score calculation must have at least 1 * {@link ProblemFactCollectionProperty} * or {@link ProblemFactProperty} property. * <p> * The class should have a public no-arg constructor, so it can be cloned * (unless the {@link #solutionCloner()} is specified). */ @Target({ TYPE }) @Retention(RUNTIME) public @interface PlanningSolution { /** * Enable reflection through the members of the class * to automatically assume {@link PlanningScore}, {@link PlanningEntityCollectionProperty}, * {@link PlanningEntityProperty}, {@link ProblemFactCollectionProperty}, {@link ProblemFactProperty} * and {@link ConstraintConfigurationProvider} annotations based on the member type. * * <p> * This feature is not supported under Quarkus. * When using Quarkus, * setting this to anything other than {@link AutoDiscoverMemberType#NONE} will result in a build-time exception. * * @return never null */ AutoDiscoverMemberType autoDiscoverMemberType() default AutoDiscoverMemberType.NONE; /** * Overrides the default {@link SolutionCloner} to implement a custom {@link PlanningSolution} cloning implementation. * <p> * If this is not specified, then the default reflection-based {@link SolutionCloner} is used, * so you don't have to worry about it. * * @return {@link NullSolutionCloner} when it is null (workaround for annotation limitation) */ Class<? extends SolutionCloner> solutionCloner() default NullSolutionCloner.class; /** Workaround for annotation limitation in {@link #solutionCloner()}. */ interface NullSolutionCloner extends SolutionCloner { } /** * @return never null */ LookUpStrategyType lookUpStrategyType() default LookUpStrategyType.PLANNING_ID_OR_NONE; }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/solution/ProblemFactCollectionProperty.java
package ai.timefold.solver.core.api.domain.solution; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.Collection; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.score.stream.ConstraintFactory; import ai.timefold.solver.core.api.score.stream.ConstraintProvider; import ai.timefold.solver.core.api.solver.change.ProblemChange; /** * Specifies that a property (or a field) on a {@link PlanningSolution} class is a {@link Collection} of problem facts. * A problem fact must not change during solving (except through a {@link ProblemChange} event). * <p> * The constraints in a {@link ConstraintProvider} rely on problem facts for {@link ConstraintFactory#forEach(Class)}. * <p> * Do not annotate {@link PlanningEntity planning entities} as problem facts: * they are automatically available as facts for {@link ConstraintFactory#forEach(Class)}. * * @see ProblemFactProperty */ @Target({ METHOD, FIELD }) @Retention(RUNTIME) public @interface ProblemFactCollectionProperty { }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/solution/ProblemFactProperty.java
package ai.timefold.solver.core.api.domain.solution; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import ai.timefold.solver.core.api.domain.constraintweight.ConstraintConfiguration; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.score.stream.ConstraintFactory; import ai.timefold.solver.core.api.score.stream.ConstraintProvider; import ai.timefold.solver.core.api.solver.change.ProblemChange; /** * Specifies that a property (or a field) on a {@link PlanningSolution} class is a problem fact. * A problem fact must not change during solving (except through a {@link ProblemChange} event). * <p> * The constraints in a {@link ConstraintProvider} rely on problem facts for {@link ConstraintFactory#forEach(Class)}. * <p> * Do not annotate a {@link PlanningEntity planning entity} or a {@link ConstraintConfiguration planning paramerization} * as a problem fact: they are automatically available as facts for {@link ConstraintFactory#forEach(Class)}. * * @see ProblemFactCollectionProperty */ @Target({ METHOD, FIELD }) @Retention(RUNTIME) public @interface ProblemFactProperty { }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/solution
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/solution/cloner/SolutionCloner.java
package ai.timefold.solver.core.api.domain.solution.cloner; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; /** * Clones a {@link PlanningSolution} during planning. * Used to remember the state of a good {@link PlanningSolution} so it can be recalled at a later time * when the original {@link PlanningSolution} is already modified. * Also used in population based heuristics to increase or repopulate the population. * <p> * Planning cloning is hard: avoid doing it yourself. * <p> * An implementing class must be thread-safe after initialization * on account of partitioned search using the same cloner on multiple part threads. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public interface SolutionCloner<Solution_> { /** * Does a planning clone. The returned {@link PlanningSolution} clone must fulfill these requirements: * <ul> * <li>The clone must represent the same planning problem. * Usually it reuses the same instances of the problem facts and problem fact collections as the {@code original}. * </li> * <li>The clone must have the same (equal) score as the {@code original}. * </li> * <li>The clone must use different, cloned instances of the entities and entity collections. * If a cloned entity changes, the original must remain unchanged. * If an entity is added or removed in a cloned {@link PlanningSolution}, * the original {@link PlanningSolution} must remain unchanged.</li> * </ul> * Note that a class might support more than 1 clone method: planning clone is just one of them. * <p> * This method is thread-safe. * * @param original never null, the original {@link PlanningSolution} * @return never null, the cloned {@link PlanningSolution} */ Solution_ cloneSolution(Solution_ original); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/valuerange/CountableValueRange.java
package ai.timefold.solver.core.api.domain.valuerange; import java.util.Iterator; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; /** * A {@link ValueRange} that is ending. Therefore, it has a discrete (as in non-continuous) range. * * @see ValueRangeFactory * @see ValueRange */ public interface CountableValueRange<T> extends ValueRange<T> { /** * Used by uniform random selection in a composite CountableValueRange, * or one which includes nulls. * * @return the exact number of elements generated by this {@link CountableValueRange}, always {@code >= 0} */ long getSize(); /** * Used by uniform random selection in a composite CountableValueRange, * or one which includes nulls. * * @param index always {@code <} {@link #getSize()} * @return sometimes null (if {@link PlanningVariable#allowsUnassigned()} is true) */ T get(long index); /** * Select the elements in original (natural) order. * * @return never null */ Iterator<T> createOriginalIterator(); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/valuerange/ValueRange.java
package ai.timefold.solver.core.api.domain.valuerange; 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.api.domain.variable.PlanningVariable; /** * A ValueRange is a set of a values for a {@link PlanningVariable}. * These values might be stored in memory as a {@link Collection} (usually a {@link List} or {@link Set}), * but if the values are numbers, they can also be stored in memory by their bounds * to use less memory and provide more opportunities. * <p> * ValueRange is stateful. * Prefer using {@link CountableValueRange} (which extends this interface) whenever possible. * Implementations must be immutable. * * @see ValueRangeFactory * @see CountableValueRange */ public interface ValueRange<T> { /** * In a {@link CountableValueRange}, this must be consistent with {@link CountableValueRange#getSize()}. * * @return true if the range is empty */ boolean isEmpty(); /** * @param value sometimes null * @return true if the ValueRange contains that value */ boolean contains(T value); /** * Select in random order, but without shuffling the elements. * Each element might be selected multiple times. * Scales well because it does not require caching. * * @param workingRandom never null, the {@link Random} to use when any random number is needed, * so runs are reproducible. * @return never null */ Iterator<T> createRandomIterator(Random workingRandom); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/valuerange/ValueRangeFactory.java
package ai.timefold.solver.core.api.domain.valuerange; import java.math.BigDecimal; import java.math.BigInteger; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.temporal.Temporal; import java.time.temporal.TemporalUnit; import ai.timefold.solver.core.impl.domain.valuerange.buildin.bigdecimal.BigDecimalValueRange; import ai.timefold.solver.core.impl.domain.valuerange.buildin.biginteger.BigIntegerValueRange; import ai.timefold.solver.core.impl.domain.valuerange.buildin.primboolean.BooleanValueRange; import ai.timefold.solver.core.impl.domain.valuerange.buildin.primdouble.DoubleValueRange; import ai.timefold.solver.core.impl.domain.valuerange.buildin.primint.IntValueRange; import ai.timefold.solver.core.impl.domain.valuerange.buildin.primlong.LongValueRange; import ai.timefold.solver.core.impl.domain.valuerange.buildin.temporal.TemporalValueRange; /** * Factory for {@link ValueRange}. */ public final class ValueRangeFactory { /** * Build a {@link CountableValueRange} of both {@code boolean} values. * * @return never null */ public static CountableValueRange<Boolean> createBooleanValueRange() { return new BooleanValueRange(); } /** * Build a {@link CountableValueRange} of all {@code int} values between 2 bounds. * * @param from inclusive minimum * @param to exclusive maximum, {@code >= from} * @return never null */ public static CountableValueRange<Integer> createIntValueRange(int from, int to) { return new IntValueRange(from, to); } /** * Build a {@link CountableValueRange} of a subset of {@code int} values between 2 bounds. * * @param from inclusive minimum * @param to exclusive maximum, {@code >= from} * @param incrementUnit {@code > 0} * @return never null */ public static CountableValueRange<Integer> createIntValueRange(int from, int to, int incrementUnit) { return new IntValueRange(from, to, incrementUnit); } /** * Build a {@link CountableValueRange} of all {@code long} values between 2 bounds. * * @param from inclusive minimum * @param to exclusive maximum, {@code >= from} * @return never null */ public static CountableValueRange<Long> createLongValueRange(long from, long to) { return new LongValueRange(from, to); } /** * Build a {@link CountableValueRange} of a subset of {@code long} values between 2 bounds. * * @param from inclusive minimum * @param to exclusive maximum, {@code >= from} * @param incrementUnit {@code > 0} * @return never null */ public static CountableValueRange<Long> createLongValueRange(long from, long to, long incrementUnit) { return new LongValueRange(from, to, incrementUnit); } /** * Build an uncountable {@link ValueRange} of all {@code double} values between 2 bounds. * * @param from inclusive minimum * @param to exclusive maximum, {@code >= from} * @return never null * @deprecated Prefer {@link #createBigDecimalValueRange(BigDecimal, BigDecimal)}. */ @Deprecated(forRemoval = true, since = "1.1.0") public static ValueRange<Double> createDoubleValueRange(double from, double to) { return new DoubleValueRange(from, to); } /** * Build a {@link CountableValueRange} of all {@link BigInteger} values between 2 bounds. * * @param from inclusive minimum * @param to exclusive maximum, {@code >= from} * @return never null */ public static CountableValueRange<BigInteger> createBigIntegerValueRange(BigInteger from, BigInteger to) { return new BigIntegerValueRange(from, to); } /** * Build a {@link CountableValueRange} of a subset of {@link BigInteger} values between 2 bounds. * * @param from inclusive minimum * @param to exclusive maximum, {@code >= from} * @param incrementUnit {@code > 0} * @return never null */ public static CountableValueRange<BigInteger> createBigIntegerValueRange(BigInteger from, BigInteger to, BigInteger incrementUnit) { return new BigIntegerValueRange(from, to, incrementUnit); } /** * Build a {@link CountableValueRange} of all {@link BigDecimal} values (of a specific scale) between 2 bounds. * All parameters must have the same {@link BigDecimal#scale()}. * * @param from inclusive minimum * @param to exclusive maximum, {@code >= from} * @return never null */ public static CountableValueRange<BigDecimal> createBigDecimalValueRange(BigDecimal from, BigDecimal to) { return new BigDecimalValueRange(from, to); } /** * Build a {@link CountableValueRange} of a subset of {@link BigDecimal} values (of a specific scale) between 2 bounds. * All parameters must have the same {@link BigDecimal#scale()}. * * @param from inclusive minimum * @param to exclusive maximum, {@code >= from} * @param incrementUnit {@code > 0} * @return never null */ public static CountableValueRange<BigDecimal> createBigDecimalValueRange(BigDecimal from, BigDecimal to, BigDecimal incrementUnit) { return new BigDecimalValueRange(from, to, incrementUnit); } /** * Build a {@link CountableValueRange} of a subset of {@link LocalDate} values between 2 bounds. * <p> * Facade for {@link #createTemporalValueRange(Temporal, Temporal, long, TemporalUnit)}. * * @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 LocalDate#isSupported(TemporalUnit) supported} */ public static CountableValueRange<LocalDate> createLocalDateValueRange( LocalDate from, LocalDate to, long incrementUnitAmount, TemporalUnit incrementUnitType) { return createTemporalValueRange(from, to, incrementUnitAmount, incrementUnitType); } /** * Build a {@link CountableValueRange} of a subset of {@link LocalTime} values between 2 bounds. * <p> * Facade for {@link #createTemporalValueRange(Temporal, Temporal, long, TemporalUnit)}. * * @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 LocalTime#isSupported(TemporalUnit) supported} */ public static CountableValueRange<LocalTime> createLocalTimeValueRange( LocalTime from, LocalTime to, long incrementUnitAmount, TemporalUnit incrementUnitType) { return createTemporalValueRange(from, to, incrementUnitAmount, incrementUnitType); } /** * Build a {@link CountableValueRange} of a subset of {@link LocalDateTime} values between 2 bounds. * <p> * Facade for {@link #createTemporalValueRange(Temporal, Temporal, long, TemporalUnit)}. * * @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 LocalDateTime#isSupported(TemporalUnit) supported} */ public static CountableValueRange<LocalDateTime> createLocalDateTimeValueRange( LocalDateTime from, LocalDateTime to, long incrementUnitAmount, TemporalUnit incrementUnitType) { return createTemporalValueRange(from, to, incrementUnitAmount, incrementUnitType); } /** * Build a {@link CountableValueRange} of a subset of {@link Temporal} values (such as {@link LocalDate} or * {@link LocalDateTime}) between 2 bounds. * All parameters must have the same {@link TemporalUnit}. * * @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 static <Temporal_ extends Temporal & Comparable<? super Temporal_>> CountableValueRange<Temporal_> createTemporalValueRange(Temporal_ from, Temporal_ to, long incrementUnitAmount, TemporalUnit incrementUnitType) { return new TemporalValueRange<>(from, to, incrementUnitAmount, incrementUnitType); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/valuerange/ValueRangeProvider.java
package ai.timefold.solver.core.api.domain.valuerange; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.Collection; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import ai.timefold.solver.core.api.solver.SolverFactory; /** * Provides the planning values that can be used for a {@link PlanningVariable}. * <p> * This is specified on a getter of a java bean property (or directly on a field) * which returns a {@link Collection} or {@link ValueRange}. * A {@link Collection} is implicitly converted to a {@link ValueRange}. */ @Target({ METHOD, FIELD }) @Retention(RUNTIME) public @interface ValueRangeProvider { /** * Used by {@link PlanningVariable#valueRangeProviderRefs()} * to map a {@link PlanningVariable} to a {@link ValueRangeProvider}. * If not provided, an attempt will be made to find a matching {@link PlanningVariable} without a ref. * * @return if provided, must be unique across a {@link SolverFactory} */ String id() default ""; }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/variable/AbstractVariableListener.java
package ai.timefold.solver.core.api.domain.variable; import java.io.Closeable; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; /** * Common ancestor for specialized planning variable listeners. * <p> * <strong>Do not implement this interface directly.</strong> * Implement either {@link VariableListener} or {@link ListVariableListener}. * * @see VariableListener * @see ListVariableListener * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <Entity_> {@link PlanningEntity} on which the source variable is declared */ public interface AbstractVariableListener<Solution_, Entity_> extends Closeable { /** * @param scoreDirector never null * @param entity never null */ void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Entity_ entity); /** * @param scoreDirector never null * @param entity never null */ void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Entity_ entity); /** * @param scoreDirector never null * @param entity never null */ void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Entity_ entity); /** * @param scoreDirector never null * @param entity never null */ void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Entity_ entity); /** * Called when the entire working solution changes. In this event, the other before..()/after...() methods will not * be called. * At this point, implementations should clear state, if any. * * @param scoreDirector never null */ default void resetWorkingSolution(ScoreDirector<Solution_> scoreDirector) { // No need to do anything for stateless implementations. } /** * Called before this {@link AbstractVariableListener} is thrown away and not used anymore. */ @Override default void close() { // No need to do anything for stateless implementations. } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/variable/ListVariableListener.java
package ai.timefold.solver.core.api.domain.variable; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; /** * A listener sourced on a {@link PlanningListVariable}. * <p> * Changes shadow variables when a genuine source list variable changes. * <p> * Important: it must only change the shadow variable(s) for which it's configured! * It should never change a genuine variable or a problem fact. * It can change its shadow variable(s) on multiple entity instances * (for example: an arrivalTime change affects all trailing entities too). * <p> * It is recommended to keep implementations stateless. * If state must be implemented, implementations may need to override the default methods * ({@link #resetWorkingSolution(ScoreDirector)}, {@link #close()}). * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <Entity_> {@link PlanningEntity} on which the source variable is declared * @param <Element_> the type of elements of the source list variable */ public interface ListVariableListener<Solution_, Entity_, Element_> extends AbstractVariableListener<Solution_, Entity_> { /** * The listener must unset all shadow variables it is responsible for when an element is unassigned from the source list * variable. For example, a {@code Task}'s {@code startTime} shadow variable must be reset to {@code null} after a task * is unassigned from {@code Employee.tasks} when the move that assigned it there is undone during Construction Heuristic * phase. * * @param scoreDirector score director * @param element the unassigned element */ void afterListVariableElementUnassigned(ScoreDirector<Solution_> scoreDirector, Element_ element); /** * Tells the listener that some elements within the range starting at {@code fromIndex} (inclusive) and ending at * {@code toIndex} (exclusive) will change. * Be aware that the {@link #afterListVariableChanged} call after the change is done often has a different * {@code fromIndex} and {@code toIndex} because the number of elements in the list variable can change. * * <p> * The list variable change includes: * <ul> * <li>Changing position (index) of one or more elements.</li> * <li>Removing one or more elements from the list variable.</li> * <li>Adding one or more elements to the list variable.</li> * <li>Any mix of the above.</li> * </ul> * * <p> * The range has the following properties: * <ol> * <li>{@code fromIndex} is greater than or equal to 0; {@code toIndex} is less than or equal to the list variable * size.</li> * <li>{@code toIndex} is greater than or equal to {@code fromIndex}.</li> * <li>The range contains all elements that are going to be changed.</li> * <li>The range may contain elements that are not going to be changed.</li> * <li>The range may be empty ({@code fromIndex} equals {@code toIndex}) if none of the existing list variable elements * are going to be changed.</li> * </ol> * * @param scoreDirector score director * @param entity entity with the changed list variable * @param fromIndex low endpoint (inclusive) of the changed range * @param toIndex high endpoint (exclusive) of the changed range */ void beforeListVariableChanged(ScoreDirector<Solution_> scoreDirector, Entity_ entity, int fromIndex, int toIndex); /** * Tells the listener that some elements within the range starting at {@code fromIndex} (inclusive) and ending at * {@code toIndex} (exclusive) changed. * <p> * The list variable change includes: * <ul> * <li>Changing position (index) of one or more elements.</li> * <li>Removing one or more elements from the list variable.</li> * <li>Adding one or more elements to the list variable.</li> * <li>Any mix of the above.</li> * </ul> * * <p> * The range has the following properties: * <ol> * <li>{@code fromIndex} is greater than or equal to 0; {@code toIndex} is less than or equal to the list variable * size.</li> * <li>{@code toIndex} is greater than or equal to {@code fromIndex}.</li> * <li>The range contains all elements that have changed.</li> * <li>The range may contain elements that have not changed.</li> * <li>The range may be empty ({@code fromIndex} equals {@code toIndex}) if none of the existing list variable elements * have changed.</li> * </ol> * * @param scoreDirector score director * @param entity entity with the changed list variable * @param fromIndex low endpoint (inclusive) of the changed range * @param toIndex high endpoint (exclusive) of the changed range */ void afterListVariableChanged(ScoreDirector<Solution_> scoreDirector, Entity_ entity, int fromIndex, int toIndex); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/variable/PlanningListVariable.java
package ai.timefold.solver.core.api.domain.variable; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; 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; /** * Specifies that a bean property (or a field) can be changed and should be optimized by the optimization algorithms. * It is specified on a getter of a java bean property (or directly on a field) of a {@link PlanningEntity} class. * The type of the {@link PlanningListVariable} annotated bean property (or a field) must be {@link List}. * * <h2>List variable</h2> * <p> * A planning entity's property annotated with {@code @PlanningListVariable} is referred to as a <strong>list variable</strong>. * The way solver optimizes a list variable is by adding, removing, or changing order of elements in the {@code List} object * held by the list variable. * * <h2>Disjoint lists</h2> * <p> * Furthermore, the current implementation works under the assumption that the list variables of all entity instances * are "disjoint lists": * <ul> * <li><strong>List</strong> means that the order of elements inside a list planning variable is significant.</li> * <li><strong>Disjoint</strong> means that any given pair of entities have no common elements in their list variables. * In other words, each element from the list variable's value range appears in exactly one entity's list variable.</li> * </ul> * * <p> * This makes sense for common use cases, for example the Vehicle Routing Problem or Task Assigning. In both cases * the <em>order</em> in which customers are visited and tasks are being worked on matters. Also, each customer * must be visited <em>once</em> and each task must be completed by <em>exactly one</em> employee. * * <p> * <strong>Overconstrained planning is currently not supported for list variables.</strong> * * @see PlanningPin * @see PlanningPinToIndex */ @Target({ METHOD, FIELD }) @Retention(RUNTIME) public @interface PlanningListVariable { /** * If set to false (default), all elements must be assigned to some list. * If set to true, elements may be left unassigned. * * @see PlanningVariable#allowsUnassigned() Basic planning value equivalent. */ boolean allowsUnassignedValues() default false; String[] valueRangeProviderRefs() default {}; // TODO value comparison: https://issues.redhat.com/browse/PLANNER-2542 }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/variable/ShadowVariable.java
package ai.timefold.solver.core.api.domain.variable; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.Target; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.domain.variable.ShadowVariable.List; /** * Specifies that a bean property (or a field) is a custom shadow variable of 1 or more source variables. * The source variable may be a genuine {@link PlanningVariable}, {@link PlanningListVariable}, or another shadow variable. * <p> * It is specified on a getter of a java bean property (or a field) of a {@link PlanningEntity} class. */ @Target({ METHOD, FIELD }) @Retention(RUNTIME) @Repeatable(List.class) public @interface ShadowVariable { /** * A {@link VariableListener} or {@link ListVariableListener} gets notified after a source planning variable has changed. * That listener changes the shadow variable (often recursively on multiple planning entities) accordingly. * Those shadow variables should make the score calculation more natural to write. * <p> * For example: VRP with time windows uses a {@link VariableListener} to update the arrival times * of all the trailing entities when an entity is changed. * * @return a variable listener class */ Class<? extends AbstractVariableListener> variableListenerClass(); /** * The {@link PlanningEntity} class of the source variable. * <p> * Specified if the source variable is on a different {@link Class} than the class that uses this referencing annotation. * * @return {@link NullEntityClass} when the attribute is omitted (workaround for annotation limitation). * Defaults to the same {@link Class} as the one that uses this annotation. */ Class<?> sourceEntityClass() default NullEntityClass.class; /** * The source variable name. * * @return never null, a genuine or shadow variable name */ String sourceVariableName(); /** * Defines several {@link ShadowVariable} annotations on the same element. */ @Target({ METHOD, FIELD }) @Retention(RUNTIME) @interface List { ShadowVariable[] value(); } /** Workaround for annotation limitation in {@link #sourceEntityClass()}. */ interface NullEntityClass { } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/domain/variable/VariableListener.java
package ai.timefold.solver.core.api.domain.variable; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; /** * A listener sourced on a basic {@link PlanningVariable}. * <p> * Changes shadow variables when a source basic planning variable changes. * The source variable can be either a genuine or a shadow variable. * <p> * Important: it must only change the shadow variable(s) for which it's configured! * It should never change a genuine variable or a problem fact. * It can change its shadow variable(s) on multiple entity instances * (for example: an arrivalTime change affects all trailing entities too). * <p> * It is recommended to keep implementations stateless. * If state must be implemented, implementations may need to override the default methods * ({@link #resetWorkingSolution(ScoreDirector)}, {@link #close()}). * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <Entity_> {@link PlanningEntity} on which the source variable is declared */ public interface VariableListener<Solution_, Entity_> extends AbstractVariableListener<Solution_, Entity_> { /** * When set to {@code true}, this has a performance loss. * When set to {@code false}, it's easier to make the listener implementation correct and fast. * * @return true to guarantee that each of the before/after methods is only called once per entity instance * per operation type (add, change or remove). */ default boolean requiresUniqueEntityEvents() { return false; } /** * @param scoreDirector never null * @param entity never null */ void beforeVariableChanged(ScoreDirector<Solution_> scoreDirector, Entity_ entity); /** * @param scoreDirector never null * @param entity never null */ void afterVariableChanged(ScoreDirector<Solution_> scoreDirector, Entity_ entity); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/function/PentaPredicate.java
package ai.timefold.solver.core.api.function; import java.util.Objects; import java.util.function.Predicate; /** * Represents a predicate (boolean-valued function) of five arguments. * This is the five-arity specialization of {@link Predicate}. * * <p> * This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #test(Object, Object, Object, Object, Object)}. * * @param <A> the type of the first argument to the predicate * @param <B> the type of the second argument the predicate * @param <C> the type of the third argument the predicate * @param <D> the type of the fourth argument the predicate * @param <E> the type of the fifth argument the predicate * * @see Predicate */ @FunctionalInterface public interface PentaPredicate<A, B, C, D, E> { /** * Evaluates this predicate on the given arguments. * * @param a the first input argument * @param b the second input argument * @param c the third input argument * @param d the fourth input argument * @param e the fifth input argument * @return {@code true} if the input arguments match the predicate, * otherwise {@code false} */ boolean test(A a, B b, C c, D d, E e); /** * Returns a composed predicate that represents a short-circuiting logical * AND of this predicate and another. When evaluating the composed * predicate, if this predicate is {@code false}, then the {@code other} * predicate is not evaluated. * * <p> * Any exceptions thrown during evaluation of either predicate are relayed * to the caller; if evaluation of this predicate throws an exception, the * {@code other} predicate will not be evaluated. * * @param other a predicate that will be logically-ANDed with this predicate * @return a composed predicate that represents the short-circuiting logical * AND of this predicate and the {@code other} predicate * @throws NullPointerException if other is null */ default PentaPredicate<A, B, C, D, E> and( PentaPredicate<? super A, ? super B, ? super C, ? super D, ? super E> other) { Objects.requireNonNull(other); return (A a, B b, C c, D d, E e) -> test(a, b, c, d, e) && other.test(a, b, c, d, e); } /** * Returns a predicate that represents the logical negation of this * predicate. * * @return a predicate that represents the logical negation of this * predicate */ default PentaPredicate<A, B, C, D, E> negate() { return (A a, B b, C c, D d, E e) -> !test(a, b, c, d, e); } /** * Returns a composed predicate that represents a short-circuiting logical * OR of this predicate and another. When evaluating the composed * predicate, if this predicate is {@code true}, then the {@code other} * predicate is not evaluated. * * <p> * Any exceptions thrown during evaluation of either predicate are relayed * to the caller; if evaluation of this predicate throws an exception, the * {@code other} predicate will not be evaluated. * * @param other a predicate that will be logically-ORed with this predicate * @return a composed predicate that represents the short-circuiting logical * OR of this predicate and the {@code other} predicate * @throws NullPointerException if other is null */ default PentaPredicate<A, B, C, D, E> or( PentaPredicate<? super A, ? super B, ? super C, ? super D, ? super E> other) { Objects.requireNonNull(other); return (A a, B b, C c, D d, E e) -> test(a, b, c, d, e) || other.test(a, b, c, d, e); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/function/QuadPredicate.java
package ai.timefold.solver.core.api.function; import java.util.Objects; import java.util.function.Predicate; /** * Represents a predicate (boolean-valued function) of four arguments. * This is the four-arity specialization of {@link Predicate}. * * <p> * This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #test(Object, Object, Object, Object)}. * * @param <A> the type of the first argument to the predicate * @param <B> the type of the second argument the predicate * @param <C> the type of the third argument the predicate * @param <D> the type of the fourth argument the predicate * * @see Predicate */ @FunctionalInterface public interface QuadPredicate<A, B, C, D> { /** * Evaluates this predicate on the given arguments. * * @param a the first input argument * @param b the second input argument * @param c the third input argument * @param d the fourth input argument * @return {@code true} if the input arguments match the predicate, * otherwise {@code false} */ boolean test(A a, B b, C c, D d); /** * Returns a composed predicate that represents a short-circuiting logical * AND of this predicate and another. When evaluating the composed * predicate, if this predicate is {@code false}, then the {@code other} * predicate is not evaluated. * * <p> * Any exceptions thrown during evaluation of either predicate are relayed * to the caller; if evaluation of this predicate throws an exception, the * {@code other} predicate will not be evaluated. * * @param other a predicate that will be logically-ANDed with this predicate * @return a composed predicate that represents the short-circuiting logical * AND of this predicate and the {@code other} predicate * @throws NullPointerException if other is null */ default QuadPredicate<A, B, C, D> and(QuadPredicate<? super A, ? super B, ? super C, ? super D> other) { Objects.requireNonNull(other); return (A a, B b, C c, D d) -> test(a, b, c, d) && other.test(a, b, c, d); } /** * Returns a predicate that represents the logical negation of this * predicate. * * @return a predicate that represents the logical negation of this * predicate */ default QuadPredicate<A, B, C, D> negate() { return (A a, B b, C c, D d) -> !test(a, b, c, d); } /** * Returns a composed predicate that represents a short-circuiting logical * OR of this predicate and another. When evaluating the composed * predicate, if this predicate is {@code true}, then the {@code other} * predicate is not evaluated. * * <p> * Any exceptions thrown during evaluation of either predicate are relayed * to the caller; if evaluation of this predicate throws an exception, the * {@code other} predicate will not be evaluated. * * @param other a predicate that will be logically-ORed with this predicate * @return a composed predicate that represents the short-circuiting logical * OR of this predicate and the {@code other} predicate * @throws NullPointerException if other is null */ default QuadPredicate<A, B, C, D> or(QuadPredicate<? super A, ? super B, ? super C, ? super D> other) { Objects.requireNonNull(other); return (A a, B b, C c, D d) -> test(a, b, c, d) || other.test(a, b, c, d); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/function/TriConsumer.java
package ai.timefold.solver.core.api.function; import java.util.Objects; import java.util.function.Consumer; import java.util.function.Function; /** * Represents a function that accepts three arguments and returns no result. * This is the three-arity specialization of {@link Consumer}. * * <p> * This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #accept(Object, Object, Object)}. * * @param <A> the type of the first argument to the function * @param <B> the type of the second argument to the function * @param <C> the type of the third argument to the function * * @see Function */ @FunctionalInterface public interface TriConsumer<A, B, C> { /** * Performs this operation on the given arguments. * * @param a the first function argument * @param b the second function argument * @param c the third function argument */ void accept(A a, B b, C c); default TriConsumer<A, B, C> andThen(TriConsumer<? super A, ? super B, ? super C> after) { Objects.requireNonNull(after); return (a, b, c) -> { accept(a, b, c); after.accept(a, b, c); }; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/function/TriPredicate.java
package ai.timefold.solver.core.api.function; import java.util.Objects; import java.util.function.Predicate; /** * Represents a predicate (boolean-valued function) of three arguments. * This is the three-arity specialization of {@link Predicate}. * * <p> * This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #test(Object, Object, Object)}. * * @param <A> the type of the first argument to the predicate * @param <B> the type of the second argument the predicate * @param <C> the type of the third argument the predicate * * @see Predicate */ @FunctionalInterface public interface TriPredicate<A, B, C> { /** * Evaluates this predicate on the given arguments. * * @param a the first input argument * @param b the second input argument * @param c the third input argument * @return {@code true} if the input arguments match the predicate, * otherwise {@code false} */ boolean test(A a, B b, C c); /** * Returns a composed predicate that represents a short-circuiting logical * AND of this predicate and another. When evaluating the composed * predicate, if this predicate is {@code false}, then the {@code other} * predicate is not evaluated. * * <p> * Any exceptions thrown during evaluation of either predicate are relayed * to the caller; if evaluation of this predicate throws an exception, the * {@code other} predicate will not be evaluated. * * @param other a predicate that will be logically-ANDed with this predicate * @return a composed predicate that represents the short-circuiting logical * AND of this predicate and the {@code other} predicate * @throws NullPointerException if other is null */ default TriPredicate<A, B, C> and(TriPredicate<? super A, ? super B, ? super C> other) { Objects.requireNonNull(other); return (A a, B b, C c) -> test(a, b, c) && other.test(a, b, c); } /** * Returns a predicate that represents the logical negation of this * predicate. * * @return a predicate that represents the logical negation of this * predicate */ default TriPredicate<A, B, C> negate() { return (A a, B b, C c) -> !test(a, b, c); } /** * Returns a composed predicate that represents a short-circuiting logical * OR of this predicate and another. When evaluating the composed * predicate, if this predicate is {@code true}, then the {@code other} * predicate is not evaluated. * * <p> * Any exceptions thrown during evaluation of either predicate are relayed * to the caller; if evaluation of this predicate throws an exception, the * {@code other} predicate will not be evaluated. * * @param other a predicate that will be logically-ORed with this predicate * @return a composed predicate that represents the short-circuiting logical * OR of this predicate and the {@code other} predicate * @throws NullPointerException if other is null */ default TriPredicate<A, B, C> or(TriPredicate<? super A, ? super B, ? super C> other) { Objects.requireNonNull(other); return (A a, B b, C c) -> test(a, b, c) || other.test(a, b, c); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/AbstractBendableScore.java
package ai.timefold.solver.core.api.score; import java.util.function.Predicate; import ai.timefold.solver.core.impl.score.ScoreUtil; /** * Abstract superclass for bendable {@link Score} types. * <p> * Subclasses must be immutable. * * @deprecated Implement {@link IBendableScore} instead. */ @Deprecated(forRemoval = true) public abstract class AbstractBendableScore<Score_ extends AbstractBendableScore<Score_>> extends AbstractScore<Score_> implements IBendableScore<Score_> { protected static final String HARD_LABEL = ScoreUtil.HARD_LABEL; protected static final String SOFT_LABEL = ScoreUtil.SOFT_LABEL; protected static final String[] LEVEL_SUFFIXES = ScoreUtil.LEVEL_SUFFIXES; protected static String[][] parseBendableScoreTokens(Class<? extends AbstractBendableScore<?>> scoreClass, String scoreString) { return ScoreUtil.parseBendableScoreTokens(scoreClass, scoreString); } /** * @param initScore see {@link Score#initScore()} */ protected AbstractBendableScore(int initScore) { super(initScore); } protected String buildBendableShortString(Predicate<Number> notZero) { return ScoreUtil.buildBendableShortString(this, notZero); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/AbstractScore.java
package ai.timefold.solver.core.api.score; import java.io.Serializable; import java.math.BigDecimal; import java.util.function.Predicate; import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; import ai.timefold.solver.core.impl.score.ScoreUtil; /** * Abstract superclass for {@link Score}. * <p> * Subclasses must be immutable. * * @param <Score_> the actual score type * @see Score * @see HardSoftScore * @deprecated Implement {@link Score} instead. */ @Deprecated(forRemoval = true) public abstract class AbstractScore<Score_ extends AbstractScore<Score_>> implements Score<Score_>, Serializable { protected static final String INIT_LABEL = ScoreUtil.INIT_LABEL; protected static String[] parseScoreTokens(Class<? extends AbstractScore<?>> scoreClass, String scoreString, String... levelSuffixes) { return ScoreUtil.parseScoreTokens(scoreClass, scoreString, levelSuffixes); } protected static int parseInitScore(Class<? extends AbstractScore<?>> scoreClass, String scoreString, String initScoreString) { return ScoreUtil.parseInitScore(scoreClass, scoreString, initScoreString); } protected static int parseLevelAsInt(Class<? extends AbstractScore<?>> scoreClass, String scoreString, String levelString) { return ScoreUtil.parseLevelAsInt(scoreClass, scoreString, levelString); } protected static long parseLevelAsLong(Class<? extends AbstractScore<?>> scoreClass, String scoreString, String levelString) { return ScoreUtil.parseLevelAsLong(scoreClass, scoreString, levelString); } protected static BigDecimal parseLevelAsBigDecimal(Class<? extends AbstractScore<?>> scoreClass, String scoreString, String levelString) { return ScoreUtil.parseLevelAsBigDecimal(scoreClass, scoreString, levelString); } protected static String buildScorePattern(boolean bendable, String... levelSuffixes) { return ScoreUtil.buildScorePattern(bendable, levelSuffixes); } // ************************************************************************ // Fields // ************************************************************************ protected final int initScore; /** * @param initScore see {@link Score#initScore()} */ protected AbstractScore(int initScore) { this.initScore = initScore; // The initScore can be positive during statistical calculations. } @Override public int initScore() { return initScore; } // ************************************************************************ // Worker methods // ************************************************************************ protected String getInitPrefix() { return ScoreUtil.getInitPrefix(initScore); } protected String buildShortString(Predicate<Number> notZero, String... levelLabels) { return ScoreUtil.buildShortString(this, notZero, levelLabels); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/IBendableScore.java
package ai.timefold.solver.core.api.score; import java.io.Serializable; import ai.timefold.solver.core.api.score.buildin.bendable.BendableScore; /** * Bendable score is a {@link Score} whose {@link #hardLevelsSize()} and {@link #softLevelsSize()} * are only known at runtime. * * <p> * Interfaces in Timefold are usually not prefixed with "I". * However, the conflict in name with its implementation ({@link BendableScore}) made this necessary. * All the other options were considered worse, some even harmful. * This is a minor issue, as users will access the implementation and not the interface anyway. * * @param <Score_> the actual score type to allow addition, subtraction and other arithmetic */ public interface IBendableScore<Score_ extends IBendableScore<Score_>> extends Score<Score_>, Serializable { /** * The sum of this and {@link #softLevelsSize()} equals {@link #levelsSize()}. * * @return {@code >= 0} and {@code <} {@link #levelsSize()} */ int hardLevelsSize(); /** * As defined by {@link #hardLevelsSize()}. * * @deprecated Use {@link #hardLevelsSize()} instead. */ @Deprecated(forRemoval = true) default int getHardLevelsSize() { return hardLevelsSize(); } /** * The sum of {@link #hardLevelsSize()} and this equals {@link #levelsSize()}. * * @return {@code >= 0} and {@code <} {@link #levelsSize()} */ int softLevelsSize(); /** * As defined by {@link #softLevelsSize()}. * * @deprecated Use {@link #softLevelsSize()} instead. */ @Deprecated(forRemoval = true) default int getSoftLevelsSize() { return softLevelsSize(); } /** * @return {@link #hardLevelsSize()} + {@link #softLevelsSize()} */ default int levelsSize() { return hardLevelsSize() + softLevelsSize(); } /** * As defined by {@link #levelsSize()}. * * @deprecated Use {@link #levelsSize()} instead. */ @Deprecated(forRemoval = true) default int getLevelsSize() { return levelsSize(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/Score.java
package ai.timefold.solver.core.api.score; import java.io.Serializable; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; 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; /** * A Score is result of the score function (AKA fitness function) on a single possible solution. * * <ul> * <li>Implementations must be immutable, * preferably a Java record or even a primitive record, * if the target JDK permits that.</li> * <li>Implementations must override {@link #initScore()}, * or else an endless loop occurs.</li> * <li>Implementations are allowed to optionally implement Pareto comparison * and therefore slightly violate the transitive requirement of {@link Comparable#compareTo(Object)}.</li> * </ul> * * @param <Score_> the actual score type to allow addition, subtraction and other arithmetic * @see HardSoftScore */ public interface Score<Score_ extends Score<Score_>> extends Comparable<Score_>, Serializable { /** * The init score is the negative of the number of uninitialized genuine planning variables. * If it's 0 (which it usually is), the {@link PlanningSolution} is fully initialized * and the score's {@link Object#toString()} does not mention it. * <p> * During {@link #compareTo(Object)}, it's even more important than the hard score: * if you don't want this behaviour, read about overconstrained planning in the reference manual. * * @return higher is better, always negative (except in statistical calculations), 0 if all planning variables are * initialized */ default int initScore() { // TODO remove default implementation in 2.0; exists only for backwards compatibility return getInitScore(); } /** * As defined by {@link #initScore()}. * * @deprecated Use {@link #initScore()} instead. */ @Deprecated(forRemoval = true) default int getInitScore() { return initScore(); } /** * For example {@code 0hard/-8soft} with {@code -7} returns {@code -7init/0hard/-8soft}. * * @param newInitScore always negative (except in statistical calculations), 0 if all planning variables are initialized * @return equals score except that {@link #initScore()} is set to {@code newInitScore} */ Score_ withInitScore(int newInitScore); /** * Returns a Score whose value is (this + addend). * * @param addend value to be added to this Score * @return this + addend */ Score_ add(Score_ addend); /** * Returns a Score whose value is (this - subtrahend). * * @param subtrahend value to be subtracted from this Score * @return this - subtrahend, rounded as necessary */ Score_ subtract(Score_ subtrahend); /** * Returns a Score whose value is (this * multiplicand). * When rounding is needed, it should be floored (as defined by {@link Math#floor(double)}). * <p> * If the implementation has a scale/precision, then the unspecified scale/precision of the double multiplicand * should have no impact on the returned scale/precision. * * @param multiplicand value to be multiplied by this Score. * @return this * multiplicand */ Score_ multiply(double multiplicand); /** * Returns a Score whose value is (this / divisor). * When rounding is needed, it should be floored (as defined by {@link Math#floor(double)}). * <p> * If the implementation has a scale/precision, then the unspecified scale/precision of the double divisor * should have no impact on the returned scale/precision. * * @param divisor value by which this Score is to be divided * @return this / divisor */ Score_ divide(double divisor); /** * Returns a Score whose value is (this ^ exponent). * When rounding is needed, it should be floored (as defined by {@link Math#floor(double)}). * <p> * If the implementation has a scale/precision, then the unspecified scale/precision of the double exponent * should have no impact on the returned scale/precision. * * @param exponent value by which this Score is to be powered * @return this ^ exponent */ Score_ power(double exponent); /** * Returns a Score whose value is (- this). * * @return - this */ default Score_ negate() { Score_ zero = zero(); Score_ current = (Score_) this; if (zero.equals(current)) { return current; } return zero.subtract(current); } /** * Returns a Score whose value is the absolute value of the score, i.e. |this|. * * @return never null */ Score_ abs(); /** * Returns a Score, all levels of which are zero. * * @return never null */ Score_ zero(); /** * * @return true when this {@link Object#equals(Object) is equal to} {@link #zero()}. */ default boolean isZero() { return this.equals(zero()); } /** * Returns an array of numbers representing the Score. Each number represents 1 score level. * A greater score level uses a lower array index than a lesser score level. * <p> * When rounding is needed, each rounding should be floored (as defined by {@link Math#floor(double)}). * The length of the returned array must be stable for a specific {@link Score} implementation. * <p> * For example: {@code -0hard/-7soft} returns {@code new int{-0, -7}} * <p> * The level numbers do not contain the {@link #initScore()}. * For example: {@code -3init/-0hard/-7soft} also returns {@code new int{-0, -7}} * * @return never null */ Number[] toLevelNumbers(); /** * As defined by {@link #toLevelNumbers()}, only returns double[] instead of Number[]. * * @return never null */ default double[] toLevelDoubles() { Number[] levelNumbers = toLevelNumbers(); double[] levelDoubles = new double[levelNumbers.length]; for (int i = 0; i < levelNumbers.length; i++) { levelDoubles[i] = levelNumbers[i].doubleValue(); } return levelDoubles; } /** * Checks if the {@link PlanningSolution} of this score was fully initialized when it was calculated. * * @return true if {@link #initScore()} is 0 */ default boolean isSolutionInitialized() { return initScore() >= 0; } /** * A {@link PlanningSolution} is feasible if it has no broken hard constraints * and {@link #isSolutionInitialized()} is true. * * Simple scores ({@link SimpleScore}, {@link SimpleLongScore}, {@link SimpleBigDecimalScore}) are always feasible, * if their {@link #initScore()} is 0. * * @return true if the hard score is 0 or higher and the {@link #initScore()} is 0. */ boolean isFeasible(); /** * Like {@link Object#toString()}, but trims score levels which have a zero weight. * For example {@literal 0hard/-258soft} returns {@literal -258soft}. * <p> * Do not use this format to persist information as text, use {@link Object#toString()} instead, * so it can be parsed reliably. * * @return never null */ String toShortString(); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/ScoreExplanation.java
package ai.timefold.solver.core.api.score; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty; import ai.timefold.solver.core.api.score.analysis.ScoreAnalysis; import ai.timefold.solver.core.api.score.calculator.ConstraintMatchAwareIncrementalScoreCalculator; import ai.timefold.solver.core.api.score.constraint.ConstraintMatch; import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal; import ai.timefold.solver.core.api.score.constraint.ConstraintRef; import ai.timefold.solver.core.api.score.constraint.Indictment; import ai.timefold.solver.core.api.score.stream.Constraint; import ai.timefold.solver.core.api.score.stream.ConstraintJustification; import ai.timefold.solver.core.api.score.stream.DefaultConstraintJustification; import ai.timefold.solver.core.api.solver.SolutionManager; /** * Build by {@link SolutionManager#explain(Object)} to hold {@link ConstraintMatchTotal}s and {@link Indictment}s * necessary to explain the quality of a particular {@link Score}. * <p> * For a simplified, faster and JSON-friendly alternative, see {@link ScoreAnalysis}. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <Score_> the actual score type */ public interface ScoreExplanation<Solution_, Score_ extends Score<Score_>> { /** * Retrieve the {@link PlanningSolution} that the score being explained comes from. * * @return never null */ Solution_ getSolution(); /** * Return the {@link Score} being explained. * If the specific {@link Score} type used by the {@link PlanningSolution} is required, * call {@link #getSolution()} and retrieve it from there. * * @return never null */ Score_ getScore(); /** * Returns a diagnostic text that explains the solution through the {@link ConstraintMatch} API to identify which * constraints or planning entities cause that score quality. * <p> * In case of an {@link Score#isFeasible() infeasible} solution, this can help diagnose the cause of that. * * <p> * Do not parse the return value, its format may change without warning. * Instead, to provide this information in a UI or a service, * use {@link ScoreExplanation#getConstraintMatchTotalMap()} and {@link ScoreExplanation#getIndictmentMap()} * and convert those into a domain-specific API. * * @return never null */ String getSummary(); /** * Explains the {@link Score} of {@link #getScore()} by splitting it up per {@link Constraint}. * <p> * The sum of {@link ConstraintMatchTotal#getScore()} equals {@link #getScore()}. * * @return never null, the key is the constraintId * (to create one, use {@link ConstraintRef#composeConstraintId(String, String)}). * @see #getIndictmentMap() */ Map<String, ConstraintMatchTotal<Score_>> getConstraintMatchTotalMap(); /** * Explains the {@link Score} of {@link #getScore()} for all constraints. * The return value of this method is determined by several factors: * * <ul> * <li> * With Constraint Streams, the user has an option to provide a custom justification mapping, * implementing {@link ConstraintJustification}. * If provided, every {@link ConstraintMatch} of such constraint will be associated with this custom justification class. * Every constraint not associated with a custom justification class * will be associated with {@link DefaultConstraintJustification}. * </li> * <li> * With {@link ConstraintMatchAwareIncrementalScoreCalculator}, * every {@link ConstraintMatch} will be associated with the justification class that the user created it with. * </li> * </ul> * * @return never null, all constraint matches * @see #getIndictmentMap() */ List<ConstraintJustification> getJustificationList(); /** * Explains the {@link Score} of {@link #getScore()} for all constraints * justified with a given {@link ConstraintJustification} type. * Otherwise, as defined by {@link #getJustificationList()}. * * @param constraintJustificationClass never null * @return never null, all constraint matches associated with the given justification class * @see #getIndictmentMap() */ default <ConstraintJustification_ extends ConstraintJustification> List<ConstraintJustification_> getJustificationList(Class<? extends ConstraintJustification_> constraintJustificationClass) { return getJustificationList() .stream() .filter(constraintJustification -> constraintJustificationClass .isAssignableFrom(constraintJustification.getClass())) .map(constraintJustification -> (ConstraintJustification_) constraintJustification) .collect(Collectors.toList()); } /** * Explains the impact of each planning entity or problem fact on the {@link Score}. * An {@link Indictment} is basically the inverse of a {@link ConstraintMatchTotal}: * it is a {@link Score} total for any of the {@link ConstraintMatch#getIndictedObjectList() indicted objects}. * <p> * The sum of {@link ConstraintMatchTotal#getScore()} differs from {@link #getScore()} * because each {@link ConstraintMatch#getScore()} is counted * for each of the {@link ConstraintMatch#getIndictedObjectList() indicted objects}. * * @return never null, the key is a {@link ProblemFactCollectionProperty problem fact} or a * {@link PlanningEntity planning entity} * @see #getConstraintMatchTotalMap() */ Map<Object, Indictment<Score_>> getIndictmentMap(); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/ScoreManager.java
package ai.timefold.solver.core.api.score; import static ai.timefold.solver.core.api.solver.SolutionUpdatePolicy.UPDATE_ALL; import java.util.UUID; import ai.timefold.solver.core.api.domain.solution.PlanningScore; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.calculator.EasyScoreCalculator; import ai.timefold.solver.core.api.score.constraint.ConstraintMatch; import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal; import ai.timefold.solver.core.api.score.constraint.Indictment; import ai.timefold.solver.core.api.solver.SolutionManager; import ai.timefold.solver.core.api.solver.SolutionUpdatePolicy; import ai.timefold.solver.core.api.solver.SolverFactory; import ai.timefold.solver.core.api.solver.SolverManager; import ai.timefold.solver.core.impl.score.DefaultScoreManager; /** * A stateless service to help calculate {@link Score}, {@link ConstraintMatchTotal}, {@link Indictment}, etc. * <p> * To create a ScoreManager, use {@link #create(SolverFactory)}. * <p> * These methods are thread-safe unless explicitly stated otherwise. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <Score_> the actual score type * @deprecated Use {@link SolutionManager} instead. */ @Deprecated(forRemoval = true) public interface ScoreManager<Solution_, Score_ extends Score<Score_>> { // ************************************************************************ // Static creation methods: SolverFactory // ************************************************************************ /** * Uses a {@link SolverFactory} to build a {@link ScoreManager}. * * @param solverFactory never null * @return never null * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <Score_> the actual score type */ static <Solution_, Score_ extends Score<Score_>> ScoreManager<Solution_, Score_> create( SolverFactory<Solution_> solverFactory) { return new DefaultScoreManager<>(SolutionManager.<Solution_, Score_> create(solverFactory)); } /** * Uses a {@link SolverManager} to build a {@link ScoreManager}. * * @param solverManager never null * @return never null * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <Score_> the actual score type * @param <ProblemId_> the ID type of a submitted problem, such as {@link Long} or {@link UUID} */ static <Solution_, Score_ extends Score<Score_>, ProblemId_> ScoreManager<Solution_, Score_> create( SolverManager<Solution_, ProblemId_> solverManager) { return new DefaultScoreManager<>(SolutionManager.<Solution_, Score_, ProblemId_> create(solverManager)); } // ************************************************************************ // Interface methods // ************************************************************************ /** * Calculates the {@link Score} of a {@link PlanningSolution} and updates its {@link PlanningScore} member. * * @param solution never null */ Score_ updateScore(Solution_ solution); /** * Returns a diagnostic text that explains the solution through the {@link ConstraintMatch} API to identify which * constraints or planning entities cause that score quality. * In case of an {@link Score#isFeasible() infeasible} solution, this can help diagnose the cause of that. * <p> * Do not parse this string. * Instead, to provide this information in a UI or a service, use {@link #explainScore(Object)} * to retrieve {@link ScoreExplanation#getConstraintMatchTotalMap()} and {@link ScoreExplanation#getIndictmentMap()} * and convert those into a domain specific API. * * @param solution never null * @return null if {@link #updateScore(Object)} returns null with the same solution * @throws IllegalStateException when constraint matching is disabled or not supported by the underlying score * calculator, such as {@link EasyScoreCalculator}. */ String getSummary(Solution_ solution); /** * Calculates and retrieves {@link ConstraintMatchTotal}s and {@link Indictment}s necessary for describing the * quality of a particular solution. * * @param solution never null * @return never null * @throws IllegalStateException when constraint matching is disabled or not supported by the underlying score * calculator, such as {@link EasyScoreCalculator}. */ ScoreExplanation<Solution_, Score_> explainScore(Solution_ solution); /** * As defined by {@link #update(Object, SolutionUpdatePolicy)}, * using {@link SolutionUpdatePolicy#UPDATE_ALL}. * */ default Score_ update(Solution_ solution) { return update(solution, UPDATE_ALL); } /** * Updates the given solution according to the {@link SolutionUpdatePolicy}. * * @param solution never null * @param solutionUpdatePolicy never null; if unsure, pick {@link SolutionUpdatePolicy#UPDATE_ALL} * @return possibly null if already null and {@link SolutionUpdatePolicy} didn't cause its update * @see SolutionUpdatePolicy Description of individual policies with respect to performance trade-offs. */ Score_ update(Solution_ solution, SolutionUpdatePolicy solutionUpdatePolicy); /** * As defined by {@link #explain(Object)}, * using {@link SolutionUpdatePolicy#UPDATE_ALL}. */ default ScoreExplanation<Solution_, Score_> explain(Solution_ solution) { return explain(solution, UPDATE_ALL); } /** * Calculates and retrieves {@link ConstraintMatchTotal}s and {@link Indictment}s necessary for describing the * quality of a particular solution. * * @param solution never null * @param solutionUpdatePolicy never null; if unsure, pick {@link SolutionUpdatePolicy#UPDATE_ALL} * @return never null * @throws IllegalStateException when constraint matching is disabled or not supported by the underlying score * calculator, such as {@link EasyScoreCalculator}. * @see SolutionUpdatePolicy Description of individual policies with respect to performance trade-offs. */ ScoreExplanation<Solution_, Score_> explain(Solution_ solution, SolutionUpdatePolicy solutionUpdatePolicy); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/analysis/ConstraintAnalysis.java
package ai.timefold.solver.core.api.score.analysis; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.calculator.ConstraintMatchAwareIncrementalScoreCalculator; import ai.timefold.solver.core.api.score.constraint.ConstraintRef; import ai.timefold.solver.core.api.score.stream.ConstraintJustification; import ai.timefold.solver.core.api.solver.SolutionManager; import ai.timefold.solver.core.impl.score.constraint.DefaultConstraintMatchTotal; import ai.timefold.solver.core.impl.util.CollectionUtils; /** * Note: Users should never create instances of this type directly. * It is available transitively via {@link SolutionManager#analyze(Object)}. * * @param <Score_> * @param constraintRef never null * @param weight never null * @param score never null * @param matches null if analysis not available; * empty if constraint has no matches, but still non-zero constraint weight; * non-empty if constraint has matches. * This is a {@link List} to simplify access to individual elements, * but it contains no duplicates just like {@link HashSet} wouldn't. */ public record ConstraintAnalysis<Score_ extends Score<Score_>>(ConstraintRef constraintRef, Score_ weight, Score_ score, List<MatchAnalysis<Score_>> matches) { static <Score_ extends Score<Score_>> ConstraintAnalysis<Score_> of(ConstraintRef constraintRef, Score_ constraintWeight, Score_ score) { return new ConstraintAnalysis<>(constraintRef, constraintWeight, score, null); } public ConstraintAnalysis { Objects.requireNonNull(constraintRef); if (weight == null) { /* * Only possible in ConstraintMatchAwareIncrementalScoreCalculator and/or tests. * Easy doesn't support constraint analysis at all. * CS always provides constraint weights. */ throw new IllegalArgumentException(""" The constraint weight must be non-null. Maybe use a non-deprecated %s constructor in your %s implementation? """ .stripTrailing() .formatted(DefaultConstraintMatchTotal.class.getSimpleName(), ConstraintMatchAwareIncrementalScoreCalculator.class.getSimpleName())); } Objects.requireNonNull(score); } ConstraintAnalysis<Score_> negate() { if (matches == null) { return ConstraintAnalysis.of(constraintRef, weight.negate(), score.negate()); } else { var negatedMatchAnalyses = matches.stream() .map(MatchAnalysis::negate) .toList(); return new ConstraintAnalysis<>(constraintRef, weight.negate(), score.negate(), negatedMatchAnalyses); } } static <Score_ extends Score<Score_>> ConstraintAnalysis<Score_> diff( ConstraintRef constraintRef, ConstraintAnalysis<Score_> constraintAnalysis, ConstraintAnalysis<Score_> otherConstraintAnalysis) { if (constraintAnalysis == null) { if (otherConstraintAnalysis == null) { throw new IllegalStateException(""" Impossible state: none of the score explanations provided constraint matches for a constraint (%s). """.formatted(constraintRef)); } // No need to compute diff; this constraint is not present in this score explanation. return otherConstraintAnalysis.negate(); } else if (otherConstraintAnalysis == null) { // No need to compute diff; this constraint is not present in the other score explanation. return constraintAnalysis; } var matchAnalyses = constraintAnalysis.matches(); var otherMatchAnalyses = otherConstraintAnalysis.matches(); if ((matchAnalyses == null && otherMatchAnalyses != null) || (matchAnalyses != null && otherMatchAnalyses == null)) { throw new IllegalStateException(""" Impossible state: Only one of the score analyses (%s, %s) provided match analyses for a constraint (%s).""" .formatted(constraintAnalysis, otherConstraintAnalysis, constraintRef)); } // Compute the diff. var constraintWeightDifference = constraintAnalysis.weight().subtract(otherConstraintAnalysis.weight()); var scoreDifference = constraintAnalysis.score().subtract(otherConstraintAnalysis.score()); if (matchAnalyses == null) { return ConstraintAnalysis.of(constraintRef, constraintWeightDifference, scoreDifference); } var matchAnalysisMap = mapMatchesToJustifications(matchAnalyses); var otherMatchAnalysisMap = mapMatchesToJustifications(otherMatchAnalyses); var result = Stream.concat(matchAnalysisMap.keySet().stream(), otherMatchAnalysisMap.keySet().stream()) .distinct() .map(justification -> { var matchAnalysis = matchAnalysisMap.get(justification); var otherMatchAnalysis = otherMatchAnalysisMap.get(justification); if (matchAnalysis == null) { if (otherMatchAnalysis == null) { throw new IllegalStateException(""" Impossible state: none of the match analyses provided for a constraint (%s). """.formatted(constraintRef)); } // No need to compute diff; this match is not present in this score explanation. return otherMatchAnalysis.negate(); } else if (otherMatchAnalysis == null) { // No need to compute diff; this match is not present in the other score explanation. return matchAnalysis; } else { // Compute the diff. return new MatchAnalysis<>(constraintRef, matchAnalysis.score().subtract(otherMatchAnalysis.score()), justification); } }) .collect(Collectors.toList()); return new ConstraintAnalysis<>(constraintRef, constraintWeightDifference, scoreDifference, result); } private static <Score_ extends Score<Score_>> Map<ConstraintJustification, MatchAnalysis<Score_>> mapMatchesToJustifications(List<MatchAnalysis<Score_>> matchAnalyses) { Map<ConstraintJustification, MatchAnalysis<Score_>> matchAnalysisMap = CollectionUtils.newLinkedHashMap(matchAnalyses.size()); for (var matchAnalysis : matchAnalyses) { var previous = matchAnalysisMap.put(matchAnalysis.justification(), matchAnalysis); if (previous != null) { // Match analysis for the same justification should have been merged already. throw new IllegalStateException( "Impossible state: multiple constraint matches (%s, %s) have the same justification (%s)." .formatted(previous, matchAnalysis, matchAnalysis.justification())); } } return matchAnalysisMap; } /** * Return package name of the constraint that this analysis is for. * * @return equal to {@code constraintRef.packageName()} */ public String constraintPackage() { return constraintRef.packageName(); } /** * Return name of the constraint that this analysis is for. * * @return equal to {@code constraintRef.constraintName()} */ public String constraintName() { return constraintRef.constraintName(); } @Override public String toString() { if (matches == null) { return "(%s at %s, no matches)" .formatted(score, weight); } else { return "(%s at %s, %s matches)" .formatted(score, weight, matches.size()); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/analysis/MatchAnalysis.java
package ai.timefold.solver.core.api.score.analysis; import java.util.Objects; 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.ConstraintJustification; import ai.timefold.solver.core.api.score.stream.ConstraintProvider; import ai.timefold.solver.core.api.solver.SolutionManager; /** * Note: Users should never create instances of this type directly. * It is available transitively via {@link SolutionManager#analyze(Object)}. * * @param <Score_> * @param constraintRef never null * @param score never null * @param justification never null */ public record MatchAnalysis<Score_ extends Score<Score_>>(ConstraintRef constraintRef, Score_ score, ConstraintJustification justification) implements Comparable<MatchAnalysis<Score_>> { public MatchAnalysis { Objects.requireNonNull(constraintRef); Objects.requireNonNull(score); Objects.requireNonNull(justification, """ Received a null justification. Maybe check your %s's justifyWith() implementation for that constraint?""" .formatted(ConstraintProvider.class)); } MatchAnalysis<Score_> negate() { return new MatchAnalysis<>(constraintRef, score.negate(), justification); } @Override public int compareTo(MatchAnalysis<Score_> other) { int constraintRefComparison = this.constraintRef.compareTo(other.constraintRef); if (constraintRefComparison != 0) { return constraintRefComparison; } int scoreComparison = this.score.compareTo(other.score); if (scoreComparison != 0) { return scoreComparison; } else { if (this.justification instanceof Comparable && other.justification instanceof Comparable) { return ((Comparable) this.justification).compareTo(other.justification); } else { return 0; } } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/analysis/ScoreAnalysis.java
package ai.timefold.solver.core.api.score.analysis; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.ScoreExplanation; import ai.timefold.solver.core.api.score.constraint.ConstraintRef; import ai.timefold.solver.core.api.score.stream.Constraint; import ai.timefold.solver.core.api.score.stream.ConstraintJustification; import ai.timefold.solver.core.api.solver.SolutionManager; /** * Represents the breakdown of a {@link Score} into individual {@link ConstraintAnalysis} instances, * one for each constraint. * Compared to {@link ScoreExplanation}, this is JSON-friendly and faster to generate. * * <p> * In order to be fully serializable to JSON, {@link MatchAnalysis} instances must be serializable to JSON * and that requires any implementations of {@link ConstraintJustification} to be serializable to JSON. * This is the responsibility of the user. * * <p> * For deserialization from JSON, the user needs to provide the deserializer themselves. * This is due to the fact that, once the {@link ScoreAnalysis} is received over the wire, * we no longer know which {@link Score} type or {@link ConstraintJustification} type was used. * The user has all of that information in their domain model, * and so they are the correct party to provide the deserializer. * * <p> * Note: the constructors of this record are off-limits. * We ask users to use exclusively {@link SolutionManager#analyze(Object)} to obtain instances of this record. * * @param score never null * @param constraintMap never null; * for each constraint identified by its {@link Constraint#getConstraintRef()}, * the {@link ConstraintAnalysis} that describes the impact of that constraint on the overall score. * Constraints are present even if they have no matches, unless their weight is zero; * zero-weight constraints are not present. * Entries in the map have a stable iteration order; items are ordered first by {@link ConstraintAnalysis#weight()}, * then by {@link ConstraintAnalysis#constraintRef()}. * * @param <Score_> */ public record ScoreAnalysis<Score_ extends Score<Score_>>(Score_ score, Map<ConstraintRef, ConstraintAnalysis<Score_>> constraintMap) { public ScoreAnalysis { Objects.requireNonNull(score, "score"); Objects.requireNonNull(constraintMap, "constraintMap"); // Ensure consistent order and no external interference. var comparator = Comparator.<ConstraintAnalysis<Score_>, Score_> comparing(ConstraintAnalysis::weight) .reversed() .thenComparing(ConstraintAnalysis::constraintRef); constraintMap = Collections.unmodifiableMap(constraintMap.values() .stream() .sorted(comparator) .collect(Collectors.toMap( ConstraintAnalysis::constraintRef, Function.identity(), (constraintAnalysis, otherConstraintAnalysis) -> constraintAnalysis, LinkedHashMap::new))); } /** * Performs a lookup on {@link #constraintMap()}. * Equivalent to {@code constraintMap().get(constraintRef)}. * * @param constraintRef never null * @return null if no constraint matches of such constraint are present */ public ConstraintAnalysis<Score_> getConstraintAnalysis(ConstraintRef constraintRef) { return constraintMap.get(constraintRef); } /** * As defined by {@link #getConstraintAnalysis(ConstraintRef)} * where the arguments are first composed into a singular constraint ID. * * @param constraintPackage never null * @param constraintName never null * @return null if no constraint matches of such constraint are present */ public ConstraintAnalysis<Score_> getConstraintAnalysis(String constraintPackage, String constraintName) { return getConstraintAnalysis(ConstraintRef.of(constraintPackage, constraintName)); } /** * Compare this {@link ScoreAnalysis} to another {@link ScoreAnalysis} * and retrieve the difference between them. * The comparison is in the direction of {@code this - other}. * <p> * Example: if {@code this} has a score of 100 and {@code other} has a score of 90, * the returned {@link ScoreAnalysis#score} will be 10. * If this and other were inverted, the score would have been -10. * The same applies to all other properties of {@link ScoreAnalysis}. * * <p> * In order to properly diff {@link MatchAnalysis} against each other, * we rely on the user implementing {@link ConstraintJustification} equality correctly. * In other words, the diff will consider two justifications equal if the user says they are equal, * and it expects the hash code to be consistent with equals. * * <p> * If one {@link ScoreAnalysis} provides {@link MatchAnalysis} and the other doesn't, exception is thrown. * Such {@link ScoreAnalysis} instances are mutually incompatible. * * @param other never null * @return never null */ public ScoreAnalysis<Score_> diff(ScoreAnalysis<Score_> other) { var result = Stream.concat(constraintMap.keySet().stream(), other.constraintMap.keySet().stream()) .distinct() .collect(Collectors.toMap( Function.identity(), constraintRef -> { var constraintAnalysis = getConstraintAnalysis(constraintRef); var otherConstraintAnalysis = other.getConstraintAnalysis(constraintRef); return ConstraintAnalysis.diff(constraintRef, constraintAnalysis, otherConstraintAnalysis); }, (constraintRef, otherConstraintRef) -> constraintRef, HashMap::new)); return new ScoreAnalysis<>(score.subtract(other.score()), result); } /** * Returns individual {@link ConstraintAnalysis} instances that make up this {@link ScoreAnalysis}. * * @return equivalent to {@code constraintMap().values()} */ public Collection<ConstraintAnalysis<Score_>> constraintAnalyses() { return constraintMap.values(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/bendable/BendableScore.java
package ai.timefold.solver.core.api.score.buildin.bendable; import java.util.Arrays; import java.util.Objects; import ai.timefold.solver.core.api.score.IBendableScore; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.score.ScoreUtil; import ai.timefold.solver.core.impl.score.buildin.BendableScoreDefinition; /** * This {@link Score} is based on n levels of int constraints. * The number of levels is bendable at configuration time. * <p> * This class is immutable. * <p> * The {@link #hardLevelsSize()} and {@link #softLevelsSize()} must be the same as in the * {@link BendableScoreDefinition} used. * * @see Score */ public final class BendableScore implements IBendableScore<BendableScore> { /** * @param scoreString never null * @return never null */ public static BendableScore parseScore(String scoreString) { String[][] scoreTokens = ScoreUtil.parseBendableScoreTokens(BendableScore.class, scoreString); int initScore = ScoreUtil.parseInitScore(BendableScore.class, scoreString, scoreTokens[0][0]); int[] hardScores = new int[scoreTokens[1].length]; for (int i = 0; i < hardScores.length; i++) { hardScores[i] = ScoreUtil.parseLevelAsInt(BendableScore.class, scoreString, scoreTokens[1][i]); } int[] softScores = new int[scoreTokens[2].length]; for (int i = 0; i < softScores.length; i++) { softScores[i] = ScoreUtil.parseLevelAsInt(BendableScore.class, scoreString, scoreTokens[2][i]); } return ofUninitialized(initScore, hardScores, softScores); } /** * Creates a new {@link BendableScore}. * * @param initScore see {@link Score#initScore()} * @param hardScores never null, never change that array afterwards: it must be immutable * @param softScores never null, never change that array afterwards: it must be immutable * @return never null */ public static BendableScore ofUninitialized(int initScore, int[] hardScores, int[] softScores) { return new BendableScore(initScore, hardScores, softScores); } /** * Creates a new {@link BendableScore}. * * @param hardScores never null, never change that array afterwards: it must be immutable * @param softScores never null, never change that array afterwards: it must be immutable * @return never null */ public static BendableScore of(int[] hardScores, int[] softScores) { return new BendableScore(0, hardScores, softScores); } /** * Creates a new {@link BendableScore}. * * @param hardLevelsSize at least 0 * @param softLevelsSize at least 0 * @return never null */ public static BendableScore zero(int hardLevelsSize, int softLevelsSize) { return new BendableScore(0, new int[hardLevelsSize], new int[softLevelsSize]); } /** * Creates a new {@link BendableScore}. * * @param hardLevelsSize at least 0 * @param softLevelsSize at least 0 * @param hardLevel at least 0, less than hardLevelsSize * @param hardScore any * @return never null */ public static BendableScore ofHard(int hardLevelsSize, int softLevelsSize, int hardLevel, int hardScore) { int[] hardScores = new int[hardLevelsSize]; hardScores[hardLevel] = hardScore; return new BendableScore(0, hardScores, new int[softLevelsSize]); } /** * Creates a new {@link BendableScore}. * * @param hardLevelsSize at least 0 * @param softLevelsSize at least 0 * @param softLevel at least 0, less than softLevelsSize * @param softScore any * @return never null */ public static BendableScore ofSoft(int hardLevelsSize, int softLevelsSize, int softLevel, int softScore) { int[] softScores = new int[softLevelsSize]; softScores[softLevel] = softScore; return new BendableScore(0, new int[hardLevelsSize], softScores); } // ************************************************************************ // Fields // ************************************************************************ private final int initScore; private final int[] hardScores; private final int[] softScores; /** * Private default constructor for default marshalling/unmarshalling of unknown frameworks that use reflection. * Such integration is always inferior to the specialized integration modules, such as * timefold-solver-jpa, timefold-solver-jackson, timefold-solver-jaxb, ... */ @SuppressWarnings("unused") private BendableScore() { this(Integer.MIN_VALUE, null, null); } /** * @param initScore see {@link Score#initScore()} * @param hardScores never null * @param softScores never null */ private BendableScore(int initScore, int[] hardScores, int[] softScores) { this.initScore = initScore; this.hardScores = hardScores; this.softScores = softScores; } @Override public int initScore() { return initScore; } /** * @return not null, array copy because this class is immutable */ public int[] hardScores() { return Arrays.copyOf(hardScores, hardScores.length); } /** * As defined by {@link #hardScores()}. * * @deprecated Use {@link #hardScores()} instead. */ @Deprecated(forRemoval = true) public int[] getHardScores() { return hardScores(); } /** * @return not null, array copy because this class is immutable */ public int[] softScores() { return Arrays.copyOf(softScores, softScores.length); } /** * As defined by {@link #softScores()}. * * @deprecated Use {@link #softScores()} instead. */ @Deprecated(forRemoval = true) public int[] getSoftScores() { return softScores(); } @Override public int hardLevelsSize() { return hardScores.length; } /** * @param hardLevel {@code 0 <= hardLevel <} {@link #hardLevelsSize()}. * The {@code scoreLevel} is {@code hardLevel} for hard levels and {@code softLevel + hardLevelSize} for soft levels. * @return higher is better */ public int hardScore(int hardLevel) { return hardScores[hardLevel]; } /** * As defined by {@link #hardScore(int)}. * * @deprecated Use {@link #hardScore(int)} instead. */ @Deprecated(forRemoval = true) public int getHardScore(int hardLevel) { return hardScore(hardLevel); } @Override public int softLevelsSize() { return softScores.length; } /** * @param softLevel {@code 0 <= softLevel <} {@link #softLevelsSize()}. * The {@code scoreLevel} is {@code hardLevel} for hard levels and {@code softLevel + hardLevelSize} for soft levels. * @return higher is better */ public int softScore(int softLevel) { return softScores[softLevel]; } /** * As defined by {@link #softScore(int)}. * * @deprecated Use {@link #softScore(int)} instead. */ @Deprecated(forRemoval = true) public int getSoftScore(int hardLevel) { return softScore(hardLevel); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public BendableScore withInitScore(int newInitScore) { return new BendableScore(newInitScore, hardScores, softScores); } /** * @param level {@code 0 <= level <} {@link #levelsSize()} * @return higher is better */ public int hardOrSoftScore(int level) { if (level < hardScores.length) { return hardScores[level]; } else { return softScores[level - hardScores.length]; } } /** * As defined by {@link #hardOrSoftScore(int)}. * * @deprecated Use {@link #hardOrSoftScore(int)} instead. */ @Deprecated(forRemoval = true) public int getHardOrSoftScore(int level) { return hardOrSoftScore(level); } @Override public boolean isFeasible() { if (initScore < 0) { return false; } for (int hardScore : hardScores) { if (hardScore < 0) { return false; } } return true; } @Override public BendableScore add(BendableScore addend) { validateCompatible(addend); int[] newHardScores = new int[hardScores.length]; int[] newSoftScores = new int[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = hardScores[i] + addend.hardScore(i); } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = softScores[i] + addend.softScore(i); } return new BendableScore( initScore + addend.initScore(), newHardScores, newSoftScores); } @Override public BendableScore subtract(BendableScore subtrahend) { validateCompatible(subtrahend); int[] newHardScores = new int[hardScores.length]; int[] newSoftScores = new int[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = hardScores[i] - subtrahend.hardScore(i); } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = softScores[i] - subtrahend.softScore(i); } return new BendableScore( initScore - subtrahend.initScore(), newHardScores, newSoftScores); } @Override public BendableScore multiply(double multiplicand) { int[] newHardScores = new int[hardScores.length]; int[] newSoftScores = new int[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = (int) Math.floor(hardScores[i] * multiplicand); } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = (int) Math.floor(softScores[i] * multiplicand); } return new BendableScore( (int) Math.floor(initScore * multiplicand), newHardScores, newSoftScores); } @Override public BendableScore divide(double divisor) { int[] newHardScores = new int[hardScores.length]; int[] newSoftScores = new int[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = (int) Math.floor(hardScores[i] / divisor); } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = (int) Math.floor(softScores[i] / divisor); } return new BendableScore( (int) Math.floor(initScore / divisor), newHardScores, newSoftScores); } @Override public BendableScore power(double exponent) { int[] newHardScores = new int[hardScores.length]; int[] newSoftScores = new int[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = (int) Math.floor(Math.pow(hardScores[i], exponent)); } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = (int) Math.floor(Math.pow(softScores[i], exponent)); } return new BendableScore( (int) Math.floor(Math.pow(initScore, exponent)), newHardScores, newSoftScores); } @Override public BendableScore negate() { // Overridden as the default impl would create zero() all the time. int[] newHardScores = new int[hardScores.length]; int[] newSoftScores = new int[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = -hardScores[i]; } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = -softScores[i]; } return new BendableScore(-initScore, newHardScores, newSoftScores); } @Override public BendableScore abs() { int[] newHardScores = new int[hardScores.length]; int[] newSoftScores = new int[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = Math.abs(hardScores[i]); } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = Math.abs(softScores[i]); } return new BendableScore(Math.abs(initScore), newHardScores, newSoftScores); } @Override public BendableScore zero() { return BendableScore.zero(hardLevelsSize(), softLevelsSize()); } @Override public Number[] toLevelNumbers() { Number[] levelNumbers = new Number[hardScores.length + softScores.length]; for (int i = 0; i < hardScores.length; i++) { levelNumbers[i] = hardScores[i]; } for (int i = 0; i < softScores.length; i++) { levelNumbers[hardScores.length + i] = softScores[i]; } return levelNumbers; } @Override public boolean equals(Object o) { if (o instanceof BendableScore other) { if (hardLevelsSize() != other.hardLevelsSize() || softLevelsSize() != other.softLevelsSize()) { return false; } if (initScore != other.initScore()) { return false; } for (int i = 0; i < hardScores.length; i++) { if (hardScores[i] != other.hardScore(i)) { return false; } } for (int i = 0; i < softScores.length; i++) { if (softScores[i] != other.softScore(i)) { return false; } } return true; } return false; } @Override public int hashCode() { return Objects.hash(initScore, Arrays.hashCode(hardScores), Arrays.hashCode(softScores)); } @Override public int compareTo(BendableScore other) { validateCompatible(other); if (initScore != other.initScore()) { return Integer.compare(initScore, other.initScore()); } for (int i = 0; i < hardScores.length; i++) { if (hardScores[i] != other.hardScore(i)) { return Integer.compare(hardScores[i], other.hardScore(i)); } } for (int i = 0; i < softScores.length; i++) { if (softScores[i] != other.softScore(i)) { return Integer.compare(softScores[i], other.softScore(i)); } } return 0; } @Override public String toShortString() { return ScoreUtil.buildBendableShortString(this, n -> n.intValue() != 0); } @Override public String toString() { StringBuilder s = new StringBuilder(((hardScores.length + softScores.length) * 4) + 13); s.append(ScoreUtil.getInitPrefix(initScore)); s.append("["); boolean first = true; for (int hardScore : hardScores) { if (first) { first = false; } else { s.append("/"); } s.append(hardScore); } s.append("]hard/["); first = true; for (int softScore : softScores) { if (first) { first = false; } else { s.append("/"); } s.append(softScore); } s.append("]soft"); return s.toString(); } public void validateCompatible(BendableScore other) { if (hardLevelsSize() != other.hardLevelsSize()) { throw new IllegalArgumentException("The score (" + this + ") with hardScoreSize (" + hardLevelsSize() + ") is not compatible with the other score (" + other + ") with hardScoreSize (" + other.hardLevelsSize() + ")."); } if (softLevelsSize() != other.softLevelsSize()) { throw new IllegalArgumentException("The score (" + this + ") with softScoreSize (" + softLevelsSize() + ") is not compatible with the other score (" + other + ") with softScoreSize (" + other.softLevelsSize() + ")."); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/bendable/package-info.java
/** * Support for a {@link ai.timefold.solver.core.api.score.Score} with a configurable number of score levels * and {@code int} score weights. */ package ai.timefold.solver.core.api.score.buildin.bendable;
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/bendablebigdecimal/BendableBigDecimalScore.java
package ai.timefold.solver.core.api.score.buildin.bendablebigdecimal; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Arrays; import java.util.Objects; import java.util.stream.Stream; import ai.timefold.solver.core.api.score.IBendableScore; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.score.ScoreUtil; import ai.timefold.solver.core.impl.score.buildin.BendableScoreDefinition; /** * This {@link Score} is based on n levels of {@link BigDecimal} constraints. * The number of levels is bendable at configuration time. * <p> * This class is immutable. * <p> * The {@link #hardLevelsSize()} and {@link #softLevelsSize()} must be the same as in the * {@link BendableScoreDefinition} used. * * @see Score */ public final class BendableBigDecimalScore implements IBendableScore<BendableBigDecimalScore> { /** * @param scoreString never null * @return never null */ public static BendableBigDecimalScore parseScore(String scoreString) { String[][] scoreTokens = ScoreUtil.parseBendableScoreTokens(BendableBigDecimalScore.class, scoreString); int initScore = ScoreUtil.parseInitScore(BendableBigDecimalScore.class, scoreString, scoreTokens[0][0]); BigDecimal[] hardScores = new BigDecimal[scoreTokens[1].length]; for (int i = 0; i < hardScores.length; i++) { hardScores[i] = ScoreUtil.parseLevelAsBigDecimal(BendableBigDecimalScore.class, scoreString, scoreTokens[1][i]); } BigDecimal[] softScores = new BigDecimal[scoreTokens[2].length]; for (int i = 0; i < softScores.length; i++) { softScores[i] = ScoreUtil.parseLevelAsBigDecimal(BendableBigDecimalScore.class, scoreString, scoreTokens[2][i]); } return ofUninitialized(initScore, hardScores, softScores); } /** * Creates a new {@link BendableBigDecimalScore}. * * @param initScore see {@link Score#initScore()} * @param hardScores never null, never change that array afterwards: it must be immutable * @param softScores never null, never change that array afterwards: it must be immutable * @return never null */ public static BendableBigDecimalScore ofUninitialized(int initScore, BigDecimal[] hardScores, BigDecimal[] softScores) { return new BendableBigDecimalScore(initScore, hardScores, softScores); } /** * Creates a new {@link BendableBigDecimalScore}. * * @param hardScores never null, never change that array afterwards: it must be immutable * @param softScores never null, never change that array afterwards: it must be immutable * @return never null */ public static BendableBigDecimalScore of(BigDecimal[] hardScores, BigDecimal[] softScores) { return new BendableBigDecimalScore(0, hardScores, softScores); } /** * Creates a new {@link BendableBigDecimalScore}. * * @param hardLevelsSize at least 0 * @param softLevelsSize at least 0 * @return never null */ public static BendableBigDecimalScore zero(int hardLevelsSize, int softLevelsSize) { BigDecimal[] hardScores = new BigDecimal[hardLevelsSize]; Arrays.fill(hardScores, BigDecimal.ZERO); BigDecimal[] softScores = new BigDecimal[softLevelsSize]; Arrays.fill(softScores, BigDecimal.ZERO); return new BendableBigDecimalScore(0, hardScores, softScores); } /** * Creates a new {@link BendableBigDecimalScore}. * * @param hardLevelsSize at least 0 * @param softLevelsSize at least 0 * @param hardLevel at least 0, less than hardLevelsSize * @param hardScore never null * @return never null */ public static BendableBigDecimalScore ofHard(int hardLevelsSize, int softLevelsSize, int hardLevel, BigDecimal hardScore) { BigDecimal[] hardScores = new BigDecimal[hardLevelsSize]; Arrays.fill(hardScores, BigDecimal.ZERO); BigDecimal[] softScores = new BigDecimal[softLevelsSize]; Arrays.fill(softScores, BigDecimal.ZERO); hardScores[hardLevel] = hardScore; return new BendableBigDecimalScore(0, hardScores, softScores); } /** * Creates a new {@link BendableBigDecimalScore}. * * @param hardLevelsSize at least 0 * @param softLevelsSize at least 0 * @param softLevel at least 0, less than softLevelsSize * @param softScore never null * @return never null */ public static BendableBigDecimalScore ofSoft(int hardLevelsSize, int softLevelsSize, int softLevel, BigDecimal softScore) { BigDecimal[] hardScores = new BigDecimal[hardLevelsSize]; Arrays.fill(hardScores, BigDecimal.ZERO); BigDecimal[] softScores = new BigDecimal[softLevelsSize]; Arrays.fill(softScores, BigDecimal.ZERO); softScores[softLevel] = softScore; return new BendableBigDecimalScore(0, hardScores, softScores); } // ************************************************************************ // Fields // ************************************************************************ private final int initScore; private final BigDecimal[] hardScores; private final BigDecimal[] softScores; /** * Private default constructor for default marshalling/unmarshalling of unknown frameworks that use reflection. * Such integration is always inferior to the specialized integration modules, such as * timefold-solver-jpa, timefold-solver-jackson, timefold-solver-jaxb, ... */ @SuppressWarnings("unused") private BendableBigDecimalScore() { this(Integer.MIN_VALUE, null, null); } /** * @param initScore see {@link Score#initScore()} * @param hardScores never null * @param softScores never null */ private BendableBigDecimalScore(int initScore, BigDecimal[] hardScores, BigDecimal[] softScores) { this.initScore = initScore; this.hardScores = hardScores; this.softScores = softScores; } @Override public int initScore() { return initScore; } /** * @return not null, array copy because this class is immutable */ public BigDecimal[] hardScores() { return Arrays.copyOf(hardScores, hardScores.length); } /** * As defined by {@link #hardScores()}. * * @deprecated Use {@link #hardScores()} instead. */ @Deprecated(forRemoval = true) public BigDecimal[] getHardScores() { return hardScores(); } /** * @return not null, array copy because this class is immutable */ public BigDecimal[] softScores() { return Arrays.copyOf(softScores, softScores.length); } /** * As defined by {@link #softScores()}. * * @deprecated Use {@link #softScores()} instead. */ @Deprecated(forRemoval = true) public BigDecimal[] getSoftScores() { return softScores(); } @Override public int hardLevelsSize() { return hardScores.length; } /** * @param index {@code 0 <= index <} {@link #hardLevelsSize()} * @return higher is better */ public BigDecimal hardScore(int index) { return hardScores[index]; } /** * As defined by {@link #hardScore(int)}. * * @deprecated Use {@link #hardScore(int)} instead. */ @Deprecated(forRemoval = true) public BigDecimal getHardScore(int index) { return hardScore(index); } @Override public int softLevelsSize() { return softScores.length; } /** * @param index {@code 0 <= index <} {@link #softLevelsSize()} * @return higher is better */ public BigDecimal softScore(int index) { return softScores[index]; } /** * As defined by {@link #softScore(int)}. * * @deprecated Use {@link #softScore(int)} instead. */ @Deprecated(forRemoval = true) public BigDecimal getSoftScore(int index) { return softScore(index); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public BendableBigDecimalScore withInitScore(int newInitScore) { return new BendableBigDecimalScore(newInitScore, hardScores, softScores); } /** * @param index {@code 0 <= index <} {@link #levelsSize()} * @return higher is better */ public BigDecimal hardOrSoftScore(int index) { if (index < hardScores.length) { return hardScores[index]; } else { return softScores[index - hardScores.length]; } } /** * As defined by {@link #hardOrSoftScore(int)}. * * @deprecated Use {@link #hardOrSoftScore(int)} instead. */ @Deprecated(forRemoval = true) public BigDecimal getHardOrSoftScore(int index) { return hardOrSoftScore(index); } @Override public boolean isFeasible() { if (initScore < 0) { return false; } for (BigDecimal hardScore : hardScores) { if (hardScore.compareTo(BigDecimal.ZERO) < 0) { return false; } } return true; } @Override public BendableBigDecimalScore add(BendableBigDecimalScore addend) { validateCompatible(addend); BigDecimal[] newHardScores = new BigDecimal[hardScores.length]; BigDecimal[] newSoftScores = new BigDecimal[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = hardScores[i].add(addend.hardScore(i)); } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = softScores[i].add(addend.softScore(i)); } return new BendableBigDecimalScore( initScore + addend.initScore(), newHardScores, newSoftScores); } @Override public BendableBigDecimalScore subtract(BendableBigDecimalScore subtrahend) { validateCompatible(subtrahend); BigDecimal[] newHardScores = new BigDecimal[hardScores.length]; BigDecimal[] newSoftScores = new BigDecimal[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = hardScores[i].subtract(subtrahend.hardScore(i)); } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = softScores[i].subtract(subtrahend.softScore(i)); } return new BendableBigDecimalScore( initScore - subtrahend.initScore(), newHardScores, newSoftScores); } @Override public BendableBigDecimalScore multiply(double multiplicand) { BigDecimal[] newHardScores = new BigDecimal[hardScores.length]; BigDecimal[] newSoftScores = new BigDecimal[softScores.length]; BigDecimal bigDecimalMultiplicand = BigDecimal.valueOf(multiplicand); for (int i = 0; i < newHardScores.length; i++) { // The (unspecified) scale/precision of the multiplicand should have no impact on the returned scale/precision newHardScores[i] = hardScores[i].multiply(bigDecimalMultiplicand).setScale(hardScores[i].scale(), RoundingMode.FLOOR); } for (int i = 0; i < newSoftScores.length; i++) { // The (unspecified) scale/precision of the multiplicand should have no impact on the returned scale/precision newSoftScores[i] = softScores[i].multiply(bigDecimalMultiplicand).setScale(softScores[i].scale(), RoundingMode.FLOOR); } return new BendableBigDecimalScore( (int) Math.floor(initScore * multiplicand), newHardScores, newSoftScores); } @Override public BendableBigDecimalScore divide(double divisor) { BigDecimal[] newHardScores = new BigDecimal[hardScores.length]; BigDecimal[] newSoftScores = new BigDecimal[softScores.length]; BigDecimal bigDecimalDivisor = BigDecimal.valueOf(divisor); for (int i = 0; i < newHardScores.length; i++) { BigDecimal hardScore = hardScores[i]; newHardScores[i] = hardScore.divide(bigDecimalDivisor, hardScore.scale(), RoundingMode.FLOOR); } for (int i = 0; i < newSoftScores.length; i++) { BigDecimal softScore = softScores[i]; newSoftScores[i] = softScore.divide(bigDecimalDivisor, softScore.scale(), RoundingMode.FLOOR); } return new BendableBigDecimalScore( (int) Math.floor(initScore / divisor), newHardScores, newSoftScores); } @Override public BendableBigDecimalScore power(double exponent) { BigDecimal[] newHardScores = new BigDecimal[hardScores.length]; BigDecimal[] newSoftScores = new BigDecimal[softScores.length]; BigDecimal actualExponent = BigDecimal.valueOf(exponent); // The (unspecified) scale/precision of the exponent should have no impact on the returned scale/precision // TODO FIXME remove .intValue() so non-integer exponents produce correct results // None of the normal Java libraries support BigDecimal.pow(BigDecimal) for (int i = 0; i < newHardScores.length; i++) { BigDecimal hardScore = hardScores[i]; newHardScores[i] = hardScore.pow(actualExponent.intValue()).setScale(hardScore.scale(), RoundingMode.FLOOR); } for (int i = 0; i < newSoftScores.length; i++) { BigDecimal softScore = softScores[i]; newSoftScores[i] = softScore.pow(actualExponent.intValue()).setScale(softScore.scale(), RoundingMode.FLOOR); } return new BendableBigDecimalScore( (int) Math.floor(Math.pow(initScore, exponent)), newHardScores, newSoftScores); } @Override public BendableBigDecimalScore negate() { // Overridden as the default impl would create zero() all the time. BigDecimal[] newHardScores = new BigDecimal[hardScores.length]; BigDecimal[] newSoftScores = new BigDecimal[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = hardScores[i].negate(); } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = softScores[i].negate(); } return new BendableBigDecimalScore(-initScore, newHardScores, newSoftScores); } @Override public BendableBigDecimalScore abs() { BigDecimal[] newHardScores = new BigDecimal[hardScores.length]; BigDecimal[] newSoftScores = new BigDecimal[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = hardScores[i].abs(); } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = softScores[i].abs(); } return new BendableBigDecimalScore(Math.abs(initScore), newHardScores, newSoftScores); } @Override public BendableBigDecimalScore zero() { return BendableBigDecimalScore.zero(hardLevelsSize(), softLevelsSize()); } @Override public Number[] toLevelNumbers() { Number[] levelNumbers = new Number[hardScores.length + softScores.length]; for (int i = 0; i < hardScores.length; i++) { levelNumbers[i] = hardScores[i]; } for (int i = 0; i < softScores.length; i++) { levelNumbers[hardScores.length + i] = softScores[i]; } return levelNumbers; } @Override public boolean equals(Object o) { if (o instanceof BendableBigDecimalScore other) { if (hardLevelsSize() != other.hardLevelsSize() || softLevelsSize() != other.softLevelsSize()) { return false; } if (initScore != other.initScore()) { return false; } for (int i = 0; i < hardScores.length; i++) { if (!hardScores[i].stripTrailingZeros().equals(other.hardScore(i).stripTrailingZeros())) { return false; } } for (int i = 0; i < softScores.length; i++) { if (!softScores[i].stripTrailingZeros().equals(other.softScore(i).stripTrailingZeros())) { return false; } } return true; } return false; } @Override public int hashCode() { int[] scoreHashCodes = Stream.concat(Arrays.stream(hardScores), Arrays.stream(softScores)) .map(BigDecimal::stripTrailingZeros) .mapToInt(BigDecimal::hashCode) .toArray(); return Objects.hash(initScore, Arrays.hashCode(scoreHashCodes)); } @Override public int compareTo(BendableBigDecimalScore other) { validateCompatible(other); if (initScore != other.initScore()) { return Integer.compare(initScore, other.initScore()); } for (int i = 0; i < hardScores.length; i++) { int hardScoreComparison = hardScores[i].compareTo(other.hardScore(i)); if (hardScoreComparison != 0) { return hardScoreComparison; } } for (int i = 0; i < softScores.length; i++) { int softScoreComparison = softScores[i].compareTo(other.softScore(i)); if (softScoreComparison != 0) { return softScoreComparison; } } return 0; } @Override public String toShortString() { return ScoreUtil.buildBendableShortString(this, n -> ((BigDecimal) n).compareTo(BigDecimal.ZERO) != 0); } @Override public String toString() { StringBuilder s = new StringBuilder(((hardScores.length + softScores.length) * 4) + 13); s.append(ScoreUtil.getInitPrefix(initScore)); s.append("["); boolean first = true; for (BigDecimal hardScore : hardScores) { if (first) { first = false; } else { s.append("/"); } s.append(hardScore); } s.append("]hard/["); first = true; for (BigDecimal softScore : softScores) { if (first) { first = false; } else { s.append("/"); } s.append(softScore); } s.append("]soft"); return s.toString(); } public void validateCompatible(BendableBigDecimalScore other) { if (hardLevelsSize() != other.hardLevelsSize()) { throw new IllegalArgumentException("The score (" + this + ") with hardScoreSize (" + hardLevelsSize() + ") is not compatible with the other score (" + other + ") with hardScoreSize (" + other.hardLevelsSize() + ")."); } if (softLevelsSize() != other.softLevelsSize()) { throw new IllegalArgumentException("The score (" + this + ") with softScoreSize (" + softLevelsSize() + ") is not compatible with the other score (" + other + ") with softScoreSize (" + other.softLevelsSize() + ")."); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/bendablebigdecimal/package-info.java
/** * Support for a {@link ai.timefold.solver.core.api.score.Score} with a configurable number of score levels * and {@link java.math.BigDecimal} score weights. */ package ai.timefold.solver.core.api.score.buildin.bendablebigdecimal;
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/bendablelong/BendableLongScore.java
package ai.timefold.solver.core.api.score.buildin.bendablelong; import java.util.Arrays; import java.util.Objects; import ai.timefold.solver.core.api.score.IBendableScore; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.score.ScoreUtil; import ai.timefold.solver.core.impl.score.buildin.BendableLongScoreDefinition; /** * This {@link Score} is based on n levels of long constraints. * The number of levels is bendable at configuration time. * <p> * This class is immutable. * <p> * The {@link #hardLevelsSize()} and {@link #softLevelsSize()} must be the same as in the * {@link BendableLongScoreDefinition} used. * * @see Score */ public final class BendableLongScore implements IBendableScore<BendableLongScore> { /** * @param scoreString never null * @return never null */ public static BendableLongScore parseScore(String scoreString) { String[][] scoreTokens = ScoreUtil.parseBendableScoreTokens(BendableLongScore.class, scoreString); int initScore = ScoreUtil.parseInitScore(BendableLongScore.class, scoreString, scoreTokens[0][0]); long[] hardScores = new long[scoreTokens[1].length]; for (int i = 0; i < hardScores.length; i++) { hardScores[i] = ScoreUtil.parseLevelAsLong(BendableLongScore.class, scoreString, scoreTokens[1][i]); } long[] softScores = new long[scoreTokens[2].length]; for (int i = 0; i < softScores.length; i++) { softScores[i] = ScoreUtil.parseLevelAsLong(BendableLongScore.class, scoreString, scoreTokens[2][i]); } return ofUninitialized(initScore, hardScores, softScores); } /** * Creates a new {@link BendableLongScore}. * * @param initScore see {@link Score#initScore()} * @param hardScores never null, never change that array afterwards: it must be immutable * @param softScores never null, never change that array afterwards: it must be immutable * @return never null */ public static BendableLongScore ofUninitialized(int initScore, long[] hardScores, long[] softScores) { return new BendableLongScore(initScore, hardScores, softScores); } /** * Creates a new {@link BendableLongScore}. * * @param hardScores never null, never change that array afterwards: it must be immutable * @param softScores never null, never change that array afterwards: it must be immutable * @return never null */ public static BendableLongScore of(long[] hardScores, long[] softScores) { return new BendableLongScore(0, hardScores, softScores); } /** * Creates a new {@link BendableLongScore}. * * @param hardLevelsSize at least 0 * @param softLevelsSize at least 0 * @return never null */ public static BendableLongScore zero(int hardLevelsSize, int softLevelsSize) { return new BendableLongScore(0, new long[hardLevelsSize], new long[softLevelsSize]); } /** * Creates a new {@link BendableLongScore}. * * @param hardLevelsSize at least 0 * @param softLevelsSize at least 0 * @param hardLevel at least 0, less than hardLevelsSize * @param hardScore any * @return never null */ public static BendableLongScore ofHard(int hardLevelsSize, int softLevelsSize, int hardLevel, long hardScore) { long[] hardScores = new long[hardLevelsSize]; hardScores[hardLevel] = hardScore; return new BendableLongScore(0, hardScores, new long[softLevelsSize]); } /** * Creates a new {@link BendableLongScore}. * * @param hardLevelsSize at least 0 * @param softLevelsSize at least 0 * @param softLevel at least 0, less than softLevelsSize * @param softScore any * @return never null */ public static BendableLongScore ofSoft(int hardLevelsSize, int softLevelsSize, int softLevel, long softScore) { long[] softScores = new long[softLevelsSize]; softScores[softLevel] = softScore; return new BendableLongScore(0, new long[hardLevelsSize], softScores); } // ************************************************************************ // Fields // ************************************************************************ private final int initScore; private final long[] hardScores; private final long[] softScores; /** * Private default constructor for default marshalling/unmarshalling of unknown frameworks that use reflection. * Such integration is always inferior to the specialized integration modules, such as * timefold-solver-jpa, timefold-solver-jackson, timefold-solver-jaxb, ... */ @SuppressWarnings("unused") private BendableLongScore() { this(Integer.MIN_VALUE, null, null); } /** * @param initScore see {@link Score#initScore()} * @param hardScores never null * @param softScores never null */ private BendableLongScore(int initScore, long[] hardScores, long[] softScores) { this.initScore = initScore; this.hardScores = hardScores; this.softScores = softScores; } @Override public int initScore() { return initScore; } /** * @return not null, array copy because this class is immutable */ public long[] hardScores() { return Arrays.copyOf(hardScores, hardScores.length); } /** * As defined by {@link #hardScores()}. * * @deprecated Use {@link #hardScores()} instead. */ @Deprecated(forRemoval = true) public long[] getHardScores() { return hardScores(); } /** * @return not null, array copy because this class is immutable */ public long[] softScores() { return Arrays.copyOf(softScores, softScores.length); } /** * As defined by {@link #softScores()}. * * @deprecated Use {@link #softScores()} instead. */ @Deprecated(forRemoval = true) public long[] getSoftScores() { return softScores(); } @Override public int hardLevelsSize() { return hardScores.length; } /** * @param index {@code 0 <= index <} {@link #hardLevelsSize()} * @return higher is better */ public long hardScore(int index) { return hardScores[index]; } /** * As defined by {@link #hardScore(int)}. * * @deprecated Use {@link #hardScore(int)} instead. */ @Deprecated(forRemoval = true) public long getHardScore(int index) { return hardScore(index); } @Override public int softLevelsSize() { return softScores.length; } /** * @param index {@code 0 <= index <} {@link #softLevelsSize()} * @return higher is better */ public long softScore(int index) { return softScores[index]; } /** * As defined by {@link #softScore(int)}. * * @deprecated Use {@link #softScore(int)} instead. */ @Deprecated(forRemoval = true) public long getSoftScore(int index) { return softScore(index); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public BendableLongScore withInitScore(int newInitScore) { return new BendableLongScore(newInitScore, hardScores, softScores); } /** * @param index {@code 0 <= index <} {@link #levelsSize()} * @return higher is better */ public long hardOrSoftScore(int index) { if (index < hardScores.length) { return hardScores[index]; } else { return softScores[index - hardScores.length]; } } /** * As defined by {@link #hardOrSoftScore(int)}. * * @deprecated Use {@link #hardOrSoftScore(int)} instead. */ @Deprecated(forRemoval = true) public long getHardOrSoftScore(int index) { return hardOrSoftScore(index); } @Override public boolean isFeasible() { if (initScore < 0) { return false; } for (long hardScore : hardScores) { if (hardScore < 0) { return false; } } return true; } @Override public BendableLongScore add(BendableLongScore addend) { validateCompatible(addend); long[] newHardScores = new long[hardScores.length]; long[] newSoftScores = new long[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = hardScores[i] + addend.hardScore(i); } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = softScores[i] + addend.softScore(i); } return new BendableLongScore( initScore + addend.initScore(), newHardScores, newSoftScores); } @Override public BendableLongScore subtract(BendableLongScore subtrahend) { validateCompatible(subtrahend); long[] newHardScores = new long[hardScores.length]; long[] newSoftScores = new long[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = hardScores[i] - subtrahend.hardScore(i); } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = softScores[i] - subtrahend.softScore(i); } return new BendableLongScore( initScore - subtrahend.initScore(), newHardScores, newSoftScores); } @Override public BendableLongScore multiply(double multiplicand) { long[] newHardScores = new long[hardScores.length]; long[] newSoftScores = new long[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = (long) Math.floor(hardScores[i] * multiplicand); } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = (long) Math.floor(softScores[i] * multiplicand); } return new BendableLongScore( (int) Math.floor(initScore * multiplicand), newHardScores, newSoftScores); } @Override public BendableLongScore divide(double divisor) { long[] newHardScores = new long[hardScores.length]; long[] newSoftScores = new long[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = (long) Math.floor(hardScores[i] / divisor); } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = (long) Math.floor(softScores[i] / divisor); } return new BendableLongScore( (int) Math.floor(initScore / divisor), newHardScores, newSoftScores); } @Override public BendableLongScore power(double exponent) { long[] newHardScores = new long[hardScores.length]; long[] newSoftScores = new long[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = (long) Math.floor(Math.pow(hardScores[i], exponent)); } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = (long) Math.floor(Math.pow(softScores[i], exponent)); } return new BendableLongScore( (int) Math.floor(Math.pow(initScore, exponent)), newHardScores, newSoftScores); } @Override public BendableLongScore negate() { // Overridden as the default impl would create zero() all the time. long[] newHardScores = new long[hardScores.length]; long[] newSoftScores = new long[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = -hardScores[i]; } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = -softScores[i]; } return new BendableLongScore(-initScore, newHardScores, newSoftScores); } @Override public BendableLongScore abs() { long[] newHardScores = new long[hardScores.length]; long[] newSoftScores = new long[softScores.length]; for (int i = 0; i < newHardScores.length; i++) { newHardScores[i] = Math.abs(hardScores[i]); } for (int i = 0; i < newSoftScores.length; i++) { newSoftScores[i] = Math.abs(softScores[i]); } return new BendableLongScore(Math.abs(initScore), newHardScores, newSoftScores); } @Override public BendableLongScore zero() { return BendableLongScore.zero(hardLevelsSize(), softLevelsSize()); } @Override public Number[] toLevelNumbers() { Number[] levelNumbers = new Number[hardScores.length + softScores.length]; for (int i = 0; i < hardScores.length; i++) { levelNumbers[i] = hardScores[i]; } for (int i = 0; i < softScores.length; i++) { levelNumbers[hardScores.length + i] = softScores[i]; } return levelNumbers; } @Override public boolean equals(Object o) { if (o instanceof BendableLongScore other) { if (hardLevelsSize() != other.hardLevelsSize() || softLevelsSize() != other.softLevelsSize()) { return false; } if (initScore != other.initScore()) { return false; } for (int i = 0; i < hardScores.length; i++) { if (hardScores[i] != other.hardScore(i)) { return false; } } for (int i = 0; i < softScores.length; i++) { if (softScores[i] != other.softScore(i)) { return false; } } return true; } return false; } @Override public int hashCode() { return Objects.hash(initScore, Arrays.hashCode(hardScores), Arrays.hashCode(softScores)); } @Override public int compareTo(BendableLongScore other) { validateCompatible(other); if (initScore != other.initScore()) { return Integer.compare(initScore, other.initScore()); } for (int i = 0; i < hardScores.length; i++) { if (hardScores[i] != other.hardScore(i)) { return Long.compare(hardScores[i], other.hardScore(i)); } } for (int i = 0; i < softScores.length; i++) { if (softScores[i] != other.softScore(i)) { return Long.compare(softScores[i], other.softScore(i)); } } return 0; } @Override public String toShortString() { return ScoreUtil.buildBendableShortString(this, n -> n.longValue() != 0L); } @Override public String toString() { StringBuilder s = new StringBuilder(((hardScores.length + softScores.length) * 4) + 13); s.append(ScoreUtil.getInitPrefix(initScore)); s.append("["); boolean first = true; for (long hardScore : hardScores) { if (first) { first = false; } else { s.append("/"); } s.append(hardScore); } s.append("]hard/["); first = true; for (long softScore : softScores) { if (first) { first = false; } else { s.append("/"); } s.append(softScore); } s.append("]soft"); return s.toString(); } public void validateCompatible(BendableLongScore other) { if (hardLevelsSize() != other.hardLevelsSize()) { throw new IllegalArgumentException("The score (" + this + ") with hardScoreSize (" + hardLevelsSize() + ") is not compatible with the other score (" + other + ") with hardScoreSize (" + other.hardLevelsSize() + ")."); } if (softLevelsSize() != other.softLevelsSize()) { throw new IllegalArgumentException("The score (" + this + ") with softScoreSize (" + softLevelsSize() + ") is not compatible with the other score (" + other + ") with softScoreSize (" + other.softLevelsSize() + ")."); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/bendablelong/package-info.java
/** * Support for a {@link ai.timefold.solver.core.api.score.Score} with a configurable number of score levels * and {@code long} score weights. */ package ai.timefold.solver.core.api.score.buildin.bendablelong;
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/hardmediumsoft/HardMediumSoftScore.java
package ai.timefold.solver.core.api.score.buildin.hardmediumsoft; import static ai.timefold.solver.core.impl.score.ScoreUtil.HARD_LABEL; import static ai.timefold.solver.core.impl.score.ScoreUtil.MEDIUM_LABEL; import static ai.timefold.solver.core.impl.score.ScoreUtil.SOFT_LABEL; import java.util.Objects; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.score.ScoreUtil; /** * This {@link Score} is based on 3 levels of int constraints: hard, medium and soft. * Hard constraints have priority over medium constraints. * Medium constraints have priority over soft constraints. * Hard constraints determine feasibility. * <p> * This class is immutable. * * @see Score */ public final class HardMediumSoftScore implements Score<HardMediumSoftScore> { public static final HardMediumSoftScore ZERO = new HardMediumSoftScore(0, 0, 0, 0); public static final HardMediumSoftScore ONE_HARD = new HardMediumSoftScore(0, 1, 0, 0); private static final HardMediumSoftScore MINUS_ONE_HARD = new HardMediumSoftScore(0, -1, 0, 0); public static final HardMediumSoftScore ONE_MEDIUM = new HardMediumSoftScore(0, 0, 1, 0); private static final HardMediumSoftScore MINUS_ONE_MEDIUM = new HardMediumSoftScore(0, 0, -1, 0); public static final HardMediumSoftScore ONE_SOFT = new HardMediumSoftScore(0, 0, 0, 1); private static final HardMediumSoftScore MINUS_ONE_SOFT = new HardMediumSoftScore(0, 0, 0, -1); public static HardMediumSoftScore parseScore(String scoreString) { String[] scoreTokens = ScoreUtil.parseScoreTokens(HardMediumSoftScore.class, scoreString, HARD_LABEL, MEDIUM_LABEL, SOFT_LABEL); int initScore = ScoreUtil.parseInitScore(HardMediumSoftScore.class, scoreString, scoreTokens[0]); int hardScore = ScoreUtil.parseLevelAsInt(HardMediumSoftScore.class, scoreString, scoreTokens[1]); int mediumScore = ScoreUtil.parseLevelAsInt(HardMediumSoftScore.class, scoreString, scoreTokens[2]); int softScore = ScoreUtil.parseLevelAsInt(HardMediumSoftScore.class, scoreString, scoreTokens[3]); return ofUninitialized(initScore, hardScore, mediumScore, softScore); } public static HardMediumSoftScore ofUninitialized(int initScore, int hardScore, int mediumScore, int softScore) { if (initScore == 0) { return of(hardScore, mediumScore, softScore); } return new HardMediumSoftScore(initScore, hardScore, mediumScore, softScore); } public static HardMediumSoftScore of(int hardScore, int mediumScore, int softScore) { if (hardScore == -1 && mediumScore == 0 && softScore == 0) { return MINUS_ONE_HARD; } else if (hardScore == 0) { if (mediumScore == -1 && softScore == 0) { return MINUS_ONE_MEDIUM; } else if (mediumScore == 0) { if (softScore == -1) { return MINUS_ONE_SOFT; } else if (softScore == 0) { return ZERO; } else if (softScore == 1) { return ONE_SOFT; } } else if (mediumScore == 1 && softScore == 0) { return ONE_MEDIUM; } } else if (hardScore == 1 && mediumScore == 0 && softScore == 0) { return ONE_HARD; } return new HardMediumSoftScore(0, hardScore, mediumScore, softScore); } public static HardMediumSoftScore ofHard(int hardScore) { return switch (hardScore) { case -1 -> MINUS_ONE_HARD; case 0 -> ZERO; case 1 -> ONE_HARD; default -> new HardMediumSoftScore(0, hardScore, 0, 0); }; } public static HardMediumSoftScore ofMedium(int mediumScore) { return switch (mediumScore) { case -1 -> MINUS_ONE_MEDIUM; case 0 -> ZERO; case 1 -> ONE_MEDIUM; default -> new HardMediumSoftScore(0, 0, mediumScore, 0); }; } public static HardMediumSoftScore ofSoft(int softScore) { return switch (softScore) { case -1 -> MINUS_ONE_SOFT; case 0 -> ZERO; case 1 -> ONE_SOFT; default -> new HardMediumSoftScore(0, 0, 0, softScore); }; } // ************************************************************************ // Fields // ************************************************************************ private final int initScore; private final int hardScore; private final int mediumScore; private final int softScore; /** * Private default constructor for default marshalling/unmarshalling of unknown frameworks that use reflection. * Such integration is always inferior to the specialized integration modules, such as * timefold-solver-jpa, timefold-solver-jackson, timefold-solver-jaxb, ... */ @SuppressWarnings("unused") private HardMediumSoftScore() { this(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE); } private HardMediumSoftScore(int initScore, int hardScore, int mediumScore, int softScore) { this.initScore = initScore; this.hardScore = hardScore; this.mediumScore = mediumScore; this.softScore = softScore; } @Override public int initScore() { return initScore; } /** * The total of the broken negative hard constraints and fulfilled positive hard constraints. * Their weight is included in the total. * The hard score is usually a negative number because most use cases only have negative constraints. * * @return higher is better, usually negative, 0 if no hard constraints are broken/fulfilled */ public int hardScore() { return hardScore; } /** * As defined by {@link #hardScore()}. * * @deprecated Use {@link #hardScore()} instead. */ @Deprecated(forRemoval = true) public int getHardScore() { return hardScore; } /** * The total of the broken negative medium constraints and fulfilled positive medium constraints. * Their weight is included in the total. * The medium score is usually a negative number because most use cases only have negative constraints. * <p> * In a normal score comparison, the medium score is irrelevant if the 2 scores don't have the same hard score. * * @return higher is better, usually negative, 0 if no medium constraints are broken/fulfilled */ public int mediumScore() { return mediumScore; } /** * As defined by {@link #mediumScore()}. * * @deprecated Use {@link #mediumScore()} instead. */ @Deprecated(forRemoval = true) public int getMediumScore() { return mediumScore; } /** * The total of the broken negative soft constraints and fulfilled positive soft constraints. * Their weight is included in the total. * The soft score is usually a negative number because most use cases only have negative constraints. * <p> * In a normal score comparison, the soft score is irrelevant if the 2 scores don't have the same hard and medium score. * * @return higher is better, usually negative, 0 if no soft constraints are broken/fulfilled */ public int softScore() { return softScore; } /** * As defined by {@link #softScore()}. * * @deprecated Use {@link #softScore()} instead. */ @Deprecated(forRemoval = true) public int getSoftScore() { return softScore; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public HardMediumSoftScore withInitScore(int newInitScore) { return ofUninitialized(newInitScore, hardScore, mediumScore, softScore); } /** * A {@link PlanningSolution} is feasible if it has no broken hard constraints. * * @return true if the {@link #hardScore()} is 0 or higher */ @Override public boolean isFeasible() { return initScore >= 0 && hardScore >= 0; } @Override public HardMediumSoftScore add(HardMediumSoftScore addend) { return ofUninitialized( initScore + addend.initScore(), hardScore + addend.hardScore(), mediumScore + addend.mediumScore(), softScore + addend.softScore()); } @Override public HardMediumSoftScore subtract(HardMediumSoftScore subtrahend) { return ofUninitialized( initScore - subtrahend.initScore(), hardScore - subtrahend.hardScore(), mediumScore - subtrahend.mediumScore(), softScore - subtrahend.softScore()); } @Override public HardMediumSoftScore multiply(double multiplicand) { return ofUninitialized( (int) Math.floor(initScore * multiplicand), (int) Math.floor(hardScore * multiplicand), (int) Math.floor(mediumScore * multiplicand), (int) Math.floor(softScore * multiplicand)); } @Override public HardMediumSoftScore divide(double divisor) { return ofUninitialized( (int) Math.floor(initScore / divisor), (int) Math.floor(hardScore / divisor), (int) Math.floor(mediumScore / divisor), (int) Math.floor(softScore / divisor)); } @Override public HardMediumSoftScore power(double exponent) { return ofUninitialized( (int) Math.floor(Math.pow(initScore, exponent)), (int) Math.floor(Math.pow(hardScore, exponent)), (int) Math.floor(Math.pow(mediumScore, exponent)), (int) Math.floor(Math.pow(softScore, exponent))); } @Override public HardMediumSoftScore abs() { return ofUninitialized(Math.abs(initScore), Math.abs(hardScore), Math.abs(mediumScore), Math.abs(softScore)); } @Override public HardMediumSoftScore zero() { return HardMediumSoftScore.ZERO; } @Override public Number[] toLevelNumbers() { return new Number[] { hardScore, mediumScore, softScore }; } @Override public boolean equals(Object o) { if (o instanceof HardMediumSoftScore other) { return initScore == other.initScore() && hardScore == other.hardScore() && mediumScore == other.mediumScore() && softScore == other.softScore(); } return false; } @Override public int hashCode() { return Objects.hash(initScore, hardScore, mediumScore, softScore); } @Override public int compareTo(HardMediumSoftScore other) { if (initScore != other.initScore()) { return Integer.compare(initScore, other.initScore()); } else if (hardScore != other.hardScore()) { return Integer.compare(hardScore, other.hardScore()); } else if (mediumScore != other.mediumScore()) { return Integer.compare(mediumScore, other.mediumScore()); } else { return Integer.compare(softScore, other.softScore()); } } @Override public String toShortString() { return ScoreUtil.buildShortString(this, n -> n.intValue() != 0, HARD_LABEL, MEDIUM_LABEL, SOFT_LABEL); } @Override public String toString() { return ScoreUtil.getInitPrefix(initScore) + hardScore + HARD_LABEL + "/" + mediumScore + MEDIUM_LABEL + "/" + softScore + SOFT_LABEL; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/hardmediumsoft/package-info.java
/** * Support for a {@link ai.timefold.solver.core.api.score.Score} with 3 score levels and {@code int} score weights. */ package ai.timefold.solver.core.api.score.buildin.hardmediumsoft;
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/hardmediumsoftbigdecimal/HardMediumSoftBigDecimalScore.java
package ai.timefold.solver.core.api.score.buildin.hardmediumsoftbigdecimal; import static ai.timefold.solver.core.impl.score.ScoreUtil.HARD_LABEL; import static ai.timefold.solver.core.impl.score.ScoreUtil.MEDIUM_LABEL; import static ai.timefold.solver.core.impl.score.ScoreUtil.SOFT_LABEL; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Objects; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.score.ScoreUtil; /** * This {@link Score} is based on 3 levels of {@link BigDecimal} constraints: hard, medium and soft. * Hard constraints have priority over medium constraints. * Medium constraints have priority over soft constraints. * Hard constraints determine feasibility. * <p> * This class is immutable. * * @see Score */ public final class HardMediumSoftBigDecimalScore implements Score<HardMediumSoftBigDecimalScore> { public static final HardMediumSoftBigDecimalScore ZERO = new HardMediumSoftBigDecimalScore(0, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO); public static final HardMediumSoftBigDecimalScore ONE_HARD = new HardMediumSoftBigDecimalScore(0, BigDecimal.ONE, BigDecimal.ZERO, BigDecimal.ZERO); private static final HardMediumSoftBigDecimalScore MINUS_ONE_HARD = new HardMediumSoftBigDecimalScore(0, BigDecimal.ONE.negate(), BigDecimal.ZERO, BigDecimal.ZERO); public static final HardMediumSoftBigDecimalScore ONE_MEDIUM = new HardMediumSoftBigDecimalScore(0, BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.ZERO); private static final HardMediumSoftBigDecimalScore MINUS_ONE_MEDIUM = new HardMediumSoftBigDecimalScore(0, BigDecimal.ZERO, BigDecimal.ONE.negate(), BigDecimal.ZERO); public static final HardMediumSoftBigDecimalScore ONE_SOFT = new HardMediumSoftBigDecimalScore(0, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ONE); private static final HardMediumSoftBigDecimalScore MINUS_ONE_SOFT = new HardMediumSoftBigDecimalScore(0, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ONE.negate()); public static HardMediumSoftBigDecimalScore parseScore(String scoreString) { String[] scoreTokens = ScoreUtil.parseScoreTokens(HardMediumSoftBigDecimalScore.class, scoreString, HARD_LABEL, MEDIUM_LABEL, SOFT_LABEL); int initScore = ScoreUtil.parseInitScore(HardMediumSoftBigDecimalScore.class, scoreString, scoreTokens[0]); BigDecimal hardScore = ScoreUtil.parseLevelAsBigDecimal(HardMediumSoftBigDecimalScore.class, scoreString, scoreTokens[1]); BigDecimal mediumScore = ScoreUtil.parseLevelAsBigDecimal(HardMediumSoftBigDecimalScore.class, scoreString, scoreTokens[2]); BigDecimal softScore = ScoreUtil.parseLevelAsBigDecimal(HardMediumSoftBigDecimalScore.class, scoreString, scoreTokens[3]); return ofUninitialized(initScore, hardScore, mediumScore, softScore); } public static HardMediumSoftBigDecimalScore ofUninitialized(int initScore, BigDecimal hardScore, BigDecimal mediumScore, BigDecimal softScore) { if (initScore == 0) { return of(hardScore, mediumScore, softScore); } return new HardMediumSoftBigDecimalScore(initScore, hardScore, mediumScore, softScore); } public static HardMediumSoftBigDecimalScore of(BigDecimal hardScore, BigDecimal mediumScore, BigDecimal softScore) { if (Objects.equals(hardScore, BigDecimal.ONE.negate()) && mediumScore.signum() == 0 && softScore.signum() == 0) { return MINUS_ONE_HARD; } else if (hardScore.signum() == 0) { if (Objects.equals(mediumScore, BigDecimal.ONE.negate()) && softScore.signum() == 0) { return MINUS_ONE_MEDIUM; } else if (mediumScore.signum() == 0) { if (Objects.equals(softScore, BigDecimal.ONE.negate())) { return MINUS_ONE_SOFT; } else if (softScore.signum() == 0) { return ZERO; } else if (Objects.equals(softScore, BigDecimal.ONE)) { return ONE_SOFT; } } else if (Objects.equals(mediumScore, BigDecimal.ONE) && softScore.signum() == 0) { return ONE_MEDIUM; } } else if (Objects.equals(hardScore, BigDecimal.ONE) && mediumScore.signum() == 0 && softScore.signum() == 0) { return ONE_HARD; } return new HardMediumSoftBigDecimalScore(0, hardScore, mediumScore, softScore); } public static HardMediumSoftBigDecimalScore ofHard(BigDecimal hardScore) { if (Objects.equals(hardScore, BigDecimal.ONE.negate())) { return MINUS_ONE_HARD; } else if (hardScore.signum() == 0) { return ZERO; } else if (Objects.equals(hardScore, BigDecimal.ONE)) { return ONE_HARD; } return new HardMediumSoftBigDecimalScore(0, hardScore, BigDecimal.ZERO, BigDecimal.ZERO); } public static HardMediumSoftBigDecimalScore ofMedium(BigDecimal mediumScore) { if (Objects.equals(mediumScore, BigDecimal.ONE.negate())) { return MINUS_ONE_MEDIUM; } else if (mediumScore.signum() == 0) { return ZERO; } else if (Objects.equals(mediumScore, BigDecimal.ONE)) { return ONE_MEDIUM; } return new HardMediumSoftBigDecimalScore(0, BigDecimal.ZERO, mediumScore, BigDecimal.ZERO); } public static HardMediumSoftBigDecimalScore ofSoft(BigDecimal softScore) { if (Objects.equals(softScore, BigDecimal.ONE.negate())) { return MINUS_ONE_SOFT; } else if (softScore.signum() == 0) { return ZERO; } else if (Objects.equals(softScore, BigDecimal.ONE)) { return ONE_SOFT; } return new HardMediumSoftBigDecimalScore(0, BigDecimal.ZERO, BigDecimal.ZERO, softScore); } // ************************************************************************ // Fields // ************************************************************************ private final int initScore; private final BigDecimal hardScore; private final BigDecimal mediumScore; private final BigDecimal softScore; /** * Private default constructor for default marshalling/unmarshalling of unknown frameworks that use reflection. * Such integration is always inferior to the specialized integration modules, such as * timefold-solver-jpa, timefold-solver-jackson, timefold-solver-jaxb, ... */ @SuppressWarnings("unused") private HardMediumSoftBigDecimalScore() { this(Integer.MIN_VALUE, null, null, null); } private HardMediumSoftBigDecimalScore(int initScore, BigDecimal hardScore, BigDecimal mediumScore, BigDecimal softScore) { this.initScore = initScore; this.hardScore = hardScore; this.mediumScore = mediumScore; this.softScore = softScore; } @Override public int initScore() { return initScore; } /** * The total of the broken negative hard constraints and fulfilled positive hard constraints. * Their weight is included in the total. * The hard score is usually a negative number because most use cases only have negative constraints. * * @return higher is better, usually negative, 0 if no hard constraints are broken/fulfilled */ public BigDecimal hardScore() { return hardScore; } /** * As defined by {@link #hardScore()}. * * @deprecated Use {@link #hardScore()} instead. */ @Deprecated(forRemoval = true) public BigDecimal getHardScore() { return hardScore; } /** * The total of the broken negative medium constraints and fulfilled positive medium constraints. * Their weight is included in the total. * The medium score is usually a negative number because most use cases only have negative constraints. * <p> * In a normal score comparison, the medium score is irrelevant if the 2 scores don't have the same hard score. * * @return higher is better, usually negative, 0 if no medium constraints are broken/fulfilled */ public BigDecimal mediumScore() { return mediumScore; } /** * As defined by {@link #mediumScore()}. * * @deprecated Use {@link #mediumScore()} instead. */ @Deprecated(forRemoval = true) public BigDecimal getMediumScore() { return mediumScore; } /** * The total of the broken negative soft constraints and fulfilled positive soft constraints. * Their weight is included in the total. * The soft score is usually a negative number because most use cases only have negative constraints. * <p> * In a normal score comparison, the soft score is irrelevant if the 2 scores don't have the same hard and medium score. * * @return higher is better, usually negative, 0 if no soft constraints are broken/fulfilled */ public BigDecimal softScore() { return softScore; } /** * As defined by {@link #softScore()}. * * @deprecated Use {@link #softScore()} instead. */ @Deprecated(forRemoval = true) public BigDecimal getSoftScore() { return softScore; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public HardMediumSoftBigDecimalScore withInitScore(int newInitScore) { return ofUninitialized(newInitScore, hardScore, mediumScore, softScore); } /** * A {@link PlanningSolution} is feasible if it has no broken hard constraints. * * @return true if the {@link #hardScore()} is 0 or higher */ @Override public boolean isFeasible() { return initScore >= 0 && hardScore.compareTo(BigDecimal.ZERO) >= 0; } @Override public HardMediumSoftBigDecimalScore add(HardMediumSoftBigDecimalScore addend) { return ofUninitialized( initScore + addend.initScore(), hardScore.add(addend.hardScore()), mediumScore.add(addend.mediumScore()), softScore.add(addend.softScore())); } @Override public HardMediumSoftBigDecimalScore subtract(HardMediumSoftBigDecimalScore subtrahend) { return ofUninitialized( initScore - subtrahend.initScore(), hardScore.subtract(subtrahend.hardScore()), mediumScore.subtract(subtrahend.mediumScore()), softScore.subtract(subtrahend.softScore())); } @Override public HardMediumSoftBigDecimalScore multiply(double multiplicand) { // Intentionally not taken "new BigDecimal(multiplicand, MathContext.UNLIMITED)" // because together with the floor rounding it gives unwanted behaviour BigDecimal multiplicandBigDecimal = BigDecimal.valueOf(multiplicand); // The (unspecified) scale/precision of the multiplicand should have no impact on the returned scale/precision return ofUninitialized( (int) Math.floor(initScore * multiplicand), hardScore.multiply(multiplicandBigDecimal).setScale(hardScore.scale(), RoundingMode.FLOOR), mediumScore.multiply(multiplicandBigDecimal).setScale(mediumScore.scale(), RoundingMode.FLOOR), softScore.multiply(multiplicandBigDecimal).setScale(softScore.scale(), RoundingMode.FLOOR)); } @Override public HardMediumSoftBigDecimalScore divide(double divisor) { BigDecimal divisorBigDecimal = BigDecimal.valueOf(divisor); // The (unspecified) scale/precision of the divisor should have no impact on the returned scale/precision return ofUninitialized( (int) Math.floor(initScore / divisor), hardScore.divide(divisorBigDecimal, hardScore.scale(), RoundingMode.FLOOR), mediumScore.divide(divisorBigDecimal, mediumScore.scale(), RoundingMode.FLOOR), softScore.divide(divisorBigDecimal, softScore.scale(), RoundingMode.FLOOR)); } @Override public HardMediumSoftBigDecimalScore power(double exponent) { BigDecimal exponentBigDecimal = BigDecimal.valueOf(exponent); // The (unspecified) scale/precision of the exponent should have no impact on the returned scale/precision // TODO FIXME remove .intValue() so non-integer exponents produce correct results // None of the normal Java libraries support BigDecimal.pow(BigDecimal) return ofUninitialized( (int) Math.floor(Math.pow(initScore, exponent)), hardScore.pow(exponentBigDecimal.intValue()).setScale(hardScore.scale(), RoundingMode.FLOOR), mediumScore.pow(exponentBigDecimal.intValue()).setScale(mediumScore.scale(), RoundingMode.FLOOR), softScore.pow(exponentBigDecimal.intValue()).setScale(softScore.scale(), RoundingMode.FLOOR)); } @Override public HardMediumSoftBigDecimalScore abs() { return ofUninitialized(Math.abs(initScore), hardScore.abs(), mediumScore.abs(), softScore.abs()); } @Override public HardMediumSoftBigDecimalScore zero() { return HardMediumSoftBigDecimalScore.ZERO; } @Override public Number[] toLevelNumbers() { return new Number[] { hardScore, mediumScore, softScore }; } @Override public boolean equals(Object o) { if (o instanceof HardMediumSoftBigDecimalScore other) { return initScore == other.initScore() && hardScore.stripTrailingZeros().equals(other.hardScore().stripTrailingZeros()) && mediumScore.stripTrailingZeros().equals(other.mediumScore().stripTrailingZeros()) && softScore.stripTrailingZeros().equals(other.softScore().stripTrailingZeros()); } return false; } @Override public int hashCode() { return Objects.hash(initScore, hardScore.stripTrailingZeros(), mediumScore.stripTrailingZeros(), softScore.stripTrailingZeros()); } @Override public int compareTo(HardMediumSoftBigDecimalScore other) { if (initScore != other.initScore()) { return Integer.compare(initScore, other.initScore()); } int hardScoreComparison = hardScore.compareTo(other.hardScore()); if (hardScoreComparison != 0) { return hardScoreComparison; } int mediumScoreComparison = mediumScore.compareTo(other.mediumScore()); if (mediumScoreComparison != 0) { return mediumScoreComparison; } else { return softScore.compareTo(other.softScore()); } } @Override public String toShortString() { return ScoreUtil.buildShortString(this, n -> ((BigDecimal) n).compareTo(BigDecimal.ZERO) != 0, HARD_LABEL, MEDIUM_LABEL, SOFT_LABEL); } @Override public String toString() { return ScoreUtil.getInitPrefix(initScore) + hardScore + HARD_LABEL + "/" + mediumScore + MEDIUM_LABEL + "/" + softScore + SOFT_LABEL; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/hardmediumsoftbigdecimal/package-info.java
/** * Support for a {@link ai.timefold.solver.core.api.score.Score} with 3 score levels and {@code BigDecimal} score weights. */ package ai.timefold.solver.core.api.score.buildin.hardmediumsoftbigdecimal;
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/hardmediumsoftlong/HardMediumSoftLongScore.java
package ai.timefold.solver.core.api.score.buildin.hardmediumsoftlong; import static ai.timefold.solver.core.impl.score.ScoreUtil.HARD_LABEL; import static ai.timefold.solver.core.impl.score.ScoreUtil.MEDIUM_LABEL; import static ai.timefold.solver.core.impl.score.ScoreUtil.SOFT_LABEL; import java.util.Objects; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.score.ScoreUtil; /** * This {@link Score} is based on 3 levels of long constraints: hard, medium and soft. * Hard constraints have priority over medium constraints. * Medium constraints have priority over soft constraints. * Hard constraints determine feasibility. * <p> * This class is immutable. * * @see Score */ public final class HardMediumSoftLongScore implements Score<HardMediumSoftLongScore> { public static final HardMediumSoftLongScore ZERO = new HardMediumSoftLongScore(0, 0L, 0L, 0L); public static final HardMediumSoftLongScore ONE_HARD = new HardMediumSoftLongScore(0, 1L, 0L, 0L); private static final HardMediumSoftLongScore MINUS_ONE_HARD = new HardMediumSoftLongScore(0, -1L, 0L, 0L); public static final HardMediumSoftLongScore ONE_MEDIUM = new HardMediumSoftLongScore(0, 0L, 1L, 0L); private static final HardMediumSoftLongScore MINUS_ONE_MEDIUM = new HardMediumSoftLongScore(0, 0L, -1L, 0L); public static final HardMediumSoftLongScore ONE_SOFT = new HardMediumSoftLongScore(0, 0L, 0L, 1L); private static final HardMediumSoftLongScore MINUS_ONE_SOFT = new HardMediumSoftLongScore(0, 0L, 0L, -1L); public static HardMediumSoftLongScore parseScore(String scoreString) { String[] scoreTokens = ScoreUtil.parseScoreTokens(HardMediumSoftLongScore.class, scoreString, HARD_LABEL, MEDIUM_LABEL, SOFT_LABEL); int initScore = ScoreUtil.parseInitScore(HardMediumSoftLongScore.class, scoreString, scoreTokens[0]); long hardScore = ScoreUtil.parseLevelAsLong(HardMediumSoftLongScore.class, scoreString, scoreTokens[1]); long mediumScore = ScoreUtil.parseLevelAsLong(HardMediumSoftLongScore.class, scoreString, scoreTokens[2]); long softScore = ScoreUtil.parseLevelAsLong(HardMediumSoftLongScore.class, scoreString, scoreTokens[3]); return ofUninitialized(initScore, hardScore, mediumScore, softScore); } public static HardMediumSoftLongScore ofUninitialized(int initScore, long hardScore, long mediumScore, long softScore) { if (initScore == 0) { return of(hardScore, mediumScore, softScore); } return new HardMediumSoftLongScore(initScore, hardScore, mediumScore, softScore); } public static HardMediumSoftLongScore of(long hardScore, long mediumScore, long softScore) { if (hardScore == -1L && mediumScore == 0L && softScore == 0L) { return MINUS_ONE_HARD; } else if (hardScore == 0L) { if (mediumScore == -1L && softScore == 0L) { return MINUS_ONE_MEDIUM; } else if (mediumScore == 0L) { if (softScore == -1L) { return MINUS_ONE_SOFT; } else if (softScore == 0L) { return ZERO; } else if (softScore == 1L) { return ONE_SOFT; } } else if (mediumScore == 1L && softScore == 0L) { return ONE_MEDIUM; } } else if (hardScore == 1L && mediumScore == 0L && softScore == 0L) { return ONE_HARD; } return new HardMediumSoftLongScore(0, hardScore, mediumScore, softScore); } public static HardMediumSoftLongScore ofHard(long hardScore) { if (hardScore == -1L) { return MINUS_ONE_HARD; } else if (hardScore == 0L) { return ZERO; } else if (hardScore == 1L) { return ONE_HARD; } return new HardMediumSoftLongScore(0, hardScore, 0L, 0L); } public static HardMediumSoftLongScore ofMedium(long mediumScore) { if (mediumScore == -1L) { return MINUS_ONE_MEDIUM; } else if (mediumScore == 0L) { return ZERO; } else if (mediumScore == 1L) { return ONE_MEDIUM; } return new HardMediumSoftLongScore(0, 0L, mediumScore, 0L); } public static HardMediumSoftLongScore ofSoft(long softScore) { if (softScore == -1L) { return MINUS_ONE_SOFT; } else if (softScore == 0L) { return ZERO; } else if (softScore == 1L) { return ONE_SOFT; } return new HardMediumSoftLongScore(0, 0L, 0L, softScore); } // ************************************************************************ // Fields // ************************************************************************ private final int initScore; private final long hardScore; private final long mediumScore; private final long softScore; /** * Private default constructor for default marshalling/unmarshalling of unknown frameworks that use reflection. * Such integration is always inferior to the specialized integration modules, such as * timefold-solver-jpa, timefold-solver-jackson, timefold-solver-jaxb, ... */ @SuppressWarnings("unused") private HardMediumSoftLongScore() { this(Integer.MIN_VALUE, Long.MIN_VALUE, Long.MIN_VALUE, Long.MIN_VALUE); } private HardMediumSoftLongScore(int initScore, long hardScore, long mediumScore, long softScore) { this.initScore = initScore; this.hardScore = hardScore; this.mediumScore = mediumScore; this.softScore = softScore; } @Override public int initScore() { return initScore; } /** * The total of the broken negative hard constraints and fulfilled positive hard constraints. * Their weight is included in the total. * The hard score is usually a negative number because most use cases only have negative constraints. * * @return higher is better, usually negative, 0 if no hard constraints are broken/fulfilled */ public long hardScore() { return hardScore; } /** * As defined by {@link #hardScore()}. * * @deprecated Use {@link #hardScore()} instead. */ @Deprecated(forRemoval = true) public long getHardScore() { return hardScore; } /** * The total of the broken negative medium constraints and fulfilled positive medium constraints. * Their weight is included in the total. * The medium score is usually a negative number because most use cases only have negative constraints. * <p> * In a normal score comparison, the medium score is irrelevant if the 2 scores don't have the same hard score. * * @return higher is better, usually negative, 0 if no medium constraints are broken/fulfilled */ public long mediumScore() { return mediumScore; } /** * As defined by {@link #mediumScore()}. * * @deprecated Use {@link #mediumScore()} instead. */ @Deprecated(forRemoval = true) public long getMediumScore() { return mediumScore; } /** * The total of the broken negative soft constraints and fulfilled positive soft constraints. * Their weight is included in the total. * The soft score is usually a negative number because most use cases only have negative constraints. * <p> * In a normal score comparison, the soft score is irrelevant if the 2 scores don't have the same hard and medium score. * * @return higher is better, usually negative, 0 if no soft constraints are broken/fulfilled */ public long softScore() { return softScore; } /** * As defined by {@link #softScore()}. * * @deprecated Use {@link #softScore()} instead. */ @Deprecated(forRemoval = true) public long getSoftScore() { return softScore; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public HardMediumSoftLongScore withInitScore(int newInitScore) { return ofUninitialized(newInitScore, hardScore, mediumScore, softScore); } /** * A {@link PlanningSolution} is feasible if it has no broken hard constraints. * * @return true if the {@link #hardScore()} is 0 or higher */ @Override public boolean isFeasible() { return initScore >= 0 && hardScore >= 0L; } @Override public HardMediumSoftLongScore add(HardMediumSoftLongScore addend) { return ofUninitialized( initScore + addend.initScore(), hardScore + addend.hardScore(), mediumScore + addend.mediumScore(), softScore + addend.softScore()); } @Override public HardMediumSoftLongScore subtract(HardMediumSoftLongScore subtrahend) { return ofUninitialized( initScore - subtrahend.initScore(), hardScore - subtrahend.hardScore(), mediumScore - subtrahend.mediumScore(), softScore - subtrahend.softScore()); } @Override public HardMediumSoftLongScore multiply(double multiplicand) { return ofUninitialized( (int) Math.floor(initScore * multiplicand), (long) Math.floor(hardScore * multiplicand), (long) Math.floor(mediumScore * multiplicand), (long) Math.floor(softScore * multiplicand)); } @Override public HardMediumSoftLongScore divide(double divisor) { return ofUninitialized( (int) Math.floor(initScore / divisor), (long) Math.floor(hardScore / divisor), (long) Math.floor(mediumScore / divisor), (long) Math.floor(softScore / divisor)); } @Override public HardMediumSoftLongScore power(double exponent) { return ofUninitialized( (int) Math.floor(Math.pow(initScore, exponent)), (long) Math.floor(Math.pow(hardScore, exponent)), (long) Math.floor(Math.pow(mediumScore, exponent)), (long) Math.floor(Math.pow(softScore, exponent))); } @Override public HardMediumSoftLongScore abs() { return ofUninitialized(Math.abs(initScore), Math.abs(hardScore), Math.abs(mediumScore), Math.abs(softScore)); } @Override public HardMediumSoftLongScore zero() { return HardMediumSoftLongScore.ZERO; } @Override public Number[] toLevelNumbers() { return new Number[] { hardScore, mediumScore, softScore }; } @Override public boolean equals(Object o) { if (o instanceof HardMediumSoftLongScore other) { return initScore == other.initScore() && hardScore == other.hardScore() && mediumScore == other.mediumScore() && softScore == other.softScore(); } return false; } @Override public int hashCode() { return Objects.hash(initScore, hardScore, mediumScore, softScore); } @Override public int compareTo(HardMediumSoftLongScore other) { if (initScore != other.initScore()) { return Integer.compare(initScore, other.initScore()); } else if (hardScore != other.hardScore()) { return Long.compare(hardScore, other.hardScore()); } else if (mediumScore != other.mediumScore()) { return Long.compare(mediumScore, other.mediumScore()); } else { return Long.compare(softScore, other.softScore()); } } @Override public String toShortString() { return ScoreUtil.buildShortString(this, n -> n.longValue() != 0L, HARD_LABEL, MEDIUM_LABEL, SOFT_LABEL); } @Override public String toString() { return ScoreUtil.getInitPrefix(initScore) + hardScore + HARD_LABEL + "/" + mediumScore + MEDIUM_LABEL + "/" + softScore + SOFT_LABEL; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/hardmediumsoftlong/package-info.java
/** * Support for a {@link ai.timefold.solver.core.api.score.Score} with 3 score levels and {@code long} score weights. */ package ai.timefold.solver.core.api.score.buildin.hardmediumsoftlong;
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/hardsoft/HardSoftScore.java
package ai.timefold.solver.core.api.score.buildin.hardsoft; import static ai.timefold.solver.core.impl.score.ScoreUtil.HARD_LABEL; import static ai.timefold.solver.core.impl.score.ScoreUtil.SOFT_LABEL; import static ai.timefold.solver.core.impl.score.ScoreUtil.parseInitScore; import static ai.timefold.solver.core.impl.score.ScoreUtil.parseLevelAsInt; import static ai.timefold.solver.core.impl.score.ScoreUtil.parseScoreTokens; import java.util.Objects; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.score.ScoreUtil; /** * This {@link Score} is based on 2 levels of int constraints: hard and soft. * Hard constraints have priority over soft constraints. * Hard constraints determine feasibility. * <p> * This class is immutable. * * @see Score */ public final class HardSoftScore implements Score<HardSoftScore> { public static final HardSoftScore ZERO = new HardSoftScore(0, 0, 0); public static final HardSoftScore ONE_HARD = new HardSoftScore(0, 1, 0); public static final HardSoftScore ONE_SOFT = new HardSoftScore(0, 0, 1); private static final HardSoftScore MINUS_ONE_SOFT = new HardSoftScore(0, 0, -1); private static final HardSoftScore MINUS_ONE_HARD = new HardSoftScore(0, -1, 0); public static HardSoftScore parseScore(String scoreString) { String[] scoreTokens = parseScoreTokens(HardSoftScore.class, scoreString, HARD_LABEL, SOFT_LABEL); int initScore = parseInitScore(HardSoftScore.class, scoreString, scoreTokens[0]); int hardScore = parseLevelAsInt(HardSoftScore.class, scoreString, scoreTokens[1]); int softScore = parseLevelAsInt(HardSoftScore.class, scoreString, scoreTokens[2]); return ofUninitialized(initScore, hardScore, softScore); } public static HardSoftScore ofUninitialized(int initScore, int hardScore, int softScore) { if (initScore == 0) { return of(hardScore, softScore); } return new HardSoftScore(initScore, hardScore, softScore); } public static HardSoftScore of(int hardScore, int softScore) { // Optimization for frequently seen values. if (hardScore == 0) { if (softScore == -1) { return MINUS_ONE_SOFT; } else if (softScore == 0) { return ZERO; } else if (softScore == 1) { return ONE_SOFT; } } else if (softScore == 0) { if (hardScore == 1) { return ONE_HARD; } else if (hardScore == -1) { return MINUS_ONE_HARD; } } // Every other case is constructed. return new HardSoftScore(0, hardScore, softScore); } public static HardSoftScore ofHard(int hardScore) { // Optimization for frequently seen values. if (hardScore == -1) { return MINUS_ONE_HARD; } else if (hardScore == 0) { return ZERO; } else if (hardScore == 1) { return ONE_HARD; } // Every other case is constructed. return new HardSoftScore(0, hardScore, 0); } public static HardSoftScore ofSoft(int softScore) { // Optimization for frequently seen values. if (softScore == -1) { return MINUS_ONE_SOFT; } else if (softScore == 0) { return ZERO; } else if (softScore == 1) { return ONE_SOFT; } // Every other case is constructed. return new HardSoftScore(0, 0, softScore); } // ************************************************************************ // Fields // ************************************************************************ private final int initScore; private final int hardScore; private final int softScore; /** * Private default constructor for default marshalling/unmarshalling of unknown frameworks that use reflection. * Such integration is always inferior to the specialized integration modules, such as * timefold-solver-jpa, timefold-solver-jackson, timefold-solver-jaxb, ... */ @SuppressWarnings("unused") private HardSoftScore() { this(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE); } private HardSoftScore(int initScore, int hardScore, int softScore) { this.initScore = initScore; this.hardScore = hardScore; this.softScore = softScore; } @Override public int initScore() { return initScore; } /** * The total of the broken negative hard constraints and fulfilled positive hard constraints. * Their weight is included in the total. * The hard score is usually a negative number because most use cases only have negative constraints. * * @return higher is better, usually negative, 0 if no hard constraints are broken/fulfilled */ public int hardScore() { return hardScore; } /** * As defined by {@link #hardScore()}. * * @deprecated Use {@link #hardScore()} instead. */ @Deprecated(forRemoval = true) public int getHardScore() { return hardScore; } /** * The total of the broken negative soft constraints and fulfilled positive soft constraints. * Their weight is included in the total. * The soft score is usually a negative number because most use cases only have negative constraints. * <p> * In a normal score comparison, the soft score is irrelevant if the 2 scores don't have the same hard score. * * @return higher is better, usually negative, 0 if no soft constraints are broken/fulfilled */ public int softScore() { return softScore; } /** * As defined by {@link #softScore()}. * * @deprecated Use {@link #softScore()} instead. */ @Deprecated(forRemoval = true) public int getSoftScore() { return softScore; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public HardSoftScore withInitScore(int newInitScore) { return ofUninitialized(newInitScore, hardScore, softScore); } @Override public boolean isFeasible() { return initScore >= 0 && hardScore >= 0; } @Override public HardSoftScore add(HardSoftScore addend) { return ofUninitialized( initScore + addend.initScore(), hardScore + addend.hardScore(), softScore + addend.softScore()); } @Override public HardSoftScore subtract(HardSoftScore subtrahend) { return ofUninitialized( initScore - subtrahend.initScore(), hardScore - subtrahend.hardScore(), softScore - subtrahend.softScore()); } @Override public HardSoftScore multiply(double multiplicand) { return ofUninitialized( (int) Math.floor(initScore * multiplicand), (int) Math.floor(hardScore * multiplicand), (int) Math.floor(softScore * multiplicand)); } @Override public HardSoftScore divide(double divisor) { return ofUninitialized( (int) Math.floor(initScore / divisor), (int) Math.floor(hardScore / divisor), (int) Math.floor(softScore / divisor)); } @Override public HardSoftScore power(double exponent) { return ofUninitialized( (int) Math.floor(Math.pow(initScore, exponent)), (int) Math.floor(Math.pow(hardScore, exponent)), (int) Math.floor(Math.pow(softScore, exponent))); } @Override public HardSoftScore abs() { return ofUninitialized(Math.abs(initScore), Math.abs(hardScore), Math.abs(softScore)); } @Override public HardSoftScore zero() { return ZERO; } @Override public Number[] toLevelNumbers() { return new Number[] { hardScore, softScore }; } @Override public boolean equals(Object o) { if (o instanceof HardSoftScore other) { return initScore == other.initScore() && hardScore == other.hardScore() && softScore == other.softScore(); } return false; } @Override public int hashCode() { return Objects.hash(initScore, hardScore, softScore); } @Override public int compareTo(HardSoftScore other) { if (initScore != other.initScore()) { return Integer.compare(initScore, other.initScore()); } else if (hardScore != other.hardScore()) { return Integer.compare(hardScore, other.hardScore()); } else { return Integer.compare(softScore, other.softScore()); } } @Override public String toShortString() { return ScoreUtil.buildShortString(this, n -> n.intValue() != 0, HARD_LABEL, SOFT_LABEL); } @Override public String toString() { return ScoreUtil.getInitPrefix(initScore) + hardScore + HARD_LABEL + "/" + softScore + SOFT_LABEL; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/hardsoft/package-info.java
/** * Support for a {@link ai.timefold.solver.core.api.score.Score} with 2 score levels and {@code int} score weights. */ package ai.timefold.solver.core.api.score.buildin.hardsoft;
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/hardsoftbigdecimal/HardSoftBigDecimalScore.java
package ai.timefold.solver.core.api.score.buildin.hardsoftbigdecimal; import static ai.timefold.solver.core.impl.score.ScoreUtil.HARD_LABEL; import static ai.timefold.solver.core.impl.score.ScoreUtil.SOFT_LABEL; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Objects; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.score.ScoreUtil; /** * This {@link Score} is based on 2 levels of {@link BigDecimal} constraints: hard and soft. * Hard constraints have priority over soft constraints. * Hard constraints determine feasibility. * <p> * This class is immutable. * * @see Score */ public final class HardSoftBigDecimalScore implements Score<HardSoftBigDecimalScore> { public static final HardSoftBigDecimalScore ZERO = new HardSoftBigDecimalScore(0, BigDecimal.ZERO, BigDecimal.ZERO); public static final HardSoftBigDecimalScore ONE_HARD = new HardSoftBigDecimalScore(0, BigDecimal.ONE, BigDecimal.ZERO); public static final HardSoftBigDecimalScore ONE_SOFT = new HardSoftBigDecimalScore(0, BigDecimal.ZERO, BigDecimal.ONE); public static HardSoftBigDecimalScore parseScore(String scoreString) { String[] scoreTokens = ScoreUtil.parseScoreTokens(HardSoftBigDecimalScore.class, scoreString, HARD_LABEL, SOFT_LABEL); int initScore = ScoreUtil.parseInitScore(HardSoftBigDecimalScore.class, scoreString, scoreTokens[0]); BigDecimal hardScore = ScoreUtil.parseLevelAsBigDecimal(HardSoftBigDecimalScore.class, scoreString, scoreTokens[1]); BigDecimal softScore = ScoreUtil.parseLevelAsBigDecimal(HardSoftBigDecimalScore.class, scoreString, scoreTokens[2]); return ofUninitialized(initScore, hardScore, softScore); } public static HardSoftBigDecimalScore ofUninitialized(int initScore, BigDecimal hardScore, BigDecimal softScore) { if (initScore == 0) { return of(hardScore, softScore); } return new HardSoftBigDecimalScore(initScore, hardScore, softScore); } public static HardSoftBigDecimalScore of(BigDecimal hardScore, BigDecimal softScore) { // Optimization for frequently seen values. if (hardScore.signum() == 0) { if (softScore.signum() == 0) { return ZERO; } else if (Objects.equals(softScore, BigDecimal.ONE)) { return ONE_SOFT; } } else if (Objects.equals(hardScore, BigDecimal.ONE) && softScore.signum() == 0) { return ONE_HARD; } // Every other case is constructed. return new HardSoftBigDecimalScore(0, hardScore, softScore); } public static HardSoftBigDecimalScore ofHard(BigDecimal hardScore) { // Optimization for frequently seen values. if (hardScore.signum() == 0) { return ZERO; } else if (Objects.equals(hardScore, BigDecimal.ONE)) { return ONE_HARD; } // Every other case is constructed. return new HardSoftBigDecimalScore(0, hardScore, BigDecimal.ZERO); } public static HardSoftBigDecimalScore ofSoft(BigDecimal softScore) { // Optimization for frequently seen values. if (softScore.signum() == 0) { return ZERO; } else if (Objects.equals(softScore, BigDecimal.ONE)) { return ONE_SOFT; } // Every other case is constructed. return new HardSoftBigDecimalScore(0, BigDecimal.ZERO, softScore); } // ************************************************************************ // Fields // ************************************************************************ private final int initScore; private final BigDecimal hardScore; private final BigDecimal softScore; /** * Private default constructor for default marshalling/unmarshalling of unknown frameworks that use reflection. * Such integration is always inferior to the specialized integration modules, such as * timefold-solver-jpa, timefold-solver-jackson, timefold-solver-jaxb, ... */ @SuppressWarnings("unused") private HardSoftBigDecimalScore() { this(Integer.MIN_VALUE, null, null); } private HardSoftBigDecimalScore(int initScore, BigDecimal hardScore, BigDecimal softScore) { this.initScore = initScore; this.hardScore = hardScore; this.softScore = softScore; } @Override public int initScore() { return initScore; } /** * The total of the broken negative hard constraints and fulfilled positive hard constraints. * Their weight is included in the total. * The hard score is usually a negative number because most use cases only have negative constraints. * * @return higher is better, usually negative, 0 if no hard constraints are broken/fulfilled */ public BigDecimal hardScore() { return hardScore; } /** * As defined by {@link #hardScore()}. * * @deprecated Use {@link #hardScore()} instead. */ @Deprecated(forRemoval = true) public BigDecimal getHardScore() { return hardScore; } /** * The total of the broken negative soft constraints and fulfilled positive soft constraints. * Their weight is included in the total. * The soft score is usually a negative number because most use cases only have negative constraints. * <p> * In a normal score comparison, the soft score is irrelevant if the 2 scores don't have the same hard score. * * @return higher is better, usually negative, 0 if no soft constraints are broken/fulfilled */ public BigDecimal softScore() { return softScore; } /** * As defined by {@link #softScore()}. * * @deprecated Use {@link #softScore()} instead. */ @Deprecated(forRemoval = true) public BigDecimal getSoftScore() { return softScore; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public HardSoftBigDecimalScore withInitScore(int newInitScore) { return new HardSoftBigDecimalScore(newInitScore, hardScore, softScore); } @Override public boolean isFeasible() { return initScore >= 0 && hardScore.signum() >= 0; } @Override public HardSoftBigDecimalScore add(HardSoftBigDecimalScore addend) { return ofUninitialized( initScore + addend.initScore(), hardScore.add(addend.hardScore()), softScore.add(addend.softScore())); } @Override public HardSoftBigDecimalScore subtract(HardSoftBigDecimalScore subtrahend) { return ofUninitialized( initScore - subtrahend.initScore(), hardScore.subtract(subtrahend.hardScore()), softScore.subtract(subtrahend.softScore())); } @Override public HardSoftBigDecimalScore multiply(double multiplicand) { // Intentionally not taken "new BigDecimal(multiplicand, MathContext.UNLIMITED)" // because together with the floor rounding it gives unwanted behaviour BigDecimal multiplicandBigDecimal = BigDecimal.valueOf(multiplicand); // The (unspecified) scale/precision of the multiplicand should have no impact on the returned scale/precision return ofUninitialized( (int) Math.floor(initScore * multiplicand), hardScore.multiply(multiplicandBigDecimal).setScale(hardScore.scale(), RoundingMode.FLOOR), softScore.multiply(multiplicandBigDecimal).setScale(softScore.scale(), RoundingMode.FLOOR)); } @Override public HardSoftBigDecimalScore divide(double divisor) { // Intentionally not taken "new BigDecimal(multiplicand, MathContext.UNLIMITED)" // because together with the floor rounding it gives unwanted behaviour BigDecimal divisorBigDecimal = BigDecimal.valueOf(divisor); // The (unspecified) scale/precision of the divisor should have no impact on the returned scale/precision return ofUninitialized( (int) Math.floor(initScore / divisor), hardScore.divide(divisorBigDecimal, hardScore.scale(), RoundingMode.FLOOR), softScore.divide(divisorBigDecimal, softScore.scale(), RoundingMode.FLOOR)); } @Override public HardSoftBigDecimalScore power(double exponent) { // Intentionally not taken "new BigDecimal(multiplicand, MathContext.UNLIMITED)" // because together with the floor rounding it gives unwanted behaviour BigDecimal exponentBigDecimal = BigDecimal.valueOf(exponent); // The (unspecified) scale/precision of the exponent should have no impact on the returned scale/precision // TODO FIXME remove .intValue() so non-integer exponents produce correct results // None of the normal Java libraries support BigDecimal.pow(BigDecimal) return ofUninitialized( (int) Math.floor(Math.pow(initScore, exponent)), hardScore.pow(exponentBigDecimal.intValue()).setScale(hardScore.scale(), RoundingMode.FLOOR), softScore.pow(exponentBigDecimal.intValue()).setScale(softScore.scale(), RoundingMode.FLOOR)); } @Override public HardSoftBigDecimalScore abs() { return ofUninitialized(Math.abs(initScore), hardScore.abs(), softScore.abs()); } @Override public HardSoftBigDecimalScore zero() { return ZERO; } @Override public Number[] toLevelNumbers() { return new Number[] { hardScore, softScore }; } @Override public boolean equals(Object o) { if (o instanceof HardSoftBigDecimalScore other) { return initScore == other.initScore() && hardScore.stripTrailingZeros().equals(other.hardScore().stripTrailingZeros()) && softScore.stripTrailingZeros().equals(other.softScore().stripTrailingZeros()); } return false; } @Override public int hashCode() { return Objects.hash(initScore, hardScore.stripTrailingZeros(), softScore.stripTrailingZeros()); } @Override public int compareTo(HardSoftBigDecimalScore other) { if (initScore != other.initScore()) { return Integer.compare(initScore, other.initScore()); } int hardScoreComparison = hardScore.compareTo(other.hardScore()); if (hardScoreComparison != 0) { return hardScoreComparison; } else { return softScore.compareTo(other.softScore()); } } @Override public String toShortString() { return ScoreUtil.buildShortString(this, n -> ((BigDecimal) n).compareTo(BigDecimal.ZERO) != 0, HARD_LABEL, SOFT_LABEL); } @Override public String toString() { return ScoreUtil.getInitPrefix(initScore) + hardScore + HARD_LABEL + "/" + softScore + SOFT_LABEL; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/hardsoftbigdecimal/package-info.java
/** * Support for a {@link ai.timefold.solver.core.api.score.Score} with 2 score levels and {@link java.math.BigDecimal} score * weights. */ package ai.timefold.solver.core.api.score.buildin.hardsoftbigdecimal;
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/hardsoftlong/HardSoftLongScore.java
package ai.timefold.solver.core.api.score.buildin.hardsoftlong; import static ai.timefold.solver.core.impl.score.ScoreUtil.HARD_LABEL; import static ai.timefold.solver.core.impl.score.ScoreUtil.SOFT_LABEL; import java.util.Objects; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.score.ScoreUtil; /** * This {@link Score} is based on 2 levels of long constraints: hard and soft. * Hard constraints have priority over soft constraints. * Hard constraints determine feasibility. * <p> * This class is immutable. * * @see Score */ public final class HardSoftLongScore implements Score<HardSoftLongScore> { public static final HardSoftLongScore ZERO = new HardSoftLongScore(0, 0L, 0L); public static final HardSoftLongScore ONE_HARD = new HardSoftLongScore(0, 1L, 0L); public static final HardSoftLongScore ONE_SOFT = new HardSoftLongScore(0, 0L, 1L); private static final HardSoftLongScore MINUS_ONE_SOFT = new HardSoftLongScore(0, 0L, -1L); private static final HardSoftLongScore MINUS_ONE_HARD = new HardSoftLongScore(0, -1L, 0L); public static HardSoftLongScore parseScore(String scoreString) { String[] scoreTokens = ScoreUtil.parseScoreTokens(HardSoftLongScore.class, scoreString, HARD_LABEL, SOFT_LABEL); int initScore = ScoreUtil.parseInitScore(HardSoftLongScore.class, scoreString, scoreTokens[0]); long hardScore = ScoreUtil.parseLevelAsLong(HardSoftLongScore.class, scoreString, scoreTokens[1]); long softScore = ScoreUtil.parseLevelAsLong(HardSoftLongScore.class, scoreString, scoreTokens[2]); return ofUninitialized(initScore, hardScore, softScore); } public static HardSoftLongScore ofUninitialized(int initScore, long hardScore, long softScore) { if (initScore == 0) { return of(hardScore, softScore); } return new HardSoftLongScore(initScore, hardScore, softScore); } public static HardSoftLongScore of(long hardScore, long softScore) { // Optimization for frequently seen values. if (hardScore == 0L) { if (softScore == -1L) { return MINUS_ONE_SOFT; } else if (softScore == 0L) { return ZERO; } else if (softScore == 1L) { return ONE_SOFT; } } else if (softScore == 0L) { if (hardScore == 1L) { return ONE_HARD; } else if (hardScore == -1L) { return MINUS_ONE_HARD; } } // Every other case is constructed. return new HardSoftLongScore(0, hardScore, softScore); } public static HardSoftLongScore ofHard(long hardScore) { // Optimization for frequently seen values. if (hardScore == -1L) { return MINUS_ONE_HARD; } else if (hardScore == 0L) { return ZERO; } else if (hardScore == 1L) { return ONE_HARD; } // Every other case is constructed. return new HardSoftLongScore(0, hardScore, 0L); } public static HardSoftLongScore ofSoft(long softScore) { // Optimization for frequently seen values. if (softScore == -1L) { return MINUS_ONE_SOFT; } else if (softScore == 0L) { return ZERO; } else if (softScore == 1L) { return ONE_SOFT; } // Every other case is constructed. return new HardSoftLongScore(0, 0L, softScore); } // ************************************************************************ // Fields // ************************************************************************ private final int initScore; private final long hardScore; private final long softScore; /** * Private default constructor for default marshalling/unmarshalling of unknown frameworks that use reflection. * Such integration is always inferior to the specialized integration modules, such as * timefold-solver-jpa, timefold-solver-jackson, timefold-solver-jaxb, ... */ @SuppressWarnings("unused") private HardSoftLongScore() { this(Integer.MIN_VALUE, Long.MIN_VALUE, Long.MIN_VALUE); } private HardSoftLongScore(int initScore, long hardScore, long softScore) { this.initScore = initScore; this.hardScore = hardScore; this.softScore = softScore; } @Override public int initScore() { return initScore; } /** * The total of the broken negative hard constraints and fulfilled positive hard constraints. * Their weight is included in the total. * The hard score is usually a negative number because most use cases only have negative constraints. * * @return higher is better, usually negative, 0 if no hard constraints are broken/fulfilled */ public long hardScore() { return hardScore; } /** * As defined by {@link #hardScore()}. * * @deprecated Use {@link #hardScore()} instead. */ @Deprecated(forRemoval = true) public long getHardScore() { return hardScore; } /** * The total of the broken negative soft constraints and fulfilled positive soft constraints. * Their weight is included in the total. * The soft score is usually a negative number because most use cases only have negative constraints. * <p> * In a normal score comparison, the soft score is irrelevant if the 2 scores don't have the same hard score. * * @return higher is better, usually negative, 0 if no soft constraints are broken/fulfilled */ public long softScore() { return softScore; } /** * As defined by {@link #softScore()}. * * @deprecated Use {@link #softScore()} instead. */ @Deprecated(forRemoval = true) public long getSoftScore() { return softScore; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public HardSoftLongScore withInitScore(int newInitScore) { return ofUninitialized(newInitScore, hardScore, softScore); } @Override public boolean isFeasible() { return initScore >= 0 && hardScore >= 0L; } @Override public HardSoftLongScore add(HardSoftLongScore addend) { return ofUninitialized( initScore + addend.initScore(), hardScore + addend.hardScore(), softScore + addend.softScore()); } @Override public HardSoftLongScore subtract(HardSoftLongScore subtrahend) { return ofUninitialized( initScore - subtrahend.initScore(), hardScore - subtrahend.hardScore(), softScore - subtrahend.softScore()); } @Override public HardSoftLongScore multiply(double multiplicand) { return ofUninitialized( (int) Math.floor(initScore * multiplicand), (long) Math.floor(hardScore * multiplicand), (long) Math.floor(softScore * multiplicand)); } @Override public HardSoftLongScore divide(double divisor) { return ofUninitialized( (int) Math.floor(initScore / divisor), (long) Math.floor(hardScore / divisor), (long) Math.floor(softScore / divisor)); } @Override public HardSoftLongScore power(double exponent) { return ofUninitialized( (int) Math.floor(Math.pow(initScore, exponent)), (long) Math.floor(Math.pow(hardScore, exponent)), (long) Math.floor(Math.pow(softScore, exponent))); } @Override public HardSoftLongScore abs() { return ofUninitialized(Math.abs(initScore), Math.abs(hardScore), Math.abs(softScore)); } @Override public HardSoftLongScore zero() { return ZERO; } @Override public Number[] toLevelNumbers() { return new Number[] { hardScore, softScore }; } @Override public boolean equals(Object o) { if (o instanceof HardSoftLongScore other) { return initScore == other.initScore() && hardScore == other.hardScore() && softScore == other.softScore(); } return false; } @Override public int hashCode() { return Objects.hash(initScore, hardScore, softScore); } @Override public int compareTo(HardSoftLongScore other) { if (initScore != other.initScore()) { return Integer.compare(initScore, other.initScore()); } else if (hardScore != other.hardScore()) { return Long.compare(hardScore, other.hardScore()); } else { return Long.compare(softScore, other.softScore()); } } @Override public String toShortString() { return ScoreUtil.buildShortString(this, n -> n.longValue() != 0L, HARD_LABEL, SOFT_LABEL); } @Override public String toString() { return ScoreUtil.getInitPrefix(initScore) + hardScore + HARD_LABEL + "/" + softScore + SOFT_LABEL; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/api/score/buildin/hardsoftlong/package-info.java
/** * Support for a {@link ai.timefold.solver.core.api.score.Score} with 2 score levels and {@code long} score weights. */ package ai.timefold.solver.core.api.score.buildin.hardsoftlong;