index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/DefaultSolverJob.java | package ai.timefold.solver.core.impl.solver;
import java.time.Duration;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.solver.ProblemSizeStatistics;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.api.solver.SolverJob;
import ai.timefold.solver.core.api.solver.SolverStatus;
import ai.timefold.solver.core.api.solver.change.ProblemChange;
import ai.timefold.solver.core.api.solver.event.BestSolutionChangedEvent;
import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleListenerAdapter;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.termination.Termination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @param <ProblemId_> the ID type of submitted problem, such as {@link Long} or {@link UUID}.
*/
public final class DefaultSolverJob<Solution_, ProblemId_> implements SolverJob<Solution_, ProblemId_>, Callable<Solution_> {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultSolverJob.class);
private final DefaultSolverManager<Solution_, ProblemId_> solverManager;
private final DefaultSolver<Solution_> solver;
private final ProblemId_ problemId;
private final Function<? super ProblemId_, ? extends Solution_> problemFinder;
private final Consumer<? super Solution_> bestSolutionConsumer;
private final Consumer<? super Solution_> finalBestSolutionConsumer;
private final BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler;
private volatile SolverStatus solverStatus;
private final CountDownLatch terminatedLatch;
private final ReentrantLock solverStatusModifyingLock;
private Future<Solution_> finalBestSolutionFuture;
private ConsumerSupport<Solution_, ProblemId_> consumerSupport;
private final AtomicBoolean terminatedEarly = new AtomicBoolean(false);
private final BestSolutionHolder<Solution_> bestSolutionHolder = new BestSolutionHolder<>();
public DefaultSolverJob(
DefaultSolverManager<Solution_, ProblemId_> solverManager,
Solver<Solution_> solver, ProblemId_ problemId,
Function<? super ProblemId_, ? extends Solution_> problemFinder,
Consumer<? super Solution_> bestSolutionConsumer,
Consumer<? super Solution_> finalBestSolutionConsumer,
BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler) {
this.solverManager = solverManager;
this.problemId = problemId;
if (!(solver instanceof DefaultSolver)) {
throw new IllegalStateException("Impossible state: solver is not instance of " +
DefaultSolver.class.getSimpleName() + ".");
}
this.solver = (DefaultSolver<Solution_>) solver;
this.problemFinder = problemFinder;
this.bestSolutionConsumer = bestSolutionConsumer;
this.finalBestSolutionConsumer = finalBestSolutionConsumer;
this.exceptionHandler = exceptionHandler;
solverStatus = SolverStatus.SOLVING_SCHEDULED;
terminatedLatch = new CountDownLatch(1);
solverStatusModifyingLock = new ReentrantLock();
}
public void setFinalBestSolutionFuture(Future<Solution_> finalBestSolutionFuture) {
this.finalBestSolutionFuture = finalBestSolutionFuture;
}
@Override
public ProblemId_ getProblemId() {
return problemId;
}
@Override
public SolverStatus getSolverStatus() {
return solverStatus;
}
@Override
public Solution_ call() {
solverStatusModifyingLock.lock();
if (solverStatus != SolverStatus.SOLVING_SCHEDULED) {
// This job has been canceled before it started,
// or it is already solving
solverStatusModifyingLock.unlock();
return problemFinder.apply(problemId);
}
try {
solverStatus = SolverStatus.SOLVING_ACTIVE;
// Create the consumer thread pool only when this solver job is active.
consumerSupport = new ConsumerSupport<>(getProblemId(), bestSolutionConsumer, finalBestSolutionConsumer,
exceptionHandler, bestSolutionHolder);
Solution_ problem = problemFinder.apply(problemId);
// add a phase lifecycle listener that unlock the solver status lock when solving started
solver.addPhaseLifecycleListener(new UnlockLockPhaseLifecycleListener());
solver.addEventListener(this::onBestSolutionChangedEvent);
final Solution_ finalBestSolution = solver.solve(problem);
consumerSupport.consumeFinalBestSolution(finalBestSolution);
return finalBestSolution;
} catch (Throwable e) {
exceptionHandler.accept(problemId, e);
bestSolutionHolder.cancelPendingChanges();
throw new IllegalStateException("Solving failed for problemId (" + problemId + ").", e);
} finally {
if (solverStatusModifyingLock.isHeldByCurrentThread()) {
// release the lock if we have it (due to solver raising an exception before solving starts);
// This does not make it possible to do a double terminate in terminateEarly because:
// 1. The case SOLVING_SCHEDULED is impossible (only set to SOLVING_SCHEDULED in constructor,
// and it was set it to SolverStatus.SOLVING_ACTIVE in the method)
// 2. The case SOLVING_ACTIVE only calls solver.terminateEarly, so it effectively does nothing
// 3. The case NOT_SOLVING does nothing
solverStatusModifyingLock.unlock();
}
solvingTerminated();
}
}
private void onBestSolutionChangedEvent(BestSolutionChangedEvent<Solution_> bestSolutionChangedEvent) {
consumerSupport.consumeIntermediateBestSolution(bestSolutionChangedEvent.getNewBestSolution(),
() -> bestSolutionChangedEvent.isEveryProblemChangeProcessed());
}
private void solvingTerminated() {
solverStatus = SolverStatus.NOT_SOLVING;
solverManager.unregisterSolverJob(problemId);
terminatedLatch.countDown();
}
// TODO Future features
// @Override
// public void reloadProblem(Function<? super ProblemId_, Solution_> problemFinder) {
// throw new UnsupportedOperationException("The solver is still solving and reloadProblem() is not yet supported.");
// }
@Override
public CompletableFuture<Void> addProblemChange(ProblemChange<Solution_> problemChange) {
Objects.requireNonNull(problemChange, () -> "A problem change (" + problemChange + ") must not be null.");
if (solverStatus == SolverStatus.NOT_SOLVING) {
throw new IllegalStateException("Cannot add the problem change (" + problemChange
+ ") because the solver job (" + solverStatus + ") is not solving.");
}
return bestSolutionHolder.addProblemChange(solver, problemChange);
}
@Override
public void terminateEarly() {
terminatedEarly.set(true);
try {
solverStatusModifyingLock.lock();
switch (solverStatus) {
case SOLVING_SCHEDULED:
finalBestSolutionFuture.cancel(false);
solvingTerminated();
break;
case SOLVING_ACTIVE:
// Indirectly triggers solvingTerminated()
// No need to cancel the finalBestSolutionFuture as it will finish normally.
solver.terminateEarly();
break;
case NOT_SOLVING:
// Do nothing, solvingTerminated() already called
break;
default:
throw new IllegalStateException("Unsupported solverStatus (" + solverStatus + ").");
}
try {
// Don't return until bestSolutionConsumer won't be called anymore
terminatedLatch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOGGER.warn("The terminateEarly() call is interrupted.", e);
}
} finally {
solverStatusModifyingLock.unlock();
}
}
@Override
public boolean isTerminatedEarly() {
return terminatedEarly.get();
}
@Override
public Solution_ getFinalBestSolution() throws InterruptedException, ExecutionException {
try {
return finalBestSolutionFuture.get();
} catch (CancellationException cancellationException) {
LOGGER.debug("The terminateEarly() has been called before the solver job started solving. "
+ "Retrieving the input problem instead.");
return problemFinder.apply(problemId);
}
}
@Override
public Duration getSolvingDuration() {
return Duration.ofMillis(solver.getTimeMillisSpent());
}
@Override
public long getScoreCalculationCount() {
return solver.getScoreCalculationCount();
}
@Override
public long getScoreCalculationSpeed() {
return solver.getScoreCalculationSpeed();
}
@Override
public ProblemSizeStatistics getProblemSizeStatistics() {
var problemSizeStatistics = solver.getSolverScope().getProblemSizeStatistics();
if (problemSizeStatistics != null) {
return problemSizeStatistics;
}
// Solving has not started yet
return solver.getSolverScope().getSolutionDescriptor().getProblemSizeStatistics(
solver.getSolverScope().getScoreDirector(),
problemFinder.apply(problemId));
}
public Termination<Solution_> getSolverTermination() {
return solver.solverTermination;
}
void close() {
if (consumerSupport != null) {
consumerSupport.close();
consumerSupport = null;
}
}
/**
* A listener that unlocks the solverStatusModifyingLock when Solving has started.
*
* It prevents the following scenario caused by unlocking before Solving started:
*
* Thread 1:
* solverStatusModifyingLock.unlock()
* >solver.solve(...) // executes second
*
* Thread 2:
* case SOLVING_ACTIVE:
* >solver.terminateEarly(); // executes first
*
* The solver.solve() call resets the terminateEarly flag, and thus the solver will not be terminated
* by the call, which means terminatedLatch will not be decremented, causing Thread 2 to wait forever
* (at least until another Thread calls terminateEarly again).
*
* To prevent Thread 2 from potentially waiting forever, we only unlock the lock after the
* solvingStarted phase lifecycle event is fired, meaning the terminateEarly flag will not be
* reset and thus the solver will actually terminate.
*/
private final class UnlockLockPhaseLifecycleListener extends PhaseLifecycleListenerAdapter<Solution_> {
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
// The solvingStarted event can be emitted as a result of addProblemChange().
if (solverStatusModifyingLock.isLocked()) {
solverStatusModifyingLock.unlock();
}
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/DefaultSolverJobBuilder.java | package ai.timefold.solver.core.impl.solver;
import java.util.Objects;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.solver.SolverConfigOverride;
import ai.timefold.solver.core.api.solver.SolverJob;
import ai.timefold.solver.core.api.solver.SolverJobBuilder;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @param <ProblemId_> the ID type of submitted problem, such as {@link Long} or {@link UUID}.
*/
public final class DefaultSolverJobBuilder<Solution_, ProblemId_> implements SolverJobBuilder<Solution_, ProblemId_> {
private final DefaultSolverManager<Solution_, ProblemId_> solverManager;
private ProblemId_ problemId;
private Function<? super ProblemId_, ? extends Solution_> problemFinder;
private Consumer<? super Solution_> bestSolutionConsumer;
private Consumer<? super Solution_> finalBestSolutionConsumer;
private BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler;
private SolverConfigOverride<Solution_> solverConfigOverride;
public DefaultSolverJobBuilder(DefaultSolverManager<Solution_, ProblemId_> solverManager) {
this.solverManager = Objects.requireNonNull(solverManager, "The SolverManager (" + solverManager + ") cannot be null.");
}
@Override
public SolverJobBuilder<Solution_, ProblemId_> withProblemId(ProblemId_ problemId) {
this.problemId = Objects.requireNonNull(problemId, "Invalid problemId (null) given to SolverJobBuilder.");
return this;
}
@Override
public SolverJobBuilder<Solution_, ProblemId_>
withProblemFinder(Function<? super ProblemId_, ? extends Solution_> problemFinder) {
this.problemFinder = Objects.requireNonNull(problemFinder, "Invalid problemFinder (null) given to SolverJobBuilder.");
return this;
}
@Override
public SolverJobBuilder<Solution_, ProblemId_> withBestSolutionConsumer(Consumer<? super Solution_> bestSolutionConsumer) {
this.bestSolutionConsumer =
Objects.requireNonNull(bestSolutionConsumer, "Invalid bestSolutionConsumer (null) given to SolverJobBuilder.");
return this;
}
@Override
public SolverJobBuilder<Solution_, ProblemId_>
withFinalBestSolutionConsumer(Consumer<? super Solution_> finalBestSolutionConsumer) {
this.finalBestSolutionConsumer = Objects.requireNonNull(finalBestSolutionConsumer,
"Invalid finalBestSolutionConsumer (null) given to SolverJobBuilder.");
return this;
}
@Override
public SolverJobBuilder<Solution_, ProblemId_>
withExceptionHandler(BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler) {
this.exceptionHandler =
Objects.requireNonNull(exceptionHandler, "Invalid exceptionHandler (null) given to SolverJobBuilder.");
return this;
}
@Override
public SolverJobBuilder<Solution_, ProblemId_> withConfigOverride(SolverConfigOverride<Solution_> solverConfigOverride) {
this.solverConfigOverride =
Objects.requireNonNull(solverConfigOverride, "Invalid solverConfigOverride (null) given to SolverJobBuilder.");
return this;
}
@Override
public SolverJob<Solution_, ProblemId_> run() {
if (solverConfigOverride == null) {
// The config is required by SolverFactory and it must be initialized
this.solverConfigOverride = new SolverConfigOverride<>();
}
if (this.bestSolutionConsumer == null) {
return solverManager.solve(problemId, problemFinder, null, finalBestSolutionConsumer,
exceptionHandler, solverConfigOverride);
} else {
return solverManager.solveAndListen(problemId, problemFinder, bestSolutionConsumer, finalBestSolutionConsumer,
exceptionHandler, solverConfigOverride);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/DefaultSolverManager.java | package ai.timefold.solver.core.impl.solver;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.api.solver.SolverConfigOverride;
import ai.timefold.solver.core.api.solver.SolverFactory;
import ai.timefold.solver.core.api.solver.SolverJob;
import ai.timefold.solver.core.api.solver.SolverJobBuilder;
import ai.timefold.solver.core.api.solver.SolverManager;
import ai.timefold.solver.core.api.solver.SolverStatus;
import ai.timefold.solver.core.api.solver.change.ProblemChange;
import ai.timefold.solver.core.config.solver.SolverManagerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @param <ProblemId_> the ID type of submitted problem, such as {@link Long} or {@link UUID}.
*/
public final class DefaultSolverManager<Solution_, ProblemId_> implements SolverManager<Solution_, ProblemId_> {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultSolverManager.class);
private final BiConsumer<ProblemId_, Throwable> defaultExceptionHandler;
private final SolverFactory<Solution_> solverFactory;
private final ExecutorService solverThreadPool;
private final ConcurrentMap<Object, DefaultSolverJob<Solution_, ProblemId_>> problemIdToSolverJobMap;
public DefaultSolverManager(SolverFactory<Solution_> solverFactory,
SolverManagerConfig solverManagerConfig) {
defaultExceptionHandler = (problemId, throwable) -> LOGGER.error(
"Solving failed for problemId ({}).", problemId, throwable);
this.solverFactory = solverFactory;
validateSolverFactory();
int parallelSolverCount = solverManagerConfig.resolveParallelSolverCount();
solverThreadPool = Executors.newFixedThreadPool(parallelSolverCount);
problemIdToSolverJobMap = new ConcurrentHashMap<>(parallelSolverCount * 10);
}
public SolverFactory<Solution_> getSolverFactory() {
return solverFactory;
}
private void validateSolverFactory() {
solverFactory.buildSolver();
}
private ProblemId_ getProblemIdOrThrow(ProblemId_ problemId) {
return Objects.requireNonNull(problemId, "Invalid problemId (null) given to SolverManager.");
}
private DefaultSolverJob<Solution_, ProblemId_> getSolverJob(ProblemId_ problemId) {
return problemIdToSolverJobMap.get(getProblemIdOrThrow(problemId));
}
@Override
public SolverJobBuilder<Solution_, ProblemId_> solveBuilder() {
return new DefaultSolverJobBuilder<>(this);
}
protected SolverJob<Solution_, ProblemId_> solveAndListen(ProblemId_ problemId,
Function<? super ProblemId_, ? extends Solution_> problemFinder,
Consumer<? super Solution_> bestSolutionConsumer,
Consumer<? super Solution_> finalBestSolutionConsumer,
BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler,
SolverConfigOverride<Solution_> solverConfigOverride) {
if (bestSolutionConsumer == null) {
throw new IllegalStateException("The consumer bestSolutionConsumer is required.");
}
return solve(getProblemIdOrThrow(problemId), problemFinder, bestSolutionConsumer, finalBestSolutionConsumer,
exceptionHandler, solverConfigOverride);
}
protected SolverJob<Solution_, ProblemId_> solve(ProblemId_ problemId,
Function<? super ProblemId_, ? extends Solution_> problemFinder,
Consumer<? super Solution_> bestSolutionConsumer,
Consumer<? super Solution_> finalBestSolutionConsumer,
BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler,
SolverConfigOverride<Solution_> configOverride) {
Solver<Solution_> solver = solverFactory.buildSolver(configOverride);
((DefaultSolver<Solution_>) solver).setMonitorTagMap(Map.of("problem.id", problemId.toString()));
BiConsumer<? super ProblemId_, ? super Throwable> finalExceptionHandler = (exceptionHandler != null)
? exceptionHandler
: defaultExceptionHandler;
DefaultSolverJob<Solution_, ProblemId_> solverJob = problemIdToSolverJobMap
.compute(problemId, (key, oldSolverJob) -> {
if (oldSolverJob != null) {
// TODO Future features: automatically restart solving by calling reloadProblem()
throw new IllegalStateException("The problemId (" + problemId + ") is already solving.");
} else {
return new DefaultSolverJob<>(this, solver, problemId, problemFinder,
bestSolutionConsumer, finalBestSolutionConsumer, finalExceptionHandler);
}
});
Future<Solution_> future = solverThreadPool.submit(solverJob);
solverJob.setFinalBestSolutionFuture(future);
return solverJob;
}
@Override
public SolverStatus getSolverStatus(ProblemId_ problemId) {
DefaultSolverJob<Solution_, ProblemId_> solverJob = getSolverJob(problemId);
if (solverJob == null) {
return SolverStatus.NOT_SOLVING;
}
return solverJob.getSolverStatus();
}
// TODO Future features
// @Override
// public void reloadProblem(ProblemId_ problemId, Function<? super ProblemId_, Solution_> problemFinder) {
// DefaultSolverJob<Solution_, ProblemId_> solverJob = problemIdToSolverJobMap.get(problemId);
// if (solverJob == null) {
// // We cannot distinguish between "already terminated" and "never solved" without causing a memory leak.
// logger.debug("Ignoring reloadProblem() call because problemId ({}) is not solving.", problemId);
// return;
// }
// solverJob.reloadProblem(problemFinder);
// }
@Override
public CompletableFuture<Void> addProblemChange(ProblemId_ problemId, ProblemChange<Solution_> problemChange) {
DefaultSolverJob<Solution_, ProblemId_> solverJob = getSolverJob(problemId);
if (solverJob == null) {
// We cannot distinguish between "already terminated" and "never solved" without causing a memory leak.
throw new IllegalStateException(
"Cannot add the problem change (" + problemChange + ") because there is no solver solving the problemId ("
+ problemId + ").");
}
return solverJob.addProblemChange(problemChange);
}
@Override
public void terminateEarly(ProblemId_ problemId) {
DefaultSolverJob<Solution_, ProblemId_> solverJob = getSolverJob(problemId);
if (solverJob == null) {
// We cannot distinguish between "already terminated" and "never solved" without causing a memory leak.
LOGGER.debug("Ignoring terminateEarly() call because problemId ({}) is not solving.", problemId);
return;
}
solverJob.terminateEarly();
}
@Override
public void close() {
solverThreadPool.shutdownNow();
problemIdToSolverJobMap.values().forEach(DefaultSolverJob::close);
}
void unregisterSolverJob(ProblemId_ problemId) {
problemIdToSolverJobMap.remove(getProblemIdOrThrow(problemId));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/FitProcessor.java | package ai.timefold.solver.core.impl.solver;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.function.Function;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.analysis.ScoreAnalysis;
import ai.timefold.solver.core.api.solver.RecommendedFit;
import ai.timefold.solver.core.api.solver.ScoreAnalysisFetchPolicy;
import ai.timefold.solver.core.impl.constructionheuristic.DefaultConstructionHeuristicPhase;
import ai.timefold.solver.core.impl.constructionheuristic.placer.EntityPlacer;
import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicPhaseScope;
import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicStepScope;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
public final class FitProcessor<Solution_, In_, Out_, Score_ extends Score<Score_>>
implements Function<InnerScoreDirector<Solution_, Score_>, List<RecommendedFit<Out_, Score_>>> {
private final DefaultSolverFactory<Solution_> solverFactory;
private final ScoreAnalysis<Score_> originalScoreAnalysis;
private final ScoreAnalysisFetchPolicy fetchPolicy;
private final Function<In_, Out_> valueResultFunction;
private final In_ clonedElement;
public FitProcessor(DefaultSolverFactory<Solution_> solverFactory, Function<In_, Out_> valueResultFunction,
ScoreAnalysis<Score_> originalScoreAnalysis, In_ clonedElement, ScoreAnalysisFetchPolicy fetchPolicy) {
this.solverFactory = Objects.requireNonNull(solverFactory);
this.originalScoreAnalysis = Objects.requireNonNull(originalScoreAnalysis);
this.fetchPolicy = Objects.requireNonNull(fetchPolicy);
this.valueResultFunction = valueResultFunction;
this.clonedElement = clonedElement;
}
@Override
public List<RecommendedFit<Out_, Score_>> apply(InnerScoreDirector<Solution_, Score_> scoreDirector) {
// The placers needs to be filtered.
// If anything else than the cloned element is unassigned, we want to keep it unassigned.
// Otherwise the solution would have to explicitly pin everything other than the cloned element.
var entityPlacer = buildEntityPlacer()
.rebuildWithFilter((solution, selection) -> selection == clonedElement);
var solverScope = new SolverScope<Solution_>();
solverScope.setWorkingRandom(new Random(0)); // We will evaluate every option; random does not matter.
solverScope.setScoreDirector(scoreDirector);
var phaseScope = new ConstructionHeuristicPhaseScope<>(solverScope);
var stepScope = new ConstructionHeuristicStepScope<>(phaseScope);
entityPlacer.solvingStarted(solverScope);
entityPlacer.phaseStarted(phaseScope);
entityPlacer.stepStarted(stepScope);
try (scoreDirector) {
var placementIterator = entityPlacer.iterator();
if (!placementIterator.hasNext()) {
throw new IllegalStateException("""
Impossible state: entity placer (%s) has no placements.
""".formatted(entityPlacer));
}
var placement = placementIterator.next();
var recommendedFitList = new ArrayList<RecommendedFit<Out_, Score_>>();
var moveIndex = 0L;
for (var move : placement) {
recommendedFitList.add(execute(scoreDirector, move, moveIndex, clonedElement, valueResultFunction));
moveIndex++;
}
recommendedFitList.sort(null);
return recommendedFitList;
} finally {
entityPlacer.stepEnded(stepScope);
entityPlacer.phaseEnded(phaseScope);
entityPlacer.solvingEnded(solverScope);
}
}
private EntityPlacer<Solution_> buildEntityPlacer() {
var solver = (DefaultSolver<Solution_>) solverFactory.buildSolver();
var phaseList = solver.getPhaseList();
long constructionHeuristicCount = phaseList.stream()
.filter(s -> (s instanceof DefaultConstructionHeuristicPhase))
.count();
if (constructionHeuristicCount != 1) {
throw new IllegalStateException(
"Fit Recommendation API requires the solver config to have exactly one construction heuristic phase, but it has (%s) instead."
.formatted(constructionHeuristicCount));
}
var phase = phaseList.get(0);
if (phase instanceof DefaultConstructionHeuristicPhase<Solution_> constructionHeuristicPhase) {
return constructionHeuristicPhase.getEntityPlacer();
} else {
throw new IllegalStateException(
"Fit Recommendation API requires the first solver phase (%s) in the solver config to be a construction heuristic."
.formatted(phase));
}
}
private RecommendedFit<Out_, Score_> execute(InnerScoreDirector<Solution_, Score_> scoreDirector, Move<Solution_> move,
long moveIndex, In_ clonedElement, Function<In_, Out_> propositionFunction) {
var undo = move.doMove(scoreDirector);
var newScoreAnalysis = scoreDirector.buildScoreAnalysis(fetchPolicy == ScoreAnalysisFetchPolicy.FETCH_ALL);
var newScoreDifference = newScoreAnalysis.diff(originalScoreAnalysis);
var result = propositionFunction.apply(clonedElement);
var recommendation = new DefaultRecommendedFit<>(moveIndex, result, newScoreDifference);
undo.doMoveOnly(scoreDirector);
return recommendation;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/Fitter.java | package ai.timefold.solver.core.impl.solver;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.solver.RecommendedFit;
import ai.timefold.solver.core.api.solver.ScoreAnalysisFetchPolicy;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
final class Fitter<Solution_, In_, Out_, Score_ extends Score<Score_>>
implements Function<InnerScoreDirector<Solution_, Score_>, List<RecommendedFit<Out_, Score_>>> {
private final DefaultSolverFactory<Solution_> solverFactory;
private final Solution_ originalSolution;
private final In_ originalElement;
private final Function<In_, Out_> propositionFunction;
private final ScoreAnalysisFetchPolicy fetchPolicy;
public Fitter(DefaultSolverFactory<Solution_> solverFactory, Solution_ originalSolution, In_ originalElement,
Function<In_, Out_> propositionFunction, ScoreAnalysisFetchPolicy fetchPolicy) {
this.solverFactory = Objects.requireNonNull(solverFactory);
this.originalSolution = Objects.requireNonNull(originalSolution);
this.originalElement = Objects.requireNonNull(originalElement);
this.propositionFunction = Objects.requireNonNull(propositionFunction);
this.fetchPolicy = Objects.requireNonNull(fetchPolicy);
}
@Override
public List<RecommendedFit<Out_, Score_>> apply(InnerScoreDirector<Solution_, Score_> scoreDirector) {
var solutionDescriptor = scoreDirector.getSolutionDescriptor();
var initializationStatistics = solutionDescriptor.computeInitializationStatistics(originalSolution);
var uninitializedCount =
initializationStatistics.uninitializedEntityCount() + initializationStatistics.unassignedValueCount();
if (uninitializedCount > 1) {
throw new IllegalStateException("""
Solution (%s) has (%d) uninitialized elements.
Fit Recommendation API requires at most one uninitialized element in the solution."""
.formatted(originalSolution, uninitializedCount));
}
var originalScoreAnalysis = scoreDirector.buildScoreAnalysis(fetchPolicy == ScoreAnalysisFetchPolicy.FETCH_ALL,
InnerScoreDirector.ScoreAnalysisMode.RECOMMENDATION_API);
var clonedElement = scoreDirector.lookUpWorkingObject(originalElement);
var processor =
new FitProcessor<>(solverFactory, propositionFunction, originalScoreAnalysis, clonedElement, fetchPolicy);
return processor.apply(scoreDirector);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/change/DefaultProblemChangeDirector.java | package ai.timefold.solver.core.impl.solver.change;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.solver.change.ProblemChange;
import ai.timefold.solver.core.api.solver.change.ProblemChangeDirector;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
public final class DefaultProblemChangeDirector<Solution_> implements ProblemChangeDirector {
private final InnerScoreDirector<Solution_, ?> scoreDirector;
public DefaultProblemChangeDirector(InnerScoreDirector<Solution_, ?> scoreDirector) {
this.scoreDirector = scoreDirector;
}
@Override
public <Entity> void addEntity(Entity entity, Consumer<Entity> entityConsumer) {
Objects.requireNonNull(entity, () -> "Entity (" + entity + ") cannot be null.");
Objects.requireNonNull(entityConsumer, () -> "Entity consumer (" + entityConsumer + ") cannot be null.");
scoreDirector.beforeEntityAdded(entity);
entityConsumer.accept(entity);
scoreDirector.afterEntityAdded(entity);
}
@Override
public <Entity> void removeEntity(Entity entity, Consumer<Entity> entityConsumer) {
Objects.requireNonNull(entity, () -> "Entity (" + entity + ") cannot be null.");
Objects.requireNonNull(entityConsumer, () -> "Entity consumer (" + entityConsumer + ") cannot be null.");
Entity workingEntity = lookUpWorkingObjectOrFail(entity);
scoreDirector.beforeEntityRemoved(workingEntity);
entityConsumer.accept(workingEntity);
scoreDirector.afterEntityRemoved(workingEntity);
}
@Override
public <Entity> void changeVariable(Entity entity, String variableName, Consumer<Entity> entityConsumer) {
Objects.requireNonNull(entity, () -> "Entity (" + entity + ") cannot be null.");
Objects.requireNonNull(variableName, () -> "Planning variable name (" + variableName + ") cannot be null.");
Objects.requireNonNull(entityConsumer, () -> "Entity consumer (" + entityConsumer + ") cannot be null.");
Entity workingEntity = lookUpWorkingObjectOrFail(entity);
scoreDirector.beforeVariableChanged(workingEntity, variableName);
entityConsumer.accept(workingEntity);
scoreDirector.afterVariableChanged(workingEntity, variableName);
}
@Override
public <ProblemFact> void addProblemFact(ProblemFact problemFact, Consumer<ProblemFact> problemFactConsumer) {
Objects.requireNonNull(problemFact, () -> "Problem fact (" + problemFact + ") cannot be null.");
Objects.requireNonNull(problemFactConsumer, () -> "Problem fact consumer (" + problemFactConsumer
+ ") cannot be null.");
scoreDirector.beforeProblemFactAdded(problemFact);
problemFactConsumer.accept(problemFact);
scoreDirector.afterProblemFactAdded(problemFact);
}
@Override
public <ProblemFact> void removeProblemFact(ProblemFact problemFact, Consumer<ProblemFact> problemFactConsumer) {
Objects.requireNonNull(problemFact, () -> "Problem fact (" + problemFact + ") cannot be null.");
Objects.requireNonNull(problemFactConsumer, () -> "Problem fact consumer (" + problemFactConsumer
+ ") cannot be null.");
ProblemFact workingProblemFact = lookUpWorkingObjectOrFail(problemFact);
scoreDirector.beforeProblemFactRemoved(workingProblemFact);
problemFactConsumer.accept(workingProblemFact);
scoreDirector.afterProblemFactRemoved(workingProblemFact);
}
@Override
public <EntityOrProblemFact> void changeProblemProperty(EntityOrProblemFact problemFactOrEntity,
Consumer<EntityOrProblemFact> problemFactOrEntityConsumer) {
Objects.requireNonNull(problemFactOrEntity,
() -> "Problem fact or entity (" + problemFactOrEntity + ") cannot be null.");
Objects.requireNonNull(problemFactOrEntityConsumer, () -> "Problem fact or entity consumer ("
+ problemFactOrEntityConsumer + ") cannot be null.");
EntityOrProblemFact workingEntityOrProblemFact = lookUpWorkingObjectOrFail(problemFactOrEntity);
scoreDirector.beforeProblemPropertyChanged(workingEntityOrProblemFact);
problemFactOrEntityConsumer.accept(workingEntityOrProblemFact);
scoreDirector.afterProblemPropertyChanged(workingEntityOrProblemFact);
}
@Override
public <EntityOrProblemFact> EntityOrProblemFact lookUpWorkingObjectOrFail(EntityOrProblemFact externalObject) {
return scoreDirector.lookUpWorkingObject(externalObject);
}
@Override
public <EntityOrProblemFact> Optional<EntityOrProblemFact>
lookUpWorkingObject(EntityOrProblemFact externalObject) {
return Optional.ofNullable(scoreDirector.lookUpWorkingObjectOrReturnNull(externalObject));
}
@Override
public void updateShadowVariables() {
scoreDirector.triggerVariableListeners();
}
public Score<?> doProblemChange(ProblemChange<Solution_> problemChange) {
problemChange.doChange(scoreDirector.getWorkingSolution(), this);
updateShadowVariables();
return scoreDirector.calculateScore();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/event/SolverEventSupport.java | package ai.timefold.solver.core.impl.solver.event;
import java.util.Iterator;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.api.solver.event.BestSolutionChangedEvent;
import ai.timefold.solver.core.api.solver.event.SolverEventListener;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
/**
* Internal API.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class SolverEventSupport<Solution_> extends AbstractEventSupport<SolverEventListener<Solution_>> {
private final Solver<Solution_> solver;
public SolverEventSupport(Solver<Solution_> solver) {
this.solver = solver;
}
public void fireBestSolutionChanged(SolverScope<Solution_> solverScope, Solution_ newBestSolution) {
final Iterator<SolverEventListener<Solution_>> it = getEventListeners().iterator();
long timeMillisSpent = solverScope.getBestSolutionTimeMillisSpent();
Score bestScore = solverScope.getBestScore();
if (it.hasNext()) {
final BestSolutionChangedEvent<Solution_> event = new BestSolutionChangedEvent<>(solver,
timeMillisSpent, newBestSolution, bestScore);
do {
it.next().bestSolutionChanged(event);
} while (it.hasNext());
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/exception/UndoScoreCorruptionException.java | package ai.timefold.solver.core.impl.solver.exception;
/**
* An exception that is thrown in {@link ai.timefold.solver.core.config.solver.EnvironmentMode#TRACKED_FULL_ASSERT} when
* undo score corruption is detected. It contains the working solution before the move, after the move, and after the undo move,
* as well as the move that caused the corruption. You can catch this exception to create a reproducer of the corruption.
* The API for this exception is currently unstable.
*/
public class UndoScoreCorruptionException extends IllegalStateException {
private final Object beforeMoveSolution;
private final Object afterMoveSolution;
private final Object afterUndoSolution;
public UndoScoreCorruptionException(String message, Object beforeMoveSolution, Object afterMoveSolution,
Object afterUndoSolution) {
super(message);
this.beforeMoveSolution = beforeMoveSolution;
this.afterMoveSolution = afterMoveSolution;
this.afterUndoSolution = afterUndoSolution;
}
/**
* Return the state of the working solution before a move was executed.
*
* @return the state of the working solution before a move was executed.
*/
@SuppressWarnings("unchecked")
public <Solution_> Solution_ getBeforeMoveSolution() {
return (Solution_) beforeMoveSolution;
}
/**
* Return the state of the working solution after a move was executed, but prior to the undo move.
*
* @return the state of the working solution after a move was executed, but prior to the undo move.
*/
@SuppressWarnings("unchecked")
public <Solution_> Solution_ getAfterMoveSolution() {
return (Solution_) afterMoveSolution;
}
/**
* Return the state of the working solution after the undo move was executed.
*
* @return the state of the working solution after the undo move was executed.
*/
@SuppressWarnings("unchecked")
public <Solution_> Solution_ getAfterUndoSolution() {
return (Solution_) afterUndoSolution;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/recaller/BestSolutionRecaller.java | package ai.timefold.solver.core.impl.solver.recaller;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleListenerAdapter;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.solver.event.SolverEventSupport;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
/**
* Remembers the {@link PlanningSolution best solution} that a {@link Solver} encounters.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class BestSolutionRecaller<Solution_> extends PhaseLifecycleListenerAdapter<Solution_> {
protected boolean assertInitialScoreFromScratch = false;
protected boolean assertShadowVariablesAreNotStale = false;
protected boolean assertBestScoreIsUnmodified = false;
protected SolverEventSupport<Solution_> solverEventSupport;
public void setAssertInitialScoreFromScratch(boolean assertInitialScoreFromScratch) {
this.assertInitialScoreFromScratch = assertInitialScoreFromScratch;
}
public void setAssertShadowVariablesAreNotStale(boolean assertShadowVariablesAreNotStale) {
this.assertShadowVariablesAreNotStale = assertShadowVariablesAreNotStale;
}
public void setAssertBestScoreIsUnmodified(boolean assertBestScoreIsUnmodified) {
this.assertBestScoreIsUnmodified = assertBestScoreIsUnmodified;
}
public void setSolverEventSupport(SolverEventSupport<Solution_> solverEventSupport) {
this.solverEventSupport = solverEventSupport;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
// Starting bestSolution is already set by Solver.solve(Solution)
InnerScoreDirector scoreDirector = solverScope.getScoreDirector();
Score score = scoreDirector.calculateScore();
solverScope.setBestScore(score);
solverScope.setBestSolutionTimeMillis(System.currentTimeMillis());
// The original bestSolution might be the final bestSolution and should have an accurate Score
solverScope.getSolutionDescriptor().setScore(solverScope.getBestSolution(), score);
if (score.isSolutionInitialized()) {
solverScope.setStartingInitializedScore(score);
} else {
solverScope.setStartingInitializedScore(null);
}
if (assertInitialScoreFromScratch) {
scoreDirector.assertWorkingScoreFromScratch(score, "Initial score calculated");
}
if (assertShadowVariablesAreNotStale) {
scoreDirector.assertShadowVariablesAreNotStale(score, "Initial score calculated");
}
}
public void processWorkingSolutionDuringConstructionHeuristicsStep(AbstractStepScope<Solution_> stepScope) {
AbstractPhaseScope<Solution_> phaseScope = stepScope.getPhaseScope();
SolverScope<Solution_> solverScope = phaseScope.getSolverScope();
stepScope.setBestScoreImproved(true);
phaseScope.setBestSolutionStepIndex(stepScope.getStepIndex());
Solution_ newBestSolution = stepScope.getWorkingSolution();
// Construction heuristics don't fire intermediate best solution changed events.
// But the best solution and score are updated, so that unimproved* terminations work correctly.
updateBestSolutionWithoutFiring(solverScope, stepScope.getScore(), newBestSolution);
}
public void processWorkingSolutionDuringStep(AbstractStepScope<Solution_> stepScope) {
AbstractPhaseScope<Solution_> phaseScope = stepScope.getPhaseScope();
Score score = stepScope.getScore();
SolverScope<Solution_> solverScope = phaseScope.getSolverScope();
boolean bestScoreImproved = score.compareTo(solverScope.getBestScore()) > 0;
stepScope.setBestScoreImproved(bestScoreImproved);
if (bestScoreImproved) {
phaseScope.setBestSolutionStepIndex(stepScope.getStepIndex());
Solution_ newBestSolution = stepScope.createOrGetClonedSolution();
updateBestSolutionAndFire(solverScope, score, newBestSolution);
} else if (assertBestScoreIsUnmodified) {
solverScope.assertScoreFromScratch(solverScope.getBestSolution());
}
}
public void processWorkingSolutionDuringMove(Score score, AbstractStepScope<Solution_> stepScope) {
AbstractPhaseScope<Solution_> phaseScope = stepScope.getPhaseScope();
SolverScope<Solution_> solverScope = phaseScope.getSolverScope();
boolean bestScoreImproved = score.compareTo(solverScope.getBestScore()) > 0;
// The method processWorkingSolutionDuringMove() is called 0..* times
// stepScope.getBestScoreImproved() is initialized on false before the first call here
if (bestScoreImproved) {
stepScope.setBestScoreImproved(bestScoreImproved);
}
if (bestScoreImproved) {
phaseScope.setBestSolutionStepIndex(stepScope.getStepIndex());
Solution_ newBestSolution = solverScope.getScoreDirector().cloneWorkingSolution();
updateBestSolutionAndFire(solverScope, score, newBestSolution);
} else if (assertBestScoreIsUnmodified) {
solverScope.assertScoreFromScratch(solverScope.getBestSolution());
}
}
public void updateBestSolutionAndFire(SolverScope<Solution_> solverScope) {
updateBestSolutionWithoutFiring(solverScope);
solverEventSupport.fireBestSolutionChanged(solverScope, solverScope.getBestSolution());
}
public void updateBestSolutionAndFireIfInitialized(SolverScope<Solution_> solverScope) {
updateBestSolutionWithoutFiring(solverScope);
if (solverScope.isBestSolutionInitialized()) {
solverEventSupport.fireBestSolutionChanged(solverScope, solverScope.getBestSolution());
}
}
private void updateBestSolutionAndFire(SolverScope<Solution_> solverScope, Score bestScore, Solution_ bestSolution) {
updateBestSolutionWithoutFiring(solverScope, bestScore, bestSolution);
solverEventSupport.fireBestSolutionChanged(solverScope, solverScope.getBestSolution());
}
private void updateBestSolutionWithoutFiring(SolverScope<Solution_> solverScope) {
Solution_ newBestSolution = solverScope.getScoreDirector().cloneWorkingSolution();
Score newBestScore = solverScope.getSolutionDescriptor().getScore(newBestSolution);
updateBestSolutionWithoutFiring(solverScope, newBestScore, newBestSolution);
}
private void updateBestSolutionWithoutFiring(SolverScope<Solution_> solverScope, Score bestScore, Solution_ bestSolution) {
if (bestScore.isSolutionInitialized()) {
if (!solverScope.isBestSolutionInitialized()) {
solverScope.setStartingInitializedScore(bestScore);
}
}
solverScope.setBestSolution(bestSolution);
solverScope.setBestScore(bestScore);
solverScope.setBestSolutionTimeMillis(System.currentTimeMillis());
}
} |
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/recaller/BestSolutionRecallerFactory.java | package ai.timefold.solver.core.impl.solver.recaller;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
public class BestSolutionRecallerFactory {
public static BestSolutionRecallerFactory create() {
return new BestSolutionRecallerFactory();
}
public <Solution_> BestSolutionRecaller<Solution_> buildBestSolutionRecaller(EnvironmentMode environmentMode) {
BestSolutionRecaller<Solution_> bestSolutionRecaller = new BestSolutionRecaller<>();
if (environmentMode.isNonIntrusiveFullAsserted()) {
bestSolutionRecaller.setAssertInitialScoreFromScratch(true);
bestSolutionRecaller.setAssertShadowVariablesAreNotStale(true);
bestSolutionRecaller.setAssertBestScoreIsUnmodified(true);
}
return bestSolutionRecaller;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/scope/SolverScope.java | package ai.timefold.solver.core.impl.solver.scope;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReference;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.solver.ProblemSizeStatistics;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.config.solver.monitoring.SolverMetric;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.solver.change.DefaultProblemChangeDirector;
import ai.timefold.solver.core.impl.solver.termination.Termination;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
import io.micrometer.core.instrument.Tags;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class SolverScope<Solution_> {
protected Set<SolverMetric> solverMetricSet;
protected Tags monitoringTags;
protected int startingSolverCount;
protected Random workingRandom;
protected InnerScoreDirector<Solution_, ?> scoreDirector;
private DefaultProblemChangeDirector<Solution_> problemChangeDirector;
/**
* Used for capping CPU power usage in multithreaded scenarios.
*/
protected Semaphore runnableThreadSemaphore = null;
protected volatile Long startingSystemTimeMillis;
protected volatile Long endingSystemTimeMillis;
protected long childThreadsScoreCalculationCount = 0;
protected Score startingInitializedScore;
protected volatile ProblemSizeStatistics problemSizeStatistics;
protected volatile Solution_ bestSolution;
protected volatile Score bestScore;
protected Long bestSolutionTimeMillis;
/**
* Used for tracking step score
*/
protected final Map<Tags, List<AtomicReference<Number>>> stepScoreMap = new ConcurrentHashMap<>();
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public DefaultProblemChangeDirector<Solution_> getProblemChangeDirector() {
return problemChangeDirector;
}
public void setProblemChangeDirector(DefaultProblemChangeDirector<Solution_> problemChangeDirector) {
this.problemChangeDirector = problemChangeDirector;
}
public Tags getMonitoringTags() {
return monitoringTags;
}
public void setMonitoringTags(Tags monitoringTags) {
this.monitoringTags = monitoringTags;
}
public Map<Tags, List<AtomicReference<Number>>> getStepScoreMap() {
return stepScoreMap;
}
public Set<SolverMetric> getSolverMetricSet() {
return solverMetricSet;
}
public void setSolverMetricSet(EnumSet<SolverMetric> solverMetricSet) {
this.solverMetricSet = solverMetricSet;
}
public int getStartingSolverCount() {
return startingSolverCount;
}
public void setStartingSolverCount(int startingSolverCount) {
this.startingSolverCount = startingSolverCount;
}
public Random getWorkingRandom() {
return workingRandom;
}
public void setWorkingRandom(Random workingRandom) {
this.workingRandom = workingRandom;
}
public <Score_ extends Score<Score_>> InnerScoreDirector<Solution_, Score_> getScoreDirector() {
return (InnerScoreDirector<Solution_, Score_>) scoreDirector;
}
public void setScoreDirector(InnerScoreDirector<Solution_, ?> scoreDirector) {
this.scoreDirector = scoreDirector;
}
public void setRunnableThreadSemaphore(Semaphore runnableThreadSemaphore) {
this.runnableThreadSemaphore = runnableThreadSemaphore;
}
public Long getStartingSystemTimeMillis() {
return startingSystemTimeMillis;
}
public Long getEndingSystemTimeMillis() {
return endingSystemTimeMillis;
}
public SolutionDescriptor<Solution_> getSolutionDescriptor() {
return scoreDirector.getSolutionDescriptor();
}
public ScoreDefinition getScoreDefinition() {
return scoreDirector.getScoreDefinition();
}
public Solution_ getWorkingSolution() {
return scoreDirector.getWorkingSolution();
}
public int getWorkingEntityCount() {
return scoreDirector.getWorkingGenuineEntityCount();
}
public Score calculateScore() {
return scoreDirector.calculateScore();
}
public void assertScoreFromScratch(Solution_ solution) {
scoreDirector.getScoreDirectorFactory().assertScoreFromScratch(solution);
}
public Score getStartingInitializedScore() {
return startingInitializedScore;
}
public void setStartingInitializedScore(Score startingInitializedScore) {
this.startingInitializedScore = startingInitializedScore;
}
public void addChildThreadsScoreCalculationCount(long addition) {
childThreadsScoreCalculationCount += addition;
}
public long getScoreCalculationCount() {
return scoreDirector.getCalculationCount() + childThreadsScoreCalculationCount;
}
public Solution_ getBestSolution() {
return bestSolution;
}
/**
* The {@link PlanningSolution best solution} must never be the same instance
* as the {@link PlanningSolution working solution}, it should be a (un)changed clone.
*
* @param bestSolution never null
*/
public void setBestSolution(Solution_ bestSolution) {
this.bestSolution = bestSolution;
}
public Score getBestScore() {
return bestScore;
}
public void setBestScore(Score bestScore) {
this.bestScore = bestScore;
}
public Long getBestSolutionTimeMillis() {
return bestSolutionTimeMillis;
}
public void setBestSolutionTimeMillis(Long bestSolutionTimeMillis) {
this.bestSolutionTimeMillis = bestSolutionTimeMillis;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
public boolean isMetricEnabled(SolverMetric solverMetric) {
return solverMetricSet.contains(solverMetric);
}
public void startingNow() {
startingSystemTimeMillis = System.currentTimeMillis();
endingSystemTimeMillis = null;
}
public Long getBestSolutionTimeMillisSpent() {
return bestSolutionTimeMillis - startingSystemTimeMillis;
}
public void endingNow() {
endingSystemTimeMillis = System.currentTimeMillis();
}
public boolean isBestSolutionInitialized() {
return bestScore.isSolutionInitialized();
}
public long calculateTimeMillisSpentUpToNow() {
long now = System.currentTimeMillis();
return now - startingSystemTimeMillis;
}
public long getTimeMillisSpent() {
return endingSystemTimeMillis - startingSystemTimeMillis;
}
public ProblemSizeStatistics getProblemSizeStatistics() {
return problemSizeStatistics;
}
public void setProblemSizeStatistics(ProblemSizeStatistics problemSizeStatistics) {
this.problemSizeStatistics = problemSizeStatistics;
}
/**
* @return at least 0, per second
*/
public long getScoreCalculationSpeed() {
long timeMillisSpent = getTimeMillisSpent();
return getScoreCalculationSpeed(getScoreCalculationCount(), timeMillisSpent);
}
public static long getScoreCalculationSpeed(long scoreCalculationCount, long timeMillisSpent) {
// Avoid divide by zero exception on a fast CPU
return scoreCalculationCount * 1000L / (timeMillisSpent == 0L ? 1L : timeMillisSpent);
}
public void setWorkingSolutionFromBestSolution() {
// The workingSolution must never be the same instance as the bestSolution.
scoreDirector.setWorkingSolution(scoreDirector.cloneSolution(bestSolution));
}
public SolverScope<Solution_> createChildThreadSolverScope(ChildThreadType childThreadType) {
SolverScope<Solution_> childThreadSolverScope = new SolverScope<>();
childThreadSolverScope.monitoringTags = monitoringTags;
childThreadSolverScope.solverMetricSet = solverMetricSet;
childThreadSolverScope.startingSolverCount = startingSolverCount;
// TODO FIXME use RandomFactory
// Experiments show that this trick to attain reproducibility doesn't break uniform distribution
childThreadSolverScope.workingRandom = new Random(workingRandom.nextLong());
childThreadSolverScope.scoreDirector = scoreDirector.createChildThreadScoreDirector(childThreadType);
childThreadSolverScope.startingSystemTimeMillis = startingSystemTimeMillis;
childThreadSolverScope.endingSystemTimeMillis = null;
childThreadSolverScope.startingInitializedScore = null;
childThreadSolverScope.bestSolution = null;
childThreadSolverScope.bestScore = null;
childThreadSolverScope.bestSolutionTimeMillis = null;
return childThreadSolverScope;
}
public void initializeYielding() {
if (runnableThreadSemaphore != null) {
try {
runnableThreadSemaphore.acquire();
} catch (InterruptedException e) {
// TODO it will take a while before the BasicPlumbingTermination is called
// The BasicPlumbingTermination will terminate the solver.
Thread.currentThread().interrupt();
}
}
}
/**
* Similar to {@link Thread#yield()}, but allows capping the number of active solver threads
* at less than the CPU processor count, so other threads (for example servlet threads that handle REST calls)
* and other processes (such as SSH) have access to uncontested CPUs and don't suffer any latency.
* <p>
* Needs to be called <b>before</b> {@link Termination#isPhaseTerminated(AbstractPhaseScope)},
* so the decision to start a new iteration is after any yield waiting time has been consumed
* (so {@link Solver#terminateEarly()} reacts immediately).
*/
public void checkYielding() {
if (runnableThreadSemaphore != null) {
runnableThreadSemaphore.release();
try {
runnableThreadSemaphore.acquire();
} catch (InterruptedException e) {
// The BasicPlumbingTermination will terminate the solver.
Thread.currentThread().interrupt();
}
}
}
public void destroyYielding() {
if (runnableThreadSemaphore != null) {
runnableThreadSemaphore.release();
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/termination/AbstractCompositeTermination.java | package ai.timefold.solver.core.impl.solver.termination;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
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;
/**
* Abstract superclass that combines multiple {@link Termination}s.
*
* @see AndCompositeTermination
* @see OrCompositeTermination
*/
public abstract class AbstractCompositeTermination<Solution_> extends AbstractTermination<Solution_> {
protected final List<Termination<Solution_>> terminationList;
protected AbstractCompositeTermination(List<Termination<Solution_>> terminationList) {
this.terminationList = terminationList;
}
public AbstractCompositeTermination(Termination<Solution_>... terminations) {
this(Arrays.asList(terminations));
}
// ************************************************************************
// Lifecycle methods
// ************************************************************************
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
for (Termination<Solution_> termination : terminationList) {
termination.solvingStarted(solverScope);
}
}
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
for (Termination<Solution_> termination : terminationList) {
termination.phaseStarted(phaseScope);
}
}
@Override
public void stepStarted(AbstractStepScope<Solution_> stepScope) {
for (Termination<Solution_> termination : terminationList) {
termination.stepStarted(stepScope);
}
}
@Override
public void stepEnded(AbstractStepScope<Solution_> stepScope) {
for (Termination<Solution_> termination : terminationList) {
termination.stepEnded(stepScope);
}
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
for (Termination<Solution_> termination : terminationList) {
termination.phaseEnded(phaseScope);
}
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
for (Termination<Solution_> termination : terminationList) {
termination.solvingEnded(solverScope);
}
}
// ************************************************************************
// Other methods
// ************************************************************************
protected List<Termination<Solution_>> createChildThreadTerminationList(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
List<Termination<Solution_>> childThreadTerminationList = new ArrayList<>(terminationList.size());
for (Termination<Solution_> termination : terminationList) {
childThreadTerminationList.add(termination.createChildThreadTermination(solverScope, childThreadType));
}
return childThreadTerminationList;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/termination/AbstractTermination.java | package ai.timefold.solver.core.impl.solver.termination;
import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleListenerAdapter;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract superclass for {@link Termination}.
*/
public abstract class AbstractTermination<Solution_> extends PhaseLifecycleListenerAdapter<Solution_>
implements Termination<Solution_> {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
throw new UnsupportedOperationException("This terminationClass (" + getClass()
+ ") does not yet support being used in child threads of type (" + childThreadType + ").");
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/termination/AndCompositeTermination.java | package ai.timefold.solver.core.impl.solver.termination;
import java.util.List;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
public class AndCompositeTermination<Solution_> extends AbstractCompositeTermination<Solution_> {
public AndCompositeTermination(List<Termination<Solution_>> terminationList) {
super(terminationList);
}
public AndCompositeTermination(Termination<Solution_>... terminations) {
super(terminations);
}
// ************************************************************************
// Terminated methods
// ************************************************************************
/**
* @param solverScope never null
* @return true if all the Terminations are terminated.
*/
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
for (Termination<Solution_> termination : terminationList) {
if (!termination.isSolverTerminated(solverScope)) {
return false;
}
}
return true;
}
/**
* @param phaseScope never null
* @return true if all the Terminations are terminated.
*/
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
for (Termination<Solution_> termination : terminationList) {
if (!termination.isPhaseTerminated(phaseScope)) {
return false;
}
}
return true;
}
// ************************************************************************
// Time gradient methods
// ************************************************************************
/**
* Calculates the minimum timeGradient of all Terminations.
* Not supported timeGradients (-1.0) are ignored.
*
* @param solverScope never null
* @return the minimum timeGradient of the Terminations.
*/
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
double timeGradient = 1.0;
for (Termination<Solution_> termination : terminationList) {
double nextTimeGradient = termination.calculateSolverTimeGradient(solverScope);
if (nextTimeGradient >= 0.0) {
timeGradient = Math.min(timeGradient, nextTimeGradient);
}
}
return timeGradient;
}
/**
* Calculates the minimum timeGradient of all Terminations.
* Not supported timeGradients (-1.0) are ignored.
*
* @param phaseScope never null
* @return the minimum timeGradient of the Terminations.
*/
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
double timeGradient = 1.0;
for (Termination<Solution_> termination : terminationList) {
double nextTimeGradient = termination.calculatePhaseTimeGradient(phaseScope);
if (nextTimeGradient >= 0.0) {
timeGradient = Math.min(timeGradient, nextTimeGradient);
}
}
return timeGradient;
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public AndCompositeTermination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
return new AndCompositeTermination<>(createChildThreadTerminationList(solverScope, childThreadType));
}
@Override
public String toString() {
return "And(" + terminationList + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/termination/BasicPlumbingTermination.java | package ai.timefold.solver.core.impl.solver.termination;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.solver.change.ProblemChangeAdapter;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
/**
* Concurrency notes:
* Condition predicate on ({@link #problemFactChangeQueue} is not empty or {@link #terminatedEarly} is true).
*/
public class BasicPlumbingTermination<Solution_> extends AbstractTermination<Solution_> {
protected final boolean daemon;
protected boolean terminatedEarly = false;
protected BlockingQueue<ProblemChangeAdapter<Solution_>> problemFactChangeQueue = new LinkedBlockingQueue<>();
protected boolean problemFactChangesBeingProcessed = false;
public BasicPlumbingTermination(boolean daemon) {
this.daemon = daemon;
}
// ************************************************************************
// Plumbing worker methods
// ************************************************************************
/**
* This method is thread-safe.
*/
public synchronized void resetTerminateEarly() {
terminatedEarly = false;
}
/**
* This method is thread-safe.
* <p>
* Concurrency note: unblocks {@link #waitForRestartSolverDecision()}.
*
* @return true if successful
*/
public synchronized boolean terminateEarly() {
boolean terminationEarlySuccessful = !terminatedEarly;
terminatedEarly = true;
notifyAll();
return terminationEarlySuccessful;
}
/**
* This method is thread-safe.
*/
public synchronized boolean isTerminateEarly() {
return terminatedEarly;
}
/**
* If this returns true, then the problemFactChangeQueue is definitely not empty.
* <p>
* Concurrency note: Blocks until {@link #problemFactChangeQueue} is not empty or {@link #terminatedEarly} is true.
*
* @return true if the solver needs to be restarted
*/
public synchronized boolean waitForRestartSolverDecision() {
if (!daemon) {
return !problemFactChangeQueue.isEmpty() && !terminatedEarly;
} else {
while (problemFactChangeQueue.isEmpty() && !terminatedEarly) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Solver thread was interrupted during Object.wait().", e);
}
}
return !terminatedEarly;
}
}
/**
* Concurrency note: unblocks {@link #waitForRestartSolverDecision()}.
*
* @param problemChange never null
* @return as specified by {@link Collection#add}
*/
public synchronized boolean addProblemChange(ProblemChangeAdapter<Solution_> problemChange) {
boolean added = problemFactChangeQueue.add(problemChange);
notifyAll();
return added;
}
/**
* Concurrency note: unblocks {@link #waitForRestartSolverDecision()}.
*
* @param problemChangeList never null
* @return as specified by {@link Collection#add}
*/
public synchronized boolean addProblemChanges(List<ProblemChangeAdapter<Solution_>> problemChangeList) {
boolean added = problemFactChangeQueue.addAll(problemChangeList);
notifyAll();
return added;
}
public synchronized BlockingQueue<ProblemChangeAdapter<Solution_>> startProblemFactChangesProcessing() {
problemFactChangesBeingProcessed = true;
return problemFactChangeQueue;
}
public synchronized void endProblemFactChangesProcessing() {
problemFactChangesBeingProcessed = false;
}
public synchronized boolean isEveryProblemFactChangeProcessed() {
return problemFactChangeQueue.isEmpty() && !problemFactChangesBeingProcessed;
}
// ************************************************************************
// Termination worker methods
// ************************************************************************
@Override
public synchronized boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
// Destroying a thread pool with solver threads will only cause it to interrupt those solver threads,
// it won't call Solver.terminateEarly()
if (Thread.currentThread().isInterrupted() // Does not clear the interrupted flag
// Avoid duplicate log message because this method is called twice:
// - in the phase step loop (every phase termination bridges to the solver termination)
// - in the solver's phase loop
&& !terminatedEarly) {
logger.info("The solver thread got interrupted, so this solver is terminating early.");
terminatedEarly = true;
}
return terminatedEarly || !problemFactChangeQueue.isEmpty();
}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
throw new IllegalStateException(BasicPlumbingTermination.class.getSimpleName()
+ " configured only as solver termination."
+ " It is always bridged to phase termination.");
}
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
return -1.0; // Not supported
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
throw new IllegalStateException(BasicPlumbingTermination.class.getSimpleName()
+ " configured only as solver termination."
+ " It is always bridged to phase termination.");
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
return this;
}
@Override
public String toString() {
return "BasicPlumbing()";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/termination/BestScoreFeasibleTermination.java | package ai.timefold.solver.core.impl.solver.termination;
import java.util.Arrays;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
public class BestScoreFeasibleTermination<Solution_> extends AbstractTermination<Solution_> {
private final int feasibleLevelsSize;
private final double[] timeGradientWeightFeasibleNumbers;
public BestScoreFeasibleTermination(ScoreDefinition scoreDefinition, double[] timeGradientWeightFeasibleNumbers) {
feasibleLevelsSize = scoreDefinition.getFeasibleLevelsSize();
this.timeGradientWeightFeasibleNumbers = timeGradientWeightFeasibleNumbers;
if (timeGradientWeightFeasibleNumbers.length != feasibleLevelsSize - 1) {
throw new IllegalStateException(
"The timeGradientWeightNumbers (" + Arrays.toString(timeGradientWeightFeasibleNumbers)
+ ")'s length (" + timeGradientWeightFeasibleNumbers.length
+ ") is not 1 less than the feasibleLevelsSize (" + scoreDefinition.getFeasibleLevelsSize()
+ ").");
}
}
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
return isTerminated(solverScope.getBestScore());
}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
return isTerminated((Score) phaseScope.getBestScore());
}
protected boolean isTerminated(Score bestScore) {
return bestScore.isFeasible();
}
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
return calculateFeasibilityTimeGradient(solverScope.getStartingInitializedScore(), solverScope.getBestScore());
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
return calculateFeasibilityTimeGradient((Score) phaseScope.getStartingScore(), (Score) phaseScope.getBestScore());
}
protected <Score_ extends Score<Score_>> double calculateFeasibilityTimeGradient(Score_ startScore, Score_ score) {
if (startScore == null || !startScore.isSolutionInitialized()) {
return 0.0;
}
Score_ totalDiff = startScore.negate();
Number[] totalDiffNumbers = totalDiff.toLevelNumbers();
Score_ scoreDiff = score.subtract(startScore);
Number[] scoreDiffNumbers = scoreDiff.toLevelNumbers();
if (scoreDiffNumbers.length != totalDiffNumbers.length) {
throw new IllegalStateException("The startScore (" + startScore + ") and score (" + score
+ ") don't have the same levelsSize.");
}
return BestScoreTermination.calculateTimeGradient(totalDiffNumbers, scoreDiffNumbers,
timeGradientWeightFeasibleNumbers, feasibleLevelsSize);
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
// TODO FIXME through some sort of solverlistener and async behaviour...
throw new UnsupportedOperationException("This terminationClass (" + getClass()
+ ") does not yet support being used in child threads of type (" + childThreadType + ").");
}
@Override
public String toString() {
return "BestScoreFeasible()";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/termination/BestScoreTermination.java | package ai.timefold.solver.core.impl.solver.termination;
import java.util.Arrays;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
public class BestScoreTermination<Solution_> extends AbstractTermination<Solution_> {
private final int levelsSize;
private final Score bestScoreLimit;
private final double[] timeGradientWeightNumbers;
public BestScoreTermination(ScoreDefinition scoreDefinition, Score bestScoreLimit, double[] timeGradientWeightNumbers) {
levelsSize = scoreDefinition.getLevelsSize();
this.bestScoreLimit = bestScoreLimit;
if (bestScoreLimit == null) {
throw new IllegalArgumentException("The bestScoreLimit (" + bestScoreLimit
+ ") cannot be null.");
}
this.timeGradientWeightNumbers = timeGradientWeightNumbers;
if (timeGradientWeightNumbers.length != levelsSize - 1) {
throw new IllegalStateException(
"The timeGradientWeightNumbers (" + Arrays.toString(timeGradientWeightNumbers)
+ ")'s length (" + timeGradientWeightNumbers.length
+ ") is not 1 less than the levelsSize (" + scoreDefinition.getLevelsSize() + ").");
}
}
// ************************************************************************
// Terminated methods
// ************************************************************************
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
return isTerminated(solverScope.isBestSolutionInitialized(), solverScope.getBestScore());
}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
return isTerminated(phaseScope.isBestSolutionInitialized(), (Score) phaseScope.getBestScore());
}
protected boolean isTerminated(boolean bestSolutionInitialized, Score bestScore) {
return bestSolutionInitialized && bestScore.compareTo(bestScoreLimit) >= 0;
}
// ************************************************************************
// Time gradient methods
// ************************************************************************
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
Score startingInitializedScore = solverScope.getStartingInitializedScore();
Score bestScore = solverScope.getBestScore();
return calculateTimeGradient(startingInitializedScore, bestScoreLimit, bestScore);
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
Score startingInitializedScore = phaseScope.getStartingScore();
Score bestScore = phaseScope.getBestScore();
return calculateTimeGradient(startingInitializedScore, bestScoreLimit, bestScore);
}
protected <Score_ extends Score<Score_>> double calculateTimeGradient(Score_ startScore, Score_ endScore,
Score_ score) {
Score_ totalDiff = endScore.subtract(startScore);
Number[] totalDiffNumbers = totalDiff.toLevelNumbers();
Score_ scoreDiff = score.subtract(startScore);
Number[] scoreDiffNumbers = scoreDiff.toLevelNumbers();
if (scoreDiffNumbers.length != totalDiffNumbers.length) {
throw new IllegalStateException("The startScore (" + startScore + "), endScore (" + endScore
+ ") and score (" + score + ") don't have the same levelsSize.");
}
return calculateTimeGradient(totalDiffNumbers, scoreDiffNumbers, timeGradientWeightNumbers,
levelsSize);
}
/**
*
* @param totalDiffNumbers never null
* @param scoreDiffNumbers never null
* @param timeGradientWeightNumbers never null
* @param levelDepth The number of levels of the diffNumbers that are included
* @return {@code 0.0 <= value <= 1.0}
*/
static double calculateTimeGradient(Number[] totalDiffNumbers, Number[] scoreDiffNumbers,
double[] timeGradientWeightNumbers, int levelDepth) {
double timeGradient = 0.0;
double remainingTimeGradient = 1.0;
for (int i = 0; i < levelDepth; i++) {
double levelTimeGradientWeight;
if (i != (levelDepth - 1)) {
levelTimeGradientWeight = remainingTimeGradient * timeGradientWeightNumbers[i];
remainingTimeGradient -= levelTimeGradientWeight;
} else {
levelTimeGradientWeight = remainingTimeGradient;
remainingTimeGradient = 0.0;
}
double totalDiffLevel = totalDiffNumbers[i].doubleValue();
double scoreDiffLevel = scoreDiffNumbers[i].doubleValue();
if (scoreDiffLevel == totalDiffLevel) {
// Max out this level
timeGradient += levelTimeGradientWeight;
} else if (scoreDiffLevel > totalDiffLevel) {
// Max out this level and all softer levels too
timeGradient += levelTimeGradientWeight + remainingTimeGradient;
break;
} else if (scoreDiffLevel == 0.0) {
// Ignore this level
// timeGradient += 0.0
} else if (scoreDiffLevel < 0.0) {
// Ignore this level and all softer levels too
// timeGradient += 0.0
break;
} else {
double levelTimeGradient = scoreDiffLevel / totalDiffLevel;
timeGradient += levelTimeGradient * levelTimeGradientWeight;
}
}
if (timeGradient > 1.0) {
// Rounding error due to calculating with doubles
timeGradient = 1.0;
}
return timeGradient;
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
// TODO FIXME through some sort of solverlistener and async behaviour...
throw new UnsupportedOperationException("This terminationClass (" + getClass()
+ ") does not yet support being used in child threads of type (" + childThreadType + ").");
}
@Override
public String toString() {
return "BestScore(" + bestScoreLimit + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/termination/ChildThreadPlumbingTermination.java | package ai.timefold.solver.core.impl.solver.termination;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
public class ChildThreadPlumbingTermination<Solution_> extends AbstractTermination<Solution_> {
protected boolean terminateChildren = false;
// ************************************************************************
// Plumbing worker methods
// ************************************************************************
/**
* This method is thread-safe.
*
* @return true if termination hasn't been requested previously
*/
public synchronized boolean terminateChildren() {
boolean terminationEarlySuccessful = !terminateChildren;
terminateChildren = true;
return terminationEarlySuccessful;
}
// ************************************************************************
// Termination worker methods
// ************************************************************************
@Override
public synchronized boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
// Destroying a thread pool with solver threads will only cause it to interrupt those child solver threads
if (Thread.currentThread().isInterrupted()) { // Does not clear the interrupted flag
logger.info("A child solver thread got interrupted, so these child solvers are terminating early.");
terminateChildren = true;
}
return terminateChildren;
}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
throw new IllegalStateException(ChildThreadPlumbingTermination.class.getSimpleName()
+ " configured only as solver termination."
+ " It is always bridged to phase termination.");
}
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
return -1.0; // Not supported
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
throw new IllegalStateException(ChildThreadPlumbingTermination.class.getSimpleName()
+ " configured only as solver termination."
+ " It is always bridged to phase termination.");
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
return this;
}
@Override
public String toString() {
return "ChildThreadPlumbing()";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/termination/OrCompositeTermination.java | package ai.timefold.solver.core.impl.solver.termination;
import java.util.List;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
public class OrCompositeTermination<Solution_> extends AbstractCompositeTermination<Solution_> {
public OrCompositeTermination(List<Termination<Solution_>> terminationList) {
super(terminationList);
}
public OrCompositeTermination(Termination<Solution_>... terminations) {
super(terminations);
}
// ************************************************************************
// Terminated methods
// ************************************************************************
/**
* @param solverScope never null
* @return true if any of the Termination is terminated.
*/
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
for (Termination<Solution_> termination : terminationList) {
if (termination.isSolverTerminated(solverScope)) {
return true;
}
}
return false;
}
/**
* @param phaseScope never null
* @return true if any of the Termination is terminated.
*/
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
for (Termination<Solution_> termination : terminationList) {
if (termination.isPhaseTerminated(phaseScope)) {
return true;
}
}
return false;
}
// ************************************************************************
// Time gradient methods
// ************************************************************************
/**
* Calculates the maximum timeGradient of all Terminations.
* Not supported timeGradients (-1.0) are ignored.
*
* @param solverScope never null
* @return the maximum timeGradient of the Terminations.
*/
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
double timeGradient = 0.0;
for (Termination<Solution_> termination : terminationList) {
double nextTimeGradient = termination.calculateSolverTimeGradient(solverScope);
if (nextTimeGradient >= 0.0) {
timeGradient = Math.max(timeGradient, nextTimeGradient);
}
}
return timeGradient;
}
/**
* Calculates the maximum timeGradient of all Terminations.
* Not supported timeGradients (-1.0) are ignored.
*
* @param phaseScope never null
* @return the maximum timeGradient of the Terminations.
*/
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
double timeGradient = 0.0;
for (Termination<Solution_> termination : terminationList) {
double nextTimeGradient = termination.calculatePhaseTimeGradient(phaseScope);
if (nextTimeGradient >= 0.0) {
timeGradient = Math.max(timeGradient, nextTimeGradient);
}
}
return timeGradient;
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public OrCompositeTermination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
return new OrCompositeTermination<>(createChildThreadTerminationList(solverScope, childThreadType));
}
@Override
public String toString() {
return "Or(" + terminationList + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/termination/PhaseToSolverTerminationBridge.java | package ai.timefold.solver.core.impl.solver.termination;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
public class PhaseToSolverTerminationBridge<Solution_> extends AbstractTermination<Solution_> {
private final Termination<Solution_> solverTermination;
public PhaseToSolverTerminationBridge(Termination<Solution_> solverTermination) {
this.solverTermination = solverTermination;
}
// ************************************************************************
// Lifecycle methods
// ************************************************************************
// Do not propagate any of the lifecycle events up to the solverTermination,
// because it already gets the solver events from the DefaultSolver
// and the phase/step events - if ever needed - should also come through the DefaultSolver
// ************************************************************************
// Terminated methods
// ************************************************************************
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
throw new UnsupportedOperationException(
getClass().getSimpleName() + " can only be used for phase termination.");
}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
return solverTermination.isSolverTerminated(phaseScope.getSolverScope());
}
// ************************************************************************
// Time gradient methods
// ************************************************************************
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
throw new UnsupportedOperationException(
getClass().getSimpleName() + " can only be used for phase termination.");
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
return solverTermination.calculateSolverTimeGradient(phaseScope.getSolverScope());
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
if (childThreadType == ChildThreadType.PART_THREAD) {
// Remove of the bridge (which is nested if there's a phase termination), PhaseConfig will add it again
return solverTermination.createChildThreadTermination(solverScope, childThreadType);
} else {
throw new IllegalStateException("The childThreadType (" + childThreadType + ") is not implemented.");
}
}
@Override
public String toString() {
return "Bridge(" + solverTermination + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/termination/ScoreCalculationCountTermination.java | package ai.timefold.solver.core.impl.solver.termination;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
public class ScoreCalculationCountTermination<Solution_> extends AbstractTermination<Solution_> {
private final long scoreCalculationCountLimit;
public ScoreCalculationCountTermination(long scoreCalculationCountLimit) {
this.scoreCalculationCountLimit = scoreCalculationCountLimit;
if (scoreCalculationCountLimit < 0L) {
throw new IllegalArgumentException("The scoreCalculationCountLimit (" + scoreCalculationCountLimit
+ ") cannot be negative.");
}
}
// ************************************************************************
// Terminated methods
// ************************************************************************
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
return isTerminated(solverScope.getScoreDirector());
}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
return isTerminated(phaseScope.getScoreDirector());
}
protected boolean isTerminated(InnerScoreDirector<Solution_, ?> scoreDirector) {
long scoreCalculationCount = scoreDirector.getCalculationCount();
return scoreCalculationCount >= scoreCalculationCountLimit;
}
// ************************************************************************
// Time gradient methods
// ************************************************************************
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
return calculateTimeGradient(solverScope.getScoreDirector());
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
return calculateTimeGradient(phaseScope.getScoreDirector());
}
protected double calculateTimeGradient(InnerScoreDirector<Solution_, ?> scoreDirector) {
long scoreCalculationCount = scoreDirector.getCalculationCount();
double timeGradient = scoreCalculationCount / ((double) scoreCalculationCountLimit);
return Math.min(timeGradient, 1.0);
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public ScoreCalculationCountTermination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
if (childThreadType == ChildThreadType.PART_THREAD) {
// The ScoreDirector.calculationCount of partitions is maxed, not summed.
return new ScoreCalculationCountTermination<>(scoreCalculationCountLimit);
} else {
throw new IllegalStateException("The childThreadType (" + childThreadType + ") is not implemented.");
}
}
@Override
public String toString() {
return "ScoreCalculationCount(" + scoreCalculationCountLimit + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/termination/StepCountTermination.java | package ai.timefold.solver.core.impl.solver.termination;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
public class StepCountTermination<Solution_> extends AbstractTermination<Solution_> {
private final int stepCountLimit;
public StepCountTermination(int stepCountLimit) {
this.stepCountLimit = stepCountLimit;
if (stepCountLimit < 0) {
throw new IllegalArgumentException("The stepCountLimit (" + stepCountLimit
+ ") cannot be negative.");
}
}
public int getStepCountLimit() {
return stepCountLimit;
}
// ************************************************************************
// Terminated methods
// ************************************************************************
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
throw new UnsupportedOperationException(
getClass().getSimpleName() + " can only be used for phase termination.");
}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
int nextStepIndex = phaseScope.getNextStepIndex();
return nextStepIndex >= stepCountLimit;
}
// ************************************************************************
// Time gradient methods
// ************************************************************************
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
throw new UnsupportedOperationException(
getClass().getSimpleName() + " can only be used for phase termination.");
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
int nextStepIndex = phaseScope.getNextStepIndex();
double timeGradient = nextStepIndex / ((double) stepCountLimit);
return Math.min(timeGradient, 1.0);
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public StepCountTermination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
return new StepCountTermination<>(stepCountLimit);
}
@Override
public String toString() {
return "StepCount(" + stepCountLimit + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/termination/Termination.java | package ai.timefold.solver.core.impl.solver.termination;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.simulatedannealing.SimulatedAnnealingAcceptor;
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 ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
/**
* A Termination determines when a {@link Solver} or a {@link Phase} should stop.
* <p>
* An implementation must extend {@link AbstractTermination} to ensure backwards compatibility in future versions.
*
* @see AbstractTermination
*/
public interface Termination<Solution_> extends PhaseLifecycleListener<Solution_> {
/**
* Called by the {@link Solver} after every phase to determine if the search should stop.
*
* @param solverScope never null
* @return true if the search should terminate.
*/
boolean isSolverTerminated(SolverScope<Solution_> solverScope);
/**
* Called by the {@link Phase} after every step and every move to determine if the search should stop.
*
* @param phaseScope never null
* @return true if the search should terminate.
*/
boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope);
/**
* A timeGradient is a relative estimate of how long the search will continue.
* <p>
* Clients that use a timeGradient should cache it at the start of a single step
* because some implementations are not time-stable.
* <p>
* If a timeGradient cannot be calculated, it should return -1.0.
* Several implementations (such a {@link SimulatedAnnealingAcceptor}) require a correctly implemented timeGradient.
* <p>
* A Termination's timeGradient can be requested after they are terminated, so implementations
* should be careful not to return a timeGradient above 1.0.
*
* @param solverScope never null
* @return timeGradient t for which {@code 0.0 <= t <= 1.0 or -1.0} when it is not supported.
* At the start of a solver t is 0.0 and at the end t would be 1.0.
*/
double calculateSolverTimeGradient(SolverScope<Solution_> solverScope);
/**
* See {@link #calculateSolverTimeGradient(SolverScope)}.
*
* @param phaseScope never null
* @return timeGradient t for which {@code 0.0 <= t <= 1.0 or -1.0} when it is not supported.
* At the start of a phase t is 0.0 and at the end t would be 1.0.
*/
double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope);
/**
* Create a {@link Termination} for a child {@link Thread} of the {@link Solver}.
*
* @param solverScope never null
* @param childThreadType never null
* @return not null
* @throws UnsupportedOperationException if not supported by this termination
*/
Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope, ChildThreadType childThreadType);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/termination/TerminationFactory.java | package ai.timefold.solver.core.impl.solver.termination;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.config.solver.termination.TerminationCompositionStyle;
import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
public class TerminationFactory<Solution_> {
public static <Solution_> TerminationFactory<Solution_> create(TerminationConfig terminationConfig) {
return new TerminationFactory<>(terminationConfig);
}
private final TerminationConfig terminationConfig;
private TerminationFactory(TerminationConfig terminationConfig) {
this.terminationConfig = terminationConfig;
}
public Termination<Solution_> buildTermination(HeuristicConfigPolicy<Solution_> configPolicy,
Termination<Solution_> chainedTermination) {
Termination<Solution_> termination = buildTermination(configPolicy);
if (termination == null) {
return chainedTermination;
}
return new OrCompositeTermination<>(chainedTermination, termination);
}
/**
* @param configPolicy never null
* @return sometimes null
*/
public <Score_ extends Score<Score_>> Termination<Solution_> buildTermination(
HeuristicConfigPolicy<Solution_> configPolicy) {
List<Termination<Solution_>> terminationList = new ArrayList<>();
if (terminationConfig.getTerminationClass() != null) {
Termination<Solution_> termination =
ConfigUtils.newInstance(terminationConfig, "terminationClass", terminationConfig.getTerminationClass());
terminationList.add(termination);
}
terminationList.addAll(buildTimeBasedTermination(configPolicy));
if (terminationConfig.getBestScoreLimit() != null) {
ScoreDefinition<Score_> scoreDefinition = configPolicy.getScoreDefinition();
Score_ bestScoreLimit_ = scoreDefinition.parseScore(terminationConfig.getBestScoreLimit());
double[] timeGradientWeightNumbers = new double[scoreDefinition.getLevelsSize() - 1];
Arrays.fill(timeGradientWeightNumbers, 0.50); // Number pulled out of thin air
terminationList.add(new BestScoreTermination<>(scoreDefinition, bestScoreLimit_, timeGradientWeightNumbers));
}
if (terminationConfig.getBestScoreFeasible() != null) {
ScoreDefinition<Score_> scoreDefinition = configPolicy.getScoreDefinition();
if (!terminationConfig.getBestScoreFeasible()) {
throw new IllegalArgumentException("The termination bestScoreFeasible ("
+ terminationConfig.getBestScoreFeasible() + ") cannot be false.");
}
int feasibleLevelsSize = scoreDefinition.getFeasibleLevelsSize();
if (feasibleLevelsSize < 1) {
throw new IllegalStateException("The termination with bestScoreFeasible ("
+ terminationConfig.getBestScoreFeasible()
+ ") can only be used with a score type that has at least 1 feasible level but the scoreDefinition ("
+ scoreDefinition + ") has feasibleLevelsSize (" + feasibleLevelsSize + "), which is less than 1.");
}
double[] timeGradientWeightFeasibleNumbers = new double[feasibleLevelsSize - 1];
Arrays.fill(timeGradientWeightFeasibleNumbers, 0.50); // Number pulled out of thin air
terminationList.add(new BestScoreFeasibleTermination<>(scoreDefinition, timeGradientWeightFeasibleNumbers));
}
if (terminationConfig.getStepCountLimit() != null) {
terminationList.add(new StepCountTermination<>(terminationConfig.getStepCountLimit()));
}
if (terminationConfig.getScoreCalculationCountLimit() != null) {
terminationList.add(new ScoreCalculationCountTermination<>(terminationConfig.getScoreCalculationCountLimit()));
}
if (terminationConfig.getUnimprovedStepCountLimit() != null) {
terminationList.add(new UnimprovedStepCountTermination<>(terminationConfig.getUnimprovedStepCountLimit()));
}
terminationList.addAll(buildInnerTermination(configPolicy));
return buildTerminationFromList(terminationList);
}
protected <Score_ extends Score<Score_>> List<Termination<Solution_>>
buildTimeBasedTermination(HeuristicConfigPolicy<Solution_> configPolicy) {
List<Termination<Solution_>> terminationList = new ArrayList<>();
Long timeMillisSpentLimit = terminationConfig.calculateTimeMillisSpentLimit();
if (timeMillisSpentLimit != null) {
terminationList.add(new TimeMillisSpentTermination<>(timeMillisSpentLimit));
}
Long unimprovedTimeMillisSpentLimit = terminationConfig.calculateUnimprovedTimeMillisSpentLimit();
if (unimprovedTimeMillisSpentLimit != null) {
if (terminationConfig.getUnimprovedScoreDifferenceThreshold() == null) {
terminationList.add(new UnimprovedTimeMillisSpentTermination<>(unimprovedTimeMillisSpentLimit));
} else {
ScoreDefinition<Score_> scoreDefinition = configPolicy.getScoreDefinition();
Score_ unimprovedScoreDifferenceThreshold_ =
scoreDefinition.parseScore(terminationConfig.getUnimprovedScoreDifferenceThreshold());
if (scoreDefinition.isNegativeOrZero(unimprovedScoreDifferenceThreshold_)) {
throw new IllegalStateException("The unimprovedScoreDifferenceThreshold ("
+ terminationConfig.getUnimprovedScoreDifferenceThreshold() + ") must be positive.");
}
terminationList.add(new UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination<>(
unimprovedTimeMillisSpentLimit, unimprovedScoreDifferenceThreshold_));
}
} else if (terminationConfig.getUnimprovedScoreDifferenceThreshold() != null) {
throw new IllegalStateException("The unimprovedScoreDifferenceThreshold ("
+ terminationConfig.getUnimprovedScoreDifferenceThreshold()
+ ") can only be used if an unimproved*SpentLimit ("
+ unimprovedTimeMillisSpentLimit + ") is used too.");
}
return terminationList;
}
protected List<Termination<Solution_>> buildInnerTermination(HeuristicConfigPolicy<Solution_> configPolicy) {
if (ConfigUtils.isEmptyCollection(terminationConfig.getTerminationConfigList())) {
return Collections.emptyList();
}
return terminationConfig.getTerminationConfigList().stream()
.map(config -> TerminationFactory.<Solution_> create(config)
.buildTermination(configPolicy))
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
protected Termination<Solution_> buildTerminationFromList(List<Termination<Solution_>> terminationList) {
if (terminationList.isEmpty()) {
return null;
} else if (terminationList.size() == 1) {
return terminationList.get(0);
} else {
AbstractCompositeTermination<Solution_> compositeTermination;
if (terminationConfig.getTerminationCompositionStyle() == null
|| terminationConfig.getTerminationCompositionStyle() == TerminationCompositionStyle.OR) {
compositeTermination = new OrCompositeTermination<>(terminationList);
} else if (terminationConfig.getTerminationCompositionStyle() == TerminationCompositionStyle.AND) {
compositeTermination = new AndCompositeTermination<>(terminationList);
} else {
throw new IllegalStateException("The terminationCompositionStyle ("
+ terminationConfig.getTerminationCompositionStyle() + ") is not implemented.");
}
return compositeTermination;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/termination/TimeMillisSpentTermination.java | package ai.timefold.solver.core.impl.solver.termination;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
public class TimeMillisSpentTermination<Solution_> extends AbstractTermination<Solution_> {
private final long timeMillisSpentLimit;
public TimeMillisSpentTermination(long timeMillisSpentLimit) {
this.timeMillisSpentLimit = timeMillisSpentLimit;
if (timeMillisSpentLimit < 0L) {
throw new IllegalArgumentException("The timeMillisSpentLimit (" + timeMillisSpentLimit
+ ") cannot be negative.");
}
}
public long getTimeMillisSpentLimit() {
return timeMillisSpentLimit;
}
// ************************************************************************
// Terminated methods
// ************************************************************************
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
long solverTimeMillisSpent = solverScope.calculateTimeMillisSpentUpToNow();
return isTerminated(solverTimeMillisSpent);
}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
long phaseTimeMillisSpent = phaseScope.calculatePhaseTimeMillisSpentUpToNow();
return isTerminated(phaseTimeMillisSpent);
}
protected boolean isTerminated(long timeMillisSpent) {
return timeMillisSpent >= timeMillisSpentLimit;
}
// ************************************************************************
// Time gradient methods
// ************************************************************************
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
long solverTimeMillisSpent = solverScope.calculateTimeMillisSpentUpToNow();
return calculateTimeGradient(solverTimeMillisSpent);
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
long phaseTimeMillisSpent = phaseScope.calculatePhaseTimeMillisSpentUpToNow();
return calculateTimeGradient(phaseTimeMillisSpent);
}
protected double calculateTimeGradient(long timeMillisSpent) {
double timeGradient = timeMillisSpent / ((double) timeMillisSpentLimit);
return Math.min(timeGradient, 1.0);
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public TimeMillisSpentTermination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
return new TimeMillisSpentTermination<>(timeMillisSpentLimit);
}
@Override
public String toString() {
return "TimeMillisSpent(" + timeMillisSpentLimit + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver/termination/UnimprovedStepCountTermination.java | package ai.timefold.solver.core.impl.solver.termination;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
public class UnimprovedStepCountTermination<Solution_> extends AbstractTermination<Solution_> {
private final int unimprovedStepCountLimit;
public UnimprovedStepCountTermination(int unimprovedStepCountLimit) {
this.unimprovedStepCountLimit = unimprovedStepCountLimit;
if (unimprovedStepCountLimit < 0) {
throw new IllegalArgumentException("The unimprovedStepCountLimit (" + unimprovedStepCountLimit
+ ") cannot be negative.");
}
}
public int getUnimprovedStepCountLimit() {
return unimprovedStepCountLimit;
}
// ************************************************************************
// Terminated methods
// ************************************************************************
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
throw new UnsupportedOperationException(
getClass().getSimpleName() + " can only be used for phase termination.");
}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
int unimprovedStepCount = calculateUnimprovedStepCount(phaseScope);
return unimprovedStepCount >= unimprovedStepCountLimit;
}
protected int calculateUnimprovedStepCount(AbstractPhaseScope<Solution_> phaseScope) {
int bestStepIndex = phaseScope.getBestSolutionStepIndex();
int lastStepIndex = phaseScope.getLastCompletedStepScope().getStepIndex();
return lastStepIndex - bestStepIndex;
}
// ************************************************************************
// Time gradient methods
// ************************************************************************
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
throw new UnsupportedOperationException(
getClass().getSimpleName() + " can only be used for phase termination.");
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
int unimprovedStepCount = calculateUnimprovedStepCount(phaseScope);
double timeGradient = unimprovedStepCount / ((double) unimprovedStepCountLimit);
return Math.min(timeGradient, 1.0);
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public UnimprovedStepCountTermination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope,
ChildThreadType childThreadType) {
return new UnimprovedStepCountTermination<>(unimprovedStepCountLimit);
}
@Override
public String toString() {
return "UnimprovedStepCount(" + unimprovedStepCountLimit + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.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.Iterator;
import java.util.Queue;
import ai.timefold.solver.core.api.score.Score;
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 ai.timefold.solver.core.impl.util.Pair;
public class UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination<Solution_>
extends AbstractTermination<Solution_> {
private final long unimprovedTimeMillisSpentLimit;
private final Score unimprovedScoreDifferenceThreshold;
private final Clock clock;
private Queue<Pair<Long, Score>> bestScoreImprovementHistoryQueue;
// safeTimeMillis is until when we're safe from termination
private long solverSafeTimeMillis = -1L;
private long phaseSafeTimeMillis = -1L;
public UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination(
long unimprovedTimeMillisSpentLimit,
Score unimprovedScoreDifferenceThreshold) {
this(unimprovedTimeMillisSpentLimit, unimprovedScoreDifferenceThreshold, Clock.systemUTC());
}
protected UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination(
long unimprovedTimeMillisSpentLimit,
Score unimprovedScoreDifferenceThreshold,
Clock clock) {
this.unimprovedTimeMillisSpentLimit = unimprovedTimeMillisSpentLimit;
this.unimprovedScoreDifferenceThreshold = unimprovedScoreDifferenceThreshold;
if (unimprovedTimeMillisSpentLimit < 0L) {
throw new IllegalArgumentException("The unimprovedTimeMillisSpentLimit (" + unimprovedTimeMillisSpentLimit
+ ") cannot be negative.");
}
this.clock = clock;
}
public long getUnimprovedTimeMillisSpentLimit() {
return unimprovedTimeMillisSpentLimit;
}
public Score getUnimprovedScoreDifferenceThreshold() {
return unimprovedScoreDifferenceThreshold;
}
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
bestScoreImprovementHistoryQueue = new ArrayDeque<>();
solverSafeTimeMillis = solverScope.getBestSolutionTimeMillis() + unimprovedTimeMillisSpentLimit;
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
bestScoreImprovementHistoryQueue = null;
solverSafeTimeMillis = -1L;
}
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
phaseSafeTimeMillis = phaseScope.getStartingSystemTimeMillis() + unimprovedTimeMillisSpentLimit;
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
phaseSafeTimeMillis = -1L;
}
@Override
public void stepEnded(AbstractStepScope<Solution_> stepScope) {
if (stepScope.getBestScoreImproved()) {
SolverScope<Solution_> solverScope = stepScope.getPhaseScope().getSolverScope();
long bestSolutionTimeMillis = solverScope.getBestSolutionTimeMillis();
Score bestScore = solverScope.getBestScore();
for (Iterator<Pair<Long, Score>> it = bestScoreImprovementHistoryQueue.iterator(); it.hasNext();) {
Pair<Long, Score> bestScoreImprovement = it.next();
Score scoreDifference = bestScore.subtract(bestScoreImprovement.value());
boolean timeLimitNotYetReached = bestScoreImprovement.key()
+ unimprovedTimeMillisSpentLimit >= bestSolutionTimeMillis;
boolean scoreImprovedOverThreshold = scoreDifference.compareTo(unimprovedScoreDifferenceThreshold) >= 0;
if (scoreImprovedOverThreshold && timeLimitNotYetReached) {
it.remove();
long safeTimeMillis = bestSolutionTimeMillis + unimprovedTimeMillisSpentLimit;
solverSafeTimeMillis = safeTimeMillis;
phaseSafeTimeMillis = safeTimeMillis;
} else {
break;
}
}
bestScoreImprovementHistoryQueue.add(new Pair<>(bestSolutionTimeMillis, bestScore));
}
}
// ************************************************************************
// Terminated methods
// ************************************************************************
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
return isTerminated(solverSafeTimeMillis);
}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
return isTerminated(phaseSafeTimeMillis);
}
protected boolean isTerminated(long safeTimeMillis) {
// 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.
long now = clock.millis();
return now > safeTimeMillis;
}
// ************************************************************************
// Time gradient methods
// ************************************************************************
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
return calculateTimeGradient(solverSafeTimeMillis);
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
return calculateTimeGradient(phaseSafeTimeMillis);
}
protected double calculateTimeGradient(long safeTimeMillis) {
long now = clock.millis();
long unimprovedTimeMillisSpent = now - (safeTimeMillis - unimprovedTimeMillisSpentLimit);
double timeGradient = unimprovedTimeMillisSpent / ((double) unimprovedTimeMillisSpentLimit);
return Math.min(timeGradient, 1.0);
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination<Solution_> createChildThreadTermination(
SolverScope<Solution_> solverScope, ChildThreadType childThreadType) {
return new UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination<>(unimprovedTimeMillisSpentLimit,
unimprovedScoreDifferenceThreshold);
}
@Override
public String toString() {
return "UnimprovedTimeMillisSpent(" + unimprovedTimeMillisSpentLimit + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.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.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
public class UnimprovedTimeMillisSpentTermination<Solution_> extends AbstractTermination<Solution_> {
private final long unimprovedTimeMillisSpentLimit;
private final Clock clock;
public UnimprovedTimeMillisSpentTermination(long unimprovedTimeMillisSpentLimit) {
this(unimprovedTimeMillisSpentLimit, Clock.systemUTC());
}
protected UnimprovedTimeMillisSpentTermination(long unimprovedTimeMillisSpentLimit, Clock clock) {
this.unimprovedTimeMillisSpentLimit = unimprovedTimeMillisSpentLimit;
if (unimprovedTimeMillisSpentLimit < 0L) {
throw new IllegalArgumentException("The unimprovedTimeMillisSpentLimit (" + unimprovedTimeMillisSpentLimit
+ ") cannot be negative.");
}
this.clock = clock;
}
public long getUnimprovedTimeMillisSpentLimit() {
return unimprovedTimeMillisSpentLimit;
}
// ************************************************************************
// Terminated methods
// ************************************************************************
@Override
public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
long bestSolutionTimeMillis = solverScope.getBestSolutionTimeMillis();
return isTerminated(bestSolutionTimeMillis);
}
@Override
public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
long bestSolutionTimeMillis = phaseScope.getPhaseBestSolutionTimeMillis();
return isTerminated(bestSolutionTimeMillis);
}
protected boolean isTerminated(long bestSolutionTimeMillis) {
long now = clock.millis();
long unimprovedTimeMillisSpent = now - bestSolutionTimeMillis;
return unimprovedTimeMillisSpent >= unimprovedTimeMillisSpentLimit;
}
// ************************************************************************
// Time gradient methods
// ************************************************************************
@Override
public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
long bestSolutionTimeMillis = solverScope.getBestSolutionTimeMillis();
return calculateTimeGradient(bestSolutionTimeMillis);
}
@Override
public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) {
long bestSolutionTimeMillis = phaseScope.getPhaseBestSolutionTimeMillis();
return calculateTimeGradient(bestSolutionTimeMillis);
}
protected double calculateTimeGradient(long bestSolutionTimeMillis) {
long now = clock.millis();
long unimprovedTimeMillisSpent = now - bestSolutionTimeMillis;
double timeGradient = unimprovedTimeMillisSpent / ((double) unimprovedTimeMillisSpentLimit);
return Math.min(timeGradient, 1.0);
}
// ************************************************************************
// Other methods
// ************************************************************************
@Override
public UnimprovedTimeMillisSpentTermination<Solution_> createChildThreadTermination(
SolverScope<Solution_> solverScope, ChildThreadType childThreadType) {
return new UnimprovedTimeMillisSpentTermination<>(unimprovedTimeMillisSpentLimit);
}
@Override
public String toString() {
return "UnimprovedTimeMillisSpent(" + unimprovedTimeMillisSpentLimit + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/statistic/BestScoreStatistic.java | package ai.timefold.solver.core.impl.statistic;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.api.solver.event.SolverEventListener;
import ai.timefold.solver.core.config.solver.monitoring.SolverMetric;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
import ai.timefold.solver.core.impl.solver.DefaultSolver;
import io.micrometer.core.instrument.Tags;
public class BestScoreStatistic<Solution_> implements SolverStatistic<Solution_> {
private final Map<Tags, List<AtomicReference<Number>>> tagsToBestScoreMap = new ConcurrentHashMap<>();
private final Map<Solver<Solution_>, SolverEventListener<Solution_>> solverToEventListenerMap = new WeakHashMap<>();
@Override
public void unregister(Solver<Solution_> solver) {
SolverEventListener<Solution_> listener = solverToEventListenerMap.remove(solver);
if (listener != null) {
solver.removeEventListener(listener);
}
}
@Override
public void register(Solver<Solution_> solver) {
DefaultSolver<Solution_> defaultSolver = (DefaultSolver<Solution_>) solver;
ScoreDefinition<?> scoreDefinition = defaultSolver.getSolverScope().getScoreDefinition();
SolverEventListener<Solution_> listener = event -> SolverMetric.registerScoreMetrics(SolverMetric.BEST_SCORE,
defaultSolver.getSolverScope().getMonitoringTags(),
scoreDefinition, tagsToBestScoreMap, event.getNewBestScore());
solverToEventListenerMap.put(defaultSolver, listener);
defaultSolver.addEventListener(listener);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/statistic/BestSolutionMutationCountStatistic.java | package ai.timefold.solver.core.impl.statistic;
import java.util.Map;
import java.util.WeakHashMap;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.api.solver.event.BestSolutionChangedEvent;
import ai.timefold.solver.core.api.solver.event.SolverEventListener;
import ai.timefold.solver.core.config.solver.monitoring.SolverMetric;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.domain.solution.mutation.MutationCounter;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirectorFactory;
import ai.timefold.solver.core.impl.solver.DefaultSolver;
import io.micrometer.core.instrument.Metrics;
public class BestSolutionMutationCountStatistic<Solution_> implements SolverStatistic<Solution_> {
private final Map<Solver<Solution_>, SolverEventListener<Solution_>> solverToEventListenerMap = new WeakHashMap<>();
@Override
public void unregister(Solver<Solution_> solver) {
SolverEventListener<Solution_> listener = solverToEventListenerMap.remove(solver);
if (listener != null) {
solver.removeEventListener(listener);
}
}
@Override
public void register(Solver<Solution_> solver) {
DefaultSolver<Solution_> defaultSolver = (DefaultSolver<Solution_>) solver;
InnerScoreDirectorFactory<Solution_, ?> innerScoreDirectorFactory = defaultSolver.getScoreDirectorFactory();
SolutionDescriptor<Solution_> solutionDescriptor = innerScoreDirectorFactory.getSolutionDescriptor();
MutationCounter<Solution_> mutationCounter = new MutationCounter<>(solutionDescriptor);
BestSolutionMutationCountStatisticListener<Solution_> listener =
Metrics.gauge(SolverMetric.BEST_SOLUTION_MUTATION.getMeterId(),
defaultSolver.getSolverScope().getMonitoringTags(),
new BestSolutionMutationCountStatisticListener<>(mutationCounter),
BestSolutionMutationCountStatisticListener::getMutationCount);
solverToEventListenerMap.put(solver, listener);
solver.addEventListener(listener);
}
private static class BestSolutionMutationCountStatisticListener<Solution_> implements SolverEventListener<Solution_> {
final MutationCounter<Solution_> mutationCounter;
int mutationCount = 0;
Solution_ oldBestSolution = null;
public BestSolutionMutationCountStatisticListener(MutationCounter<Solution_> mutationCounter) {
this.mutationCounter = mutationCounter;
}
public int getMutationCount() {
return mutationCount;
}
@Override
public void bestSolutionChanged(BestSolutionChangedEvent<Solution_> event) {
Solution_ newBestSolution = event.getNewBestSolution();
if (oldBestSolution == null) {
mutationCount = 0;
} else {
mutationCount = mutationCounter.countMutations(oldBestSolution, newBestSolution);
}
oldBestSolution = newBestSolution;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/statistic/MemoryUseStatistic.java | package ai.timefold.solver.core.impl.statistic;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.impl.solver.DefaultSolver;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics;
public class MemoryUseStatistic<Solution_> implements SolverStatistic<Solution_> {
@Override
public void unregister(Solver<Solution_> solver) {
// Intentionally Empty: JVM memory is not bound to a particular solver
}
@Override
public void register(Solver<Solution_> solver) {
DefaultSolver<Solution_> defaultSolver = (DefaultSolver<Solution_>) solver;
new JvmMemoryMetrics(defaultSolver.getSolverScope().getMonitoringTags()).bindTo(Metrics.globalRegistry);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/statistic/PickedMoveBestScoreDiffStatistic.java | package ai.timefold.solver.core.impl.statistic;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.config.solver.monitoring.SolverMetric;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope;
import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleListenerAdapter;
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.definition.ScoreDefinition;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirectorFactory;
import ai.timefold.solver.core.impl.solver.DefaultSolver;
import io.micrometer.core.instrument.Tags;
public class PickedMoveBestScoreDiffStatistic<Solution_, Score_ extends Score<Score_>> implements SolverStatistic<Solution_> {
private final Map<Solver<Solution_>, PhaseLifecycleListenerAdapter<Solution_>> solverToPhaseLifecycleListenerMap =
new WeakHashMap<>();
@Override
public void unregister(Solver<Solution_> solver) {
PhaseLifecycleListenerAdapter<Solution_> listener = solverToPhaseLifecycleListenerMap.remove(solver);
if (listener != null) {
((DefaultSolver<Solution_>) solver).removePhaseLifecycleListener(listener);
}
}
@Override
@SuppressWarnings("unchecked")
public void register(Solver<Solution_> solver) {
DefaultSolver<Solution_> defaultSolver = (DefaultSolver<Solution_>) solver;
InnerScoreDirectorFactory<Solution_, ?> innerScoreDirectorFactory = defaultSolver.getScoreDirectorFactory();
SolutionDescriptor<Solution_> solutionDescriptor = innerScoreDirectorFactory.getSolutionDescriptor();
PickedMoveBestScoreDiffStatisticListener<Solution_, Score_> listener =
new PickedMoveBestScoreDiffStatisticListener<Solution_, Score_>(solutionDescriptor.getScoreDefinition());
solverToPhaseLifecycleListenerMap.put(solver, listener);
defaultSolver.addPhaseLifecycleListener(listener);
}
private static class PickedMoveBestScoreDiffStatisticListener<Solution_, Score_ extends Score<Score_>>
extends PhaseLifecycleListenerAdapter<Solution_> {
private Score_ oldBestScore = null;
private final ScoreDefinition<Score_> scoreDefinition;
private final Map<Tags, List<AtomicReference<Number>>> tagsToMoveScoreMap = new ConcurrentHashMap<>();
public PickedMoveBestScoreDiffStatisticListener(ScoreDefinition<Score_> scoreDefinition) {
this.scoreDefinition = scoreDefinition;
}
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
if (phaseScope instanceof LocalSearchPhaseScope) {
oldBestScore = phaseScope.getBestScore();
}
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
if (phaseScope instanceof LocalSearchPhaseScope) {
oldBestScore = null;
}
}
@Override
public void stepEnded(AbstractStepScope<Solution_> stepScope) {
if (stepScope instanceof LocalSearchStepScope) {
localSearchStepEnded((LocalSearchStepScope<Solution_>) stepScope);
}
}
@SuppressWarnings("unchecked")
private void localSearchStepEnded(LocalSearchStepScope<Solution_> stepScope) {
if (stepScope.getBestScoreImproved()) {
String moveType = stepScope.getStep().getSimpleMoveTypeDescription();
Score_ newBestScore = (Score_) stepScope.getScore();
Score_ bestScoreDiff = newBestScore.subtract(oldBestScore);
oldBestScore = newBestScore;
SolverMetric.registerScoreMetrics(SolverMetric.PICKED_MOVE_TYPE_BEST_SCORE_DIFF,
stepScope.getPhaseScope().getSolverScope().getMonitoringTags()
.and("move.type", moveType),
scoreDefinition,
tagsToMoveScoreMap,
bestScoreDiff);
}
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/statistic/PickedMoveStepScoreDiffStatistic.java | package ai.timefold.solver.core.impl.statistic;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.config.solver.monitoring.SolverMetric;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope;
import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleListenerAdapter;
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.definition.ScoreDefinition;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirectorFactory;
import ai.timefold.solver.core.impl.solver.DefaultSolver;
import io.micrometer.core.instrument.Tags;
public class PickedMoveStepScoreDiffStatistic<Solution_> implements SolverStatistic<Solution_> {
private final Map<Solver<Solution_>, PhaseLifecycleListenerAdapter<Solution_>> solverToPhaseLifecycleListenerMap =
new WeakHashMap<>();
@Override
public void unregister(Solver<Solution_> solver) {
PhaseLifecycleListenerAdapter<Solution_> listener = solverToPhaseLifecycleListenerMap.remove(solver);
if (listener != null) {
((DefaultSolver<Solution_>) solver).removePhaseLifecycleListener(listener);
}
}
@Override
public void register(Solver<Solution_> solver) {
DefaultSolver<Solution_> defaultSolver = (DefaultSolver<Solution_>) solver;
InnerScoreDirectorFactory<Solution_, ?> innerScoreDirectorFactory = defaultSolver.getScoreDirectorFactory();
SolutionDescriptor<Solution_> solutionDescriptor = innerScoreDirectorFactory.getSolutionDescriptor();
PickedMoveStepScoreDiffStatisticListener<Solution_, ?> listener =
new PickedMoveStepScoreDiffStatisticListener<>((ScoreDefinition<?>) solutionDescriptor.getScoreDefinition());
solverToPhaseLifecycleListenerMap.put(solver, listener);
defaultSolver.addPhaseLifecycleListener(listener);
}
private static class PickedMoveStepScoreDiffStatisticListener<Solution_, Score_ extends Score<Score_>>
extends PhaseLifecycleListenerAdapter<Solution_> {
private Score_ oldStepScore = null;
private final ScoreDefinition<Score_> scoreDefinition;
private final Map<Tags, List<AtomicReference<Number>>> tagsToMoveScoreMap = new ConcurrentHashMap<>();
public PickedMoveStepScoreDiffStatisticListener(ScoreDefinition<Score_> scoreDefinition) {
this.scoreDefinition = scoreDefinition;
}
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
if (phaseScope instanceof LocalSearchPhaseScope) {
oldStepScore = phaseScope.getStartingScore();
}
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
if (phaseScope instanceof LocalSearchPhaseScope) {
oldStepScore = null;
}
}
@Override
public void stepEnded(AbstractStepScope<Solution_> stepScope) {
if (stepScope instanceof LocalSearchStepScope) {
localSearchStepEnded((LocalSearchStepScope<Solution_>) stepScope);
}
}
@SuppressWarnings("unchecked")
private void localSearchStepEnded(LocalSearchStepScope<Solution_> stepScope) {
String moveType = stepScope.getStep().getSimpleMoveTypeDescription();
Score_ newStepScore = (Score_) stepScope.getScore();
Score_ stepScoreDiff = newStepScore.subtract(oldStepScore);
oldStepScore = newStepScore;
SolverMetric.registerScoreMetrics(SolverMetric.PICKED_MOVE_TYPE_STEP_SCORE_DIFF,
stepScope.getPhaseScope().getSolverScope().getMonitoringTags()
.and("move.type", moveType),
scoreDefinition,
tagsToMoveScoreMap,
stepScoreDiff);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/statistic/SolverScopeStatistic.java | package ai.timefold.solver.core.impl.statistic;
import java.util.function.ToDoubleFunction;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.impl.solver.DefaultSolver;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.Metrics;
public class SolverScopeStatistic<Solution_> implements SolverStatistic<Solution_> {
private final String meterId;
private final ToDoubleFunction<SolverScope<Solution_>> metricFunction;
public SolverScopeStatistic(String meterId, ToDoubleFunction<SolverScope<Solution_>> metricFunction) {
this.meterId = meterId;
this.metricFunction = metricFunction;
}
@Override
public void register(Solver<Solution_> solver) {
SolverScope<Solution_> solverScope = ((DefaultSolver<Solution_>) solver).getSolverScope();
Metrics.gauge(meterId, solverScope.getMonitoringTags(),
solverScope, metricFunction);
}
@Override
public void unregister(Solver<Solution_> solver) {
SolverScope<Solution_> solverScope = ((DefaultSolver<Solution_>) solver).getSolverScope();
Metrics.globalRegistry.remove(new Meter.Id(meterId,
solverScope.getMonitoringTags(),
null,
null,
Meter.Type.GAUGE));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/statistic/SolverStatistic.java | package ai.timefold.solver.core.impl.statistic;
import ai.timefold.solver.core.api.solver.Solver;
public interface SolverStatistic<Solution_> {
void unregister(Solver<Solution_> solver);
void register(Solver<Solution_> solver);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/statistic/StatelessSolverStatistic.java | package ai.timefold.solver.core.impl.statistic;
import ai.timefold.solver.core.api.solver.Solver;
/**
* A {@link SolverStatistic} that has no state or event listener
*/
public class StatelessSolverStatistic<Solution_> implements SolverStatistic<Solution_> {
@Override
public void unregister(Solver<Solution_> solver) {
// intentionally empty
}
@Override
public void register(Solver<Solution_> solver) {
// intentionally empty
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/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.ceil(numElements / 0.75f);
}
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-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/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;
/**
* 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 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 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 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 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 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 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 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 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 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 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 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-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/util/ElementAwareList.java | package ai.timefold.solver.core.impl.util;
import java.util.Iterator;
import java.util.NoSuchElementException;
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 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 < 3; i++) {
* elementAwareList.forEach(entry -> 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 -> 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() {
return new ElementAwareListIterator<>(first);
}
@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;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/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> 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-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/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 {
int newSize = set.size() - 1;
if (newSize <= LIST_SIZE_THRESHOLD) {
set.remove(o);
list = new ArrayList<>(set);
set = null;
belowThreshold = true;
return true;
} else {
return set.remove(o);
}
}
}
@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;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/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);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/util/MutableReference.java | package ai.timefold.solver.core.impl.util;
import java.util.Objects;
public final class MutableReference<Value_> {
private Value_ value;
public MutableReference(Value_ value) {
this.value = value;
}
public Value_ getValue() {
return value;
}
public void setValue(Value_ value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (o instanceof MutableReference<?> other) {
return value.equals(other.value);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(value);
}
@Override
public String toString() {
return value.toString();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/app/TimefoldExamplesApp.java | package ai.timefold.solver.examples.app;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.stream.Stream;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import ai.timefold.solver.examples.common.app.CommonApp;
import ai.timefold.solver.examples.common.swingui.OpenBrowserAction;
import ai.timefold.solver.examples.common.swingui.SolverAndPersistenceFrame;
import ai.timefold.solver.examples.nurserostering.app.NurseRosteringApp;
import ai.timefold.solver.examples.projectjobscheduling.app.ProjectJobSchedulingApp;
import ai.timefold.solver.examples.taskassigning.app.TaskAssigningApp;
import ai.timefold.solver.examples.tennis.app.TennisApp;
import ai.timefold.solver.examples.travelingtournament.app.TravelingTournamentApp;
public class TimefoldExamplesApp extends JFrame {
/**
* Supported system properties: {@link CommonApp#DATA_DIR_SYSTEM_PROPERTY}.
*
* @param args never null
*/
public static void main(String[] args) {
CommonApp.prepareSwingEnvironment();
TimefoldExamplesApp timefoldExamplesApp = new TimefoldExamplesApp();
timefoldExamplesApp.pack();
timefoldExamplesApp.setLocationRelativeTo(null);
timefoldExamplesApp.setVisible(true);
}
private static String determineTimefoldExamplesVersion() {
String timefoldExamplesVersion = TimefoldExamplesApp.class.getPackage().getImplementationVersion();
if (timefoldExamplesVersion == null) {
timefoldExamplesVersion = "";
}
return timefoldExamplesVersion;
}
private JTextArea descriptionTextArea;
public TimefoldExamplesApp() {
super("Timefold examples " + determineTimefoldExamplesVersion());
setIconImage(SolverAndPersistenceFrame.TIMEFOLD_ICON.getImage());
setContentPane(createContentPane());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private Container createContentPane() {
JPanel contentPane = new JPanel(new BorderLayout(5, 5));
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel titleLabel = new JLabel("Which example do you want to see?", JLabel.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(20.0f));
contentPane.add(titleLabel, BorderLayout.NORTH);
JScrollPane examplesScrollPane = new JScrollPane(createExamplesPanel());
examplesScrollPane.getHorizontalScrollBar().setUnitIncrement(20);
examplesScrollPane.getVerticalScrollBar().setUnitIncrement(20);
examplesScrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
contentPane.add(examplesScrollPane, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel(new BorderLayout(5, 5));
bottomPanel.add(createDescriptionPanel(), BorderLayout.CENTER);
bottomPanel.add(createExtraPanel(), BorderLayout.EAST);
contentPane.add(bottomPanel, BorderLayout.SOUTH);
return contentPane;
}
private JPanel createExamplesPanel() {
JPanel panel = new JPanel(new GridLayout(0, 3, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
Stream.of(new NurseRosteringApp(),
new TaskAssigningApp(),
new ProjectJobSchedulingApp(),
new TravelingTournamentApp(),
new TennisApp())
.map(this::createExampleButton)
.forEach(panel::add);
return panel;
}
private JButton createExampleButton(final CommonApp commonApp) {
String iconResource = commonApp.getIconResource();
Icon icon = iconResource == null ? new EmptyIcon() : new ImageIcon(getClass().getResource(iconResource));
JButton button = new JButton(new AbstractAction(commonApp.getName(), icon) {
@Override
public void actionPerformed(ActionEvent e) {
commonApp.init(TimefoldExamplesApp.this, false);
}
});
button.setHorizontalAlignment(JButton.LEFT);
button.setHorizontalTextPosition(JButton.RIGHT);
button.setVerticalTextPosition(JButton.CENTER);
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
descriptionTextArea.setText(commonApp.getDescription());
}
@Override
public void mouseExited(MouseEvent e) {
descriptionTextArea.setText("");
}
});
return button;
}
private JPanel createDescriptionPanel() {
JPanel descriptionPanel = new JPanel(new BorderLayout(2, 2));
descriptionPanel.add(new JLabel("Description"), BorderLayout.NORTH);
descriptionTextArea = new JTextArea(8, 65);
descriptionTextArea.setEditable(false);
descriptionTextArea.setLineWrap(true);
descriptionTextArea.setWrapStyleWord(true);
descriptionPanel.add(new JScrollPane(descriptionTextArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), BorderLayout.CENTER);
return descriptionPanel;
}
private JPanel createExtraPanel() {
JPanel extraPanel = new JPanel(new GridLayout(0, 1, 5, 5));
extraPanel.add(new JPanel());
Action homepageAction = new OpenBrowserAction("timefold.ai", "https://timefold.ai");
extraPanel.add(new JButton(homepageAction));
Action documentationAction = new OpenBrowserAction("Documentation",
"https://timefold.ai/docs/");
extraPanel.add(new JButton(documentationAction));
return extraPanel;
}
private static class EmptyIcon implements Icon {
@Override
public int getIconWidth() {
return 64;
}
@Override
public int getIconHeight() {
return 64;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
// Do nothing
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/app/CommonApp.java | package ai.timefold.solver.examples.common.app;
import java.awt.Component;
import java.io.File;
import java.util.Collections;
import java.util.Set;
import java.util.function.BiConsumer;
import javax.swing.WindowConstants;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.solver.SolverFactory;
import ai.timefold.solver.examples.common.business.SolutionBusiness;
import ai.timefold.solver.examples.common.persistence.AbstractSolutionExporter;
import ai.timefold.solver.examples.common.persistence.AbstractSolutionImporter;
import ai.timefold.solver.examples.common.swingui.SolutionPanel;
import ai.timefold.solver.examples.common.swingui.SolverAndPersistenceFrame;
import ai.timefold.solver.persistence.common.api.domain.solution.SolutionFileIO;
import ai.timefold.solver.swing.impl.SwingUncaughtExceptionHandler;
import ai.timefold.solver.swing.impl.SwingUtils;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class CommonApp<Solution_> extends LoggingMain {
/**
* The path to the data directory, preferably with unix slashes for portability.
* For example: -D{@value #DATA_DIR_SYSTEM_PROPERTY}=sources/data/
*/
public static final String DATA_DIR_SYSTEM_PROPERTY = "ai.timefold.solver.examples.dataDir";
public static File determineDataDir(String dataDirName) {
String dataDirPath = System.getProperty(DATA_DIR_SYSTEM_PROPERTY, "data/");
File dataDir = new File(dataDirPath, dataDirName);
if (!dataDir.exists()) {
throw new IllegalStateException("The directory dataDir (" + dataDir.getAbsolutePath()
+ ") does not exist.\n" +
" Either the working directory should be set to the directory that contains the data directory" +
" (which is not the data directory itself), or the system property "
+ DATA_DIR_SYSTEM_PROPERTY + " should be set properly.\n" +
" The data directory is different in a git clone (timefold/timefold-solver-examples/data)" +
" and in a release zip (examples/sources/data).\n" +
" In an IDE (IntelliJ, Eclipse, VSCode), open the \"Run configuration\""
+ " to change \"Working directory\" (or add the system property in \"VM options\").");
}
return dataDir;
}
/**
* Some examples are not compatible with every native LookAndFeel.
* For example, NurseRosteringPanel is incompatible with Mac.
*/
public static void prepareSwingEnvironment() {
SwingUncaughtExceptionHandler.register();
SwingUtils.fixateLookAndFeel();
}
protected final String name;
protected final String description;
protected final String solverConfigResource;
protected final String dataDirName;
protected final String iconResource;
protected SolverAndPersistenceFrame<Solution_> solverAndPersistenceFrame;
protected SolutionBusiness<Solution_, ?> solutionBusiness;
protected CommonApp(String name, String description, String solverConfigResource, String dataDirName, String iconResource) {
this.name = name;
this.description = description;
this.solverConfigResource = solverConfigResource;
this.dataDirName = dataDirName;
this.iconResource = iconResource;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getSolverConfigResource() {
return solverConfigResource;
}
public String getDataDirName() {
return dataDirName;
}
public String getIconResource() {
return iconResource;
}
public void init() {
init(null, true);
}
public void init(Component centerForComponent, boolean exitOnClose) {
solutionBusiness = createSolutionBusiness();
solverAndPersistenceFrame = new SolverAndPersistenceFrame<>(solutionBusiness, createSolutionPanel(),
createExtraActions());
solverAndPersistenceFrame
.setDefaultCloseOperation(exitOnClose ? WindowConstants.EXIT_ON_CLOSE : WindowConstants.DISPOSE_ON_CLOSE);
solverAndPersistenceFrame.init(centerForComponent);
solverAndPersistenceFrame.setVisible(true);
}
public SolutionBusiness<Solution_, ?> createSolutionBusiness() {
SolutionBusiness<Solution_, ?> solutionBusiness = new SolutionBusiness<>(this,
SolverFactory.createFromXmlResource(solverConfigResource));
solutionBusiness.setDataDir(determineDataDir(dataDirName));
solutionBusiness.setSolutionFileIO(createSolutionFileIO());
solutionBusiness.setImporters(createSolutionImporters());
solutionBusiness.setExporters(createSolutionExporters());
solutionBusiness.updateDataDirs();
return solutionBusiness;
}
protected abstract SolutionPanel<Solution_> createSolutionPanel();
protected ExtraAction<Solution_>[] createExtraActions() {
return new ExtraAction[0];
}
/**
* Used for the unsolved and solved directories,
* not for the import and output directories, in the data directory.
*
* @return never null
*/
public abstract SolutionFileIO<Solution_> createSolutionFileIO();
protected Set<AbstractSolutionImporter<Solution_>> createSolutionImporters() {
return Collections.emptySet();
}
protected Set<AbstractSolutionExporter<Solution_>> createSolutionExporters() {
return Collections.emptySet();
}
public interface ExtraAction<Solution_> extends BiConsumer<SolutionBusiness<Solution_, ?>, SolutionPanel<Solution_>> {
String getName();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/app/CommonBenchmarkApp.java | package ai.timefold.solver.examples.common.app;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import ai.timefold.solver.benchmark.api.PlannerBenchmark;
import ai.timefold.solver.benchmark.api.PlannerBenchmarkFactory;
import ai.timefold.solver.benchmark.impl.aggregator.swingui.BenchmarkAggregatorFrame;
public abstract class CommonBenchmarkApp extends LoggingMain {
public static final String AGGREGATOR_ARG = "--aggregator";
private final Map<String, ArgOption> benchmarkArgumentMap;
public CommonBenchmarkApp(ArgOption... argOptions) {
benchmarkArgumentMap = new LinkedHashMap<>(argOptions.length);
for (ArgOption argOption : argOptions) {
benchmarkArgumentMap.put(argOption.getName(), argOption);
}
}
public Collection<ArgOption> getArgOptions() {
return benchmarkArgumentMap.values();
}
public void buildAndBenchmark(String[] args) {
// Parse arguments
boolean aggregator = false;
ArgOption argOption = null;
for (String arg : args) {
if (arg.equalsIgnoreCase(AGGREGATOR_ARG)) {
aggregator = true;
} else if (benchmarkArgumentMap.containsKey(arg)) {
if (argOption != null) {
throw new IllegalArgumentException("The args (" + Arrays.toString(args)
+ ") contains arg name (" + argOption.getName() + ") and arg name (" + arg + ").");
}
argOption = benchmarkArgumentMap.get(arg);
} else {
throw new IllegalArgumentException("The args (" + Arrays.toString(args)
+ ") contains an arg (" + arg + ") which is not part of the recognized args ("
+ benchmarkArgumentMap.keySet() + " or " + AGGREGATOR_ARG + ").");
}
}
if (argOption == null) {
argOption = benchmarkArgumentMap.values().iterator().next();
}
boolean template = argOption.isTemplate();
String benchmarkConfigResource = argOption.getBenchmarkConfigResource();
// Execute the benchmark or aggregation
if (!aggregator) {
PlannerBenchmarkFactory benchmarkFactory;
if (!template) {
benchmarkFactory = PlannerBenchmarkFactory.createFromXmlResource(benchmarkConfigResource);
} else {
benchmarkFactory = PlannerBenchmarkFactory.createFromFreemarkerXmlResource(benchmarkConfigResource);
}
PlannerBenchmark benchmark = benchmarkFactory.buildPlannerBenchmark();
benchmark.benchmarkAndShowReportInBrowser();
} else {
if (!template) {
BenchmarkAggregatorFrame.createAndDisplayFromXmlResource(benchmarkConfigResource);
} else {
BenchmarkAggregatorFrame.createAndDisplayFromFreemarkerXmlResource(benchmarkConfigResource);
}
}
}
public static class ArgOption {
private String name;
private String benchmarkConfigResource;
private boolean template;
public ArgOption(String name, String benchmarkConfigResource) {
this(name, benchmarkConfigResource, false);
}
public ArgOption(String name, String benchmarkConfigResource, boolean template) {
this.name = name;
this.benchmarkConfigResource = benchmarkConfigResource;
this.template = template;
}
public String getName() {
return name;
}
public String getBenchmarkConfigResource() {
return benchmarkConfigResource;
}
public boolean isTemplate() {
return template;
}
@Override
public String toString() {
return name + " (" + benchmarkConfigResource + ")";
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/app/LoggingMain.java | package ai.timefold.solver.examples.common.app;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoggingMain {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/business/AlphaNumericStringComparator.java | package ai.timefold.solver.examples.common.business;
import java.util.Comparator;
/**
* Sorts data like this: "data-1", "data-2", "data-3", "data-10", "data-20", "data-100", ...
*/
final class AlphaNumericStringComparator implements Comparator<String> {
@Override
public int compare(String a, String b) {
char[] aChars = a.toCharArray();
char[] bChars = b.toCharArray();
int aIndex = 0;
int bIndex = 0;
while (true) {
if (aIndex >= aChars.length) {
if (bIndex >= bChars.length) {
return 0;
} else {
return -1;
}
} else if (bIndex >= bChars.length) {
return 1;
}
char aChar = aChars[aIndex];
char bChar = bChars[bIndex];
if (isDigit(aChar) && isDigit(bChar)) {
int aIndexTo = aIndex + 1;
while (aIndexTo < aChars.length && isDigit(aChars[aIndexTo])) {
aIndexTo++;
}
int bIndexTo = bIndex + 1;
while (bIndexTo < bChars.length && isDigit(bChars[bIndexTo])) {
bIndexTo++;
}
int aNumber = Integer.parseInt(new String(aChars, aIndex, aIndexTo - aIndex));
int bNumber = Integer.parseInt(new String(bChars, bIndex, bIndexTo - bIndex));
if (aNumber < bNumber) {
return -1;
} else if (aNumber > bNumber) {
return 1;
}
aIndex = aIndexTo;
bIndex = bIndexTo;
} else {
if (aChar < bChar) {
return -1;
} else if (aChar > bChar) {
return 1;
}
aIndex++;
bIndex++;
}
}
}
private boolean isDigit(char aChar) {
return aChar >= '0' && aChar <= '9';
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/business/ProblemFileComparator.java | package ai.timefold.solver.examples.common.business;
import java.io.File;
import java.util.Comparator;
public class ProblemFileComparator implements Comparator<File> {
private static final AlphaNumericStringComparator ALPHA_NUMERIC_STRING_COMPARATOR = new AlphaNumericStringComparator();
private static final Comparator<File> COMPARATOR = Comparator.comparing(File::getParent, ALPHA_NUMERIC_STRING_COMPARATOR)
.thenComparing(File::isDirectory)
.thenComparing(f -> !f.getName().toLowerCase().startsWith("demo"))
.thenComparing(f -> f.getName().toLowerCase(), ALPHA_NUMERIC_STRING_COMPARATOR)
.thenComparing(File::getName);
@Override
public int compare(File a, File b) {
return COMPARATOR.compare(a, b);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/business/SolutionBusiness.java | package ai.timefold.solver.examples.common.business;
import static ai.timefold.solver.core.api.solver.SolutionUpdatePolicy.NO_UPDATE;
import static java.util.stream.Collectors.toList;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Stream;
import javax.swing.SwingUtilities;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.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.SolverFactory;
import ai.timefold.solver.core.api.solver.SolverJob;
import ai.timefold.solver.core.api.solver.SolverManager;
import ai.timefold.solver.core.api.solver.SolverStatus;
import ai.timefold.solver.core.api.solver.change.ProblemChange;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.solver.DefaultSolverFactory;
import ai.timefold.solver.core.impl.solver.change.DefaultProblemChangeDirector;
import ai.timefold.solver.examples.common.app.CommonApp;
import ai.timefold.solver.examples.common.persistence.AbstractSolutionExporter;
import ai.timefold.solver.examples.common.persistence.AbstractSolutionImporter;
import ai.timefold.solver.persistence.common.api.domain.solution.SolutionFileIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public final class SolutionBusiness<Solution_, Score_ extends Score<Score_>> implements AutoCloseable {
public static String getBaseFileName(File file) {
return getBaseFileName(file.getName());
}
public static String getBaseFileName(String name) {
int indexOfLastDot = name.lastIndexOf('.');
if (indexOfLastDot > 0) {
return name.substring(0, indexOfLastDot);
} else {
return name;
}
}
private static final Comparator<File> FILE_COMPARATOR = new ProblemFileComparator();
private static final AtomicLong SOLVER_JOB_ID_COUNTER = new AtomicLong();
private static final Logger LOGGER = LoggerFactory.getLogger(SolutionBusiness.class);
private final CommonApp<Solution_> app;
private final DefaultSolverFactory<Solution_> solverFactory;
private final SolverManager<Solution_, Long> solverManager;
private final SolutionManager<Solution_, Score_> solutionManager;
private final AtomicReference<SolverJob<Solution_, Long>> solverJobRef = new AtomicReference<>();
private final AtomicReference<Solution_> workingSolutionRef = new AtomicReference<>();
private File dataDir;
private SolutionFileIO<Solution_> solutionFileIO;
private Set<AbstractSolutionImporter<Solution_>> importers;
private Set<AbstractSolutionExporter<Solution_>> exporters;
private File importDataDir;
private File unsolvedDataDir;
private File solvedDataDir;
private File exportDataDir;
private String solutionFileName = null;
public SolutionBusiness(CommonApp<Solution_> app, SolverFactory<Solution_> solverFactory) {
this.app = app;
this.solverFactory = ((DefaultSolverFactory<Solution_>) solverFactory);
this.solverManager = SolverManager.create(solverFactory);
this.solutionManager = SolutionManager.create(solverFactory);
}
private static List<File> getFileList(File dataDir, String extension) {
try (Stream<Path> paths = Files.walk(dataDir.toPath(), FileVisitOption.FOLLOW_LINKS)) {
return paths.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith("." + extension))
.map(Path::toFile)
.sorted(FILE_COMPARATOR)
.collect(toList());
} catch (IOException e) {
throw new IllegalStateException("Error while crawling data directory (" + dataDir + ").", e);
}
}
public String getAppName() {
return app.getName();
}
public String getAppDescription() {
return app.getDescription();
}
public void setDataDir(File dataDir) {
this.dataDir = dataDir;
}
public SolutionFileIO<Solution_> getSolutionFileIO() {
return solutionFileIO;
}
public void setSolutionFileIO(SolutionFileIO<Solution_> solutionFileIO) {
this.solutionFileIO = solutionFileIO;
}
public Set<AbstractSolutionImporter<Solution_>> getImporters() {
return importers;
}
public void setImporters(Set<AbstractSolutionImporter<Solution_>> importers) {
this.importers = importers;
}
public Set<AbstractSolutionExporter<Solution_>> getExporters() {
return this.exporters;
}
public void setExporters(Set<AbstractSolutionExporter<Solution_>> exporters) {
if (exporters == null) {
throw new IllegalArgumentException("Passed exporters must not be null");
}
this.exporters = exporters;
}
public boolean hasImporter() {
return !importers.isEmpty();
}
public boolean hasExporter() {
return exporters != null && exporters.size() > 0;
}
public void updateDataDirs() {
if (hasImporter()) {
importDataDir = new File(dataDir, "import");
if (!importDataDir.exists()) {
throw new IllegalStateException("The directory importDataDir (" + importDataDir.getAbsolutePath()
+ ") does not exist.");
}
}
unsolvedDataDir = new File(dataDir, "unsolved");
if (!unsolvedDataDir.exists()) {
throw new IllegalStateException("The directory unsolvedDataDir (" + unsolvedDataDir.getAbsolutePath()
+ ") does not exist.");
}
solvedDataDir = new File(dataDir, "solved");
if (!solvedDataDir.exists() && !solvedDataDir.mkdir()) {
throw new IllegalStateException("The directory solvedDataDir (" + solvedDataDir.getAbsolutePath()
+ ") does not exist and could not be created.");
}
if (hasExporter()) {
exportDataDir = new File(dataDir, "export");
if (!exportDataDir.exists() && !exportDataDir.mkdir()) {
throw new IllegalStateException("The directory exportDataDir (" + exportDataDir.getAbsolutePath()
+ ") does not exist and could not be created.");
}
}
}
public File getImportDataDir() {
return importDataDir;
}
public File getUnsolvedDataDir() {
return unsolvedDataDir;
}
public File getSolvedDataDir() {
return solvedDataDir;
}
public File getExportDataDir() {
return exportDataDir;
}
public List<File> getUnsolvedFileList() {
return getFileList(unsolvedDataDir, solutionFileIO.getInputFileExtension());
}
public List<File> getSolvedFileList() {
return getFileList(solvedDataDir, solutionFileIO.getOutputFileExtension());
}
public Solution_ getSolution() {
return workingSolutionRef.get();
}
public void setSolution(Solution_ solution) {
workingSolutionRef.set(solution);
}
public String getSolutionFileName() {
return solutionFileName;
}
public void setSolutionFileName(String solutionFileName) {
this.solutionFileName = solutionFileName;
}
public Score_ getScore() {
return solutionManager.update(getSolution());
}
public boolean isSolving() {
SolverJob<Solution_, Long> solverJob = solverJobRef.get();
return solverJob != null && solverJob.getSolverStatus() == SolverStatus.SOLVING_ACTIVE;
}
public boolean isConstraintMatchEnabled() {
return applyScoreDirector(InnerScoreDirector::isConstraintMatchEnabled);
}
private <Result_> Result_ applyScoreDirector(Function<InnerScoreDirector<Solution_, Score_>, Result_> function) {
try (InnerScoreDirector<Solution_, Score_> scoreDirector =
(InnerScoreDirector<Solution_, Score_>) solverFactory.getScoreDirectorFactory().buildScoreDirector(true,
true)) {
scoreDirector.setWorkingSolution(getSolution());
Result_ result = function.apply(scoreDirector);
scoreDirector.triggerVariableListeners();
scoreDirector.calculateScore();
setSolution(scoreDirector.getWorkingSolution());
return result;
}
}
public List<ConstraintMatchTotal<Score_>> getConstraintMatchTotalList() {
return solutionManager.explain(getSolution(), NO_UPDATE)
.getConstraintMatchTotalMap()
.values()
.stream()
.sorted()
.collect(toList());
}
public Map<Object, Indictment<Score_>> getIndictmentMap() {
return solutionManager.explain(getSolution(), NO_UPDATE).getIndictmentMap();
}
public void importSolution(File file) {
AbstractSolutionImporter<Solution_> importer = determineImporter(file);
Solution_ solution = importer.readSolution(file);
solutionFileName = file.getName();
setSolution(solution);
}
private AbstractSolutionImporter<Solution_> determineImporter(File file) {
for (AbstractSolutionImporter<Solution_> importer : importers) {
if (importer.acceptInputFile(file)) {
return importer;
}
}
return importers.stream()
.findFirst()
.orElseThrow();
}
public void openSolution(File file) {
Solution_ solution = solutionFileIO.read(file);
LOGGER.info("Opened: {}", file);
solutionFileName = file.getName();
workingSolutionRef.set(solution);
}
public void saveSolution(File file) {
solutionFileIO.write(getSolution(), file);
LOGGER.info("Saved: {}", file);
}
public void exportSolution(AbstractSolutionExporter<Solution_> exporter, File file) {
exporter.writeSolution(getSolution(), file);
}
private void acceptScoreDirector(Consumer<InnerScoreDirector<Solution_, Score_>> consumer) {
applyScoreDirector(s -> {
consumer.accept(s);
return null;
});
}
public void doProblemChange(ProblemChange<Solution_> problemChange) {
SolverJob<Solution_, Long> solverJob = solverJobRef.get();
if (solverJob != null) {
solverJob.addProblemChange(problemChange);
} else {
acceptScoreDirector(scoreDirector -> {
DefaultProblemChangeDirector<Solution_> problemChangeDirector =
new DefaultProblemChangeDirector<>(scoreDirector);
problemChangeDirector.doProblemChange(problemChange);
});
}
}
/**
* Can be called on any thread.
*
* @param problem never null
* @param bestSolutionConsumer never null
* @return never null
*/
public Solution_ solve(Solution_ problem, Consumer<Solution_> bestSolutionConsumer) {
SolverJob<Solution_, Long> solverJob = solverManager.solveBuilder()
.withProblemId(SOLVER_JOB_ID_COUNTER.getAndIncrement())
.withProblemFinder(id -> problem)
.withBestSolutionConsumer(bestSolution -> {
setSolution(bestSolution);
SwingUtilities.invokeLater(() -> {
// Skip this event if a newer one arrived meanwhile to avoid flooding the Swing Event thread.
Solution_ skipToBestSolution = getSolution();
if (bestSolution != skipToBestSolution) {
return;
}
bestSolutionConsumer.accept(bestSolution);
});
})
.run();
solverJobRef.set(solverJob);
try {
return solverJob.getFinalBestSolution();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Solver thread was interrupted.", e);
} catch (ExecutionException e) {
throw new IllegalStateException("Solver threw an exception.", e);
} finally {
solverJobRef.set(null); // Don't keep references to jobs that have finished solving.
}
}
public void terminateSolvingEarly() {
SolverJob<Solution_, Long> solverJob = solverJobRef.get();
if (solverJob != null) {
solverJob.terminateEarly();
}
}
@Override
public void close() {
terminateSolvingEarly();
solverManager.close();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/domain/AbstractPersistable.java | package ai.timefold.solver.examples.common.domain;
import ai.timefold.solver.core.api.domain.lookup.PlanningId;
public abstract class AbstractPersistable {
protected Long id;
protected AbstractPersistable() {
}
protected AbstractPersistable(long id) {
this.id = id;
}
@PlanningId
public long getId() {
return id;
}
protected void setId(long id) {
this.id = id;
}
@Override
public String toString() {
return getClass().getName().replaceAll(".*\\.", "") + "-" + id;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental/ExperimentalConstraintCollectors.java | package ai.timefold.solver.examples.common.experimental;
import java.time.Duration;
import java.time.temporal.Temporal;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.ToLongFunction;
import ai.timefold.solver.core.api.function.PentaFunction;
import ai.timefold.solver.core.api.function.QuadFunction;
import ai.timefold.solver.core.api.function.TriFunction;
import ai.timefold.solver.core.api.score.stream.bi.BiConstraintCollector;
import ai.timefold.solver.core.api.score.stream.quad.QuadConstraintCollector;
import ai.timefold.solver.core.api.score.stream.tri.TriConstraintCollector;
import ai.timefold.solver.core.api.score.stream.uni.UniConstraintCollector;
import ai.timefold.solver.examples.common.experimental.api.ConsecutiveIntervalInfo;
import ai.timefold.solver.examples.common.experimental.impl.Interval;
import ai.timefold.solver.examples.common.experimental.impl.IntervalTree;
/**
* A collection of experimental constraint collectors subject to change in future versions.
*/
public class ExperimentalConstraintCollectors {
/**
* Creates a constraint collector that returns {@link ConsecutiveIntervalInfo} about the first fact.
*
* For instance, {@code [Shift from=2, to=4] [Shift from=3, to=5] [Shift from=6, to=7] [Shift from=7, to=8]}
* returns the following information:
*
* <pre>
* {@code
* IntervalClusters: [[Shift from=2, to=4] [Shift from=3, to=5]], [[Shift from=6, to=7] [Shift from=7, to=8]]
* Breaks: [[Break from=5, to=6, length=1]]
* }
* </pre>
*
* @param startMap Maps the fact to its start
* @param endMap Maps the fact to its end
* @param differenceFunction Computes the difference between two points. The second argument is always
* larger than the first (ex: {@link Duration#between}
* or {@code (a,b) -> b - a}).
* @param <A> type of the first mapped fact
* @param <PointType_> type of the fact endpoints
* @param <DifferenceType_> type of difference between points
* @return never null
*/
public static <A, PointType_ extends Comparable<PointType_>, DifferenceType_ extends Comparable<DifferenceType_>>
UniConstraintCollector<A, IntervalTree<A, PointType_, DifferenceType_>, ConsecutiveIntervalInfo<A, PointType_, DifferenceType_>>
consecutiveIntervals(Function<A, PointType_> startMap, Function<A, PointType_> endMap,
BiFunction<PointType_, PointType_, DifferenceType_> differenceFunction) {
return new UniConstraintCollector<>() {
@Override
public Supplier<IntervalTree<A, PointType_, DifferenceType_>> supplier() {
return () -> new IntervalTree<>(
startMap,
endMap, differenceFunction);
}
@Override
public BiFunction<IntervalTree<A, PointType_, DifferenceType_>, A, Runnable> accumulator() {
return (acc, a) -> {
Interval<A, PointType_> interval = acc.getInterval(a);
acc.add(interval);
return () -> acc.remove(interval);
};
}
@Override
public Function<IntervalTree<A, PointType_, DifferenceType_>, ConsecutiveIntervalInfo<A, PointType_, DifferenceType_>>
finisher() {
return IntervalTree::getConsecutiveIntervalData;
}
};
}
/**
* Specialized version of {@link #consecutiveIntervals(Function,Function,BiFunction)} for
* {@link Temporal} types.
*
* @param <A> type of the first mapped fact
* @param <PointType_> temporal type of the endpoints
* @param startMap Maps the fact to its start
* @param endMap Maps the fact to its end
* @return never null
*/
public static <A, PointType_ extends Temporal & Comparable<PointType_>>
UniConstraintCollector<A, IntervalTree<A, PointType_, Duration>, ConsecutiveIntervalInfo<A, PointType_, Duration>>
consecutiveTemporalIntervals(Function<A, PointType_> startMap, Function<A, PointType_> endMap) {
return consecutiveIntervals(startMap, endMap, Duration::between);
}
/**
* Specialized version of {@link #consecutiveIntervals(Function,Function,BiFunction)} for Long.
*
* @param startMap Maps the fact to its start
* @param endMap Maps the fact to its end
* @param <A> type of the first mapped fact
* @return never null
*/
public static <A> UniConstraintCollector<A, IntervalTree<A, Long, Long>, ConsecutiveIntervalInfo<A, Long, Long>>
consecutiveIntervals(ToLongFunction<A> startMap, ToLongFunction<A> endMap) {
return consecutiveIntervals(startMap::applyAsLong, endMap::applyAsLong, (a, b) -> b - a);
}
/**
* As defined by {@link #consecutiveIntervals(Function,Function,BiFunction)}.
*
* @param intervalMap Maps both facts to an item in the cluster
* @param startMap Maps the item to its start
* @param endMap Maps the item to its end
* @param differenceFunction Computes the difference between two points. The second argument is always
* larger than the first (ex: {@link Duration#between}
* or {@code (a,b) -> b - a}).
* @param <A> type of the first mapped fact
* @param <B> type of the second mapped fact
* @param <IntervalType_> type of the item in the cluster
* @param <PointType_> type of the item endpoints
* @param <DifferenceType_> type of difference between points
* @return never null
*/
public static <A, B, IntervalType_, PointType_ extends Comparable<PointType_>, DifferenceType_ extends Comparable<DifferenceType_>>
BiConstraintCollector<A, B, IntervalTree<IntervalType_, PointType_, DifferenceType_>, ConsecutiveIntervalInfo<IntervalType_, PointType_, DifferenceType_>>
consecutiveIntervals(BiFunction<A, B, IntervalType_> intervalMap, Function<IntervalType_, PointType_> startMap,
Function<IntervalType_, PointType_> endMap,
BiFunction<PointType_, PointType_, DifferenceType_> differenceFunction) {
return new BiConstraintCollector<>() {
@Override
public Supplier<IntervalTree<IntervalType_, PointType_, DifferenceType_>> supplier() {
return () -> new IntervalTree<>(
startMap,
endMap, differenceFunction);
}
@Override
public TriFunction<IntervalTree<IntervalType_, PointType_, DifferenceType_>, A, B, Runnable> accumulator() {
return (acc, a, b) -> {
IntervalType_ intervalObj = intervalMap.apply(a, b);
Interval<IntervalType_, PointType_> interval = acc.getInterval(intervalObj);
acc.add(interval);
return () -> acc.remove(interval);
};
}
@Override
public Function<IntervalTree<IntervalType_, PointType_, DifferenceType_>, ConsecutiveIntervalInfo<IntervalType_, PointType_, DifferenceType_>>
finisher() {
return IntervalTree::getConsecutiveIntervalData;
}
};
}
/**
* As defined by {@link #consecutiveTemporalIntervals(Function,Function)}.
*
* @param intervalMap Maps the three facts to an item in the cluster
* @param startMap Maps the fact to its start
* @param endMap Maps the fact to its end
* @param <A> type of the first mapped fact
* @param <B> type of the second mapped fact
* @param <IntervalType_> type of the item in the cluster
* @param <PointType_> temporal type of the endpoints
* @return never null
*/
public static <A, B, IntervalType_, PointType_ extends Temporal & Comparable<PointType_>>
BiConstraintCollector<A, B, IntervalTree<IntervalType_, PointType_, Duration>, ConsecutiveIntervalInfo<IntervalType_, PointType_, Duration>>
consecutiveTemporalIntervals(BiFunction<A, B, IntervalType_> intervalMap,
Function<IntervalType_, PointType_> startMap, Function<IntervalType_, PointType_> endMap) {
return consecutiveIntervals(intervalMap, startMap, endMap, Duration::between);
}
/**
* As defined by {@link #consecutiveIntervals(ToLongFunction, ToLongFunction)}.
*
* @param startMap Maps the fact to its start
* @param endMap Maps the fact to its end
* @param <A> type of the first mapped fact
* @param <B> type of the second mapped fact
* @param <IntervalType_> type of the item in the cluster
* @return never null
*/
public static <A, B, IntervalType_>
BiConstraintCollector<A, B, IntervalTree<IntervalType_, Long, Long>, ConsecutiveIntervalInfo<IntervalType_, Long, Long>>
consecutiveIntervals(BiFunction<A, B, IntervalType_> intervalMap, ToLongFunction<IntervalType_> startMap,
ToLongFunction<IntervalType_> endMap) {
return consecutiveIntervals(intervalMap, startMap::applyAsLong, endMap::applyAsLong, (a, b) -> b - a);
}
/**
* As defined by {@link #consecutiveIntervals(Function,Function,BiFunction)}.
*
* @param intervalMap Maps the three facts to an item in the cluster
* @param startMap Maps the item to its start
* @param endMap Maps the item to its end
* @param differenceFunction Computes the difference between two points. The second argument is always
* larger than the first (ex: {@link Duration#between}
* or {@code (a,b) -> b - a}).
* @param <A> type of the first mapped fact
* @param <B> type of the second mapped fact
* @param <C> type of the third mapped fact
* @param <IntervalType_> type of the item in the cluster
* @param <PointType_> type of the item endpoints
* @param <DifferenceType_> type of difference between points
* @return never null
*/
public static <A, B, C, IntervalType_, PointType_ extends Comparable<PointType_>, DifferenceType_ extends Comparable<DifferenceType_>>
TriConstraintCollector<A, B, C, IntervalTree<IntervalType_, PointType_, DifferenceType_>, ConsecutiveIntervalInfo<IntervalType_, PointType_, DifferenceType_>>
consecutiveIntervals(TriFunction<A, B, C, IntervalType_> intervalMap, Function<IntervalType_, PointType_> startMap,
Function<IntervalType_, PointType_> endMap,
BiFunction<PointType_, PointType_, DifferenceType_> differenceFunction) {
return new TriConstraintCollector<>() {
@Override
public Supplier<IntervalTree<IntervalType_, PointType_, DifferenceType_>> supplier() {
return () -> new IntervalTree<>(
startMap,
endMap, differenceFunction);
}
@Override
public QuadFunction<IntervalTree<IntervalType_, PointType_, DifferenceType_>, A, B, C, Runnable> accumulator() {
return (acc, a, b, c) -> {
IntervalType_ intervalObj = intervalMap.apply(a, b, c);
Interval<IntervalType_, PointType_> interval = acc.getInterval(intervalObj);
acc.add(interval);
return () -> acc.remove(interval);
};
}
@Override
public Function<IntervalTree<IntervalType_, PointType_, DifferenceType_>, ConsecutiveIntervalInfo<IntervalType_, PointType_, DifferenceType_>>
finisher() {
return IntervalTree::getConsecutiveIntervalData;
}
};
}
/**
* As defined by {@link #consecutiveTemporalIntervals(Function,Function)}.
*
* @param intervalMap Maps the three facts to an item in the cluster
* @param startMap Maps the fact to its start
* @param endMap Maps the fact to its end
* @param <A> type of the first mapped fact
* @param <B> type of the second mapped fact
* @param <C> type of the third mapped fact
* @param <IntervalType_> type of the item in the cluster
* @param <PointType_> temporal type of the endpoints
* @return never null
*/
public static <A, B, C, IntervalType_, PointType_ extends Temporal & Comparable<PointType_>>
TriConstraintCollector<A, B, C, IntervalTree<IntervalType_, PointType_, Duration>, ConsecutiveIntervalInfo<IntervalType_, PointType_, Duration>>
consecutiveTemporalIntervals(TriFunction<A, B, C, IntervalType_> intervalMap,
Function<IntervalType_, PointType_> startMap, Function<IntervalType_, PointType_> endMap) {
return consecutiveIntervals(intervalMap, startMap, endMap, Duration::between);
}
/**
* As defined by {@link #consecutiveIntervals(ToLongFunction, ToLongFunction)}.
*
* @param startMap Maps the fact to its start
* @param endMap Maps the fact to its end
* @param <A> type of the first mapped fact
* @param <B> type of the second mapped fact
* @param <C> type of the third mapped fact
* @param <IntervalType_> type of the item in the cluster
* @return never null
*/
public static <A, B, C, IntervalType_>
TriConstraintCollector<A, B, C, IntervalTree<IntervalType_, Long, Long>, ConsecutiveIntervalInfo<IntervalType_, Long, Long>>
consecutiveIntervals(TriFunction<A, B, C, IntervalType_> intervalMap, ToLongFunction<IntervalType_> startMap,
ToLongFunction<IntervalType_> endMap) {
return consecutiveIntervals(intervalMap, startMap::applyAsLong, endMap::applyAsLong, (a, b) -> b - a);
}
/**
* As defined by {@link #consecutiveIntervals(Function,Function,BiFunction)}.
*
* @param intervalMap Maps the four facts to an item in the cluster
* @param startMap Maps the item to its start
* @param endMap Maps the item to its end
* @param differenceFunction Computes the difference between two points. The second argument is always
* larger than the first (ex: {@link Duration#between}
* or {@code (a,b) -> b - a}).
* @param <A> type of the first mapped fact
* @param <B> type of the second mapped fact
* @param <C> type of the third mapped fact
* @param <D> type of the fourth mapped fact
* @param <IntervalType_> type of the item in the cluster
* @param <PointType_> type of the item endpoints
* @param <DifferenceType_> type of difference between points
* @return never null
*/
public static <A, B, C, D, IntervalType_, PointType_ extends Comparable<PointType_>, DifferenceType_ extends Comparable<DifferenceType_>>
QuadConstraintCollector<A, B, C, D, IntervalTree<IntervalType_, PointType_, DifferenceType_>, ConsecutiveIntervalInfo<IntervalType_, PointType_, DifferenceType_>>
consecutiveIntervals(QuadFunction<A, B, C, D, IntervalType_> intervalMap,
Function<IntervalType_, PointType_> startMap, Function<IntervalType_, PointType_> endMap,
BiFunction<PointType_, PointType_, DifferenceType_> differenceFunction) {
return new QuadConstraintCollector<>() {
@Override
public Supplier<IntervalTree<IntervalType_, PointType_, DifferenceType_>> supplier() {
return () -> new IntervalTree<>(
startMap,
endMap, differenceFunction);
}
@Override
public PentaFunction<IntervalTree<IntervalType_, PointType_, DifferenceType_>, A, B, C, D, Runnable> accumulator() {
return (acc, a, b, c, d) -> {
IntervalType_ intervalObj = intervalMap.apply(a, b, c, d);
Interval<IntervalType_, PointType_> interval = acc.getInterval(intervalObj);
acc.add(interval);
return () -> acc.remove(interval);
};
}
@Override
public Function<IntervalTree<IntervalType_, PointType_, DifferenceType_>, ConsecutiveIntervalInfo<IntervalType_, PointType_, DifferenceType_>>
finisher() {
return IntervalTree::getConsecutiveIntervalData;
}
};
}
/**
* As defined by {@link #consecutiveTemporalIntervals(Function,Function)}.
*
* @param intervalMap Maps the three facts to an item in the cluster
* @param startMap Maps the fact to its start
* @param endMap Maps the fact to its end
* @param <A> type of the first mapped fact
* @param <B> type of the second mapped fact
* @param <C> type of the third mapped fact
* @param <D> type of the fourth mapped fact
* @param <IntervalType_> type of the item in the cluster
* @param <PointType_> temporal type of the endpoints
* @return never null
*/
public static <A, B, C, D, IntervalType_, PointType_ extends Temporal & Comparable<PointType_>>
QuadConstraintCollector<A, B, C, D, IntervalTree<IntervalType_, PointType_, Duration>, ConsecutiveIntervalInfo<IntervalType_, PointType_, Duration>>
consecutiveTemporalIntervals(QuadFunction<A, B, C, D, IntervalType_> intervalMap,
Function<IntervalType_, PointType_> startMap, Function<IntervalType_, PointType_> endMap) {
return consecutiveIntervals(intervalMap, startMap, endMap, Duration::between);
}
/**
* As defined by {@link #consecutiveIntervals(ToLongFunction, ToLongFunction)}.
*
* @param startMap Maps the fact to its start
* @param endMap Maps the fact to its end
* @param <A> type of the first mapped fact
* @param <B> type of the second mapped fact
* @param <C> type of the third mapped fact
* @param <D> type of the fourth mapped fact
* @param <IntervalType_> type of the item in the cluster
* @return never null
*/
public static <A, B, C, D, IntervalType_>
QuadConstraintCollector<A, B, C, D, IntervalTree<IntervalType_, Long, Long>, ConsecutiveIntervalInfo<IntervalType_, Long, Long>>
consecutiveIntervals(QuadFunction<A, B, C, D, IntervalType_> intervalMap, ToLongFunction<IntervalType_> startMap,
ToLongFunction<IntervalType_> endMap) {
return consecutiveIntervals(intervalMap, startMap::applyAsLong, endMap::applyAsLong, (a, b) -> b - a);
}
// Hide constructor since this is a factory class
private ExperimentalConstraintCollectors() {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental/api/ConsecutiveIntervalInfo.java | package ai.timefold.solver.examples.common.experimental.api;
public interface ConsecutiveIntervalInfo<Interval_, Point_ extends Comparable<Point_>, Difference_ extends Comparable<Difference_>> {
/**
* @return never null, an iterable that iterates through the interval clusters
* contained in the collection in ascending order
*/
Iterable<IntervalCluster<Interval_, Point_, Difference_>> getIntervalClusters();
/**
* @return never null, an iterable that iterates through the breaks contained in
* the collection in ascending order
*/
Iterable<IntervalBreak<Interval_, Point_, Difference_>> getBreaks();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental/api/IntervalBreak.java | package ai.timefold.solver.examples.common.experimental.api;
/**
* An IntervalBreak is a gap between two consecutive interval clusters. For instance,
* the list [(1,3),(2,4),(3,5),(7,8)] has a break of length 2 between 5 and 7.
*
* @param <Interval_> The type of value in the sequence
* @param <Difference_> The type of difference between values in the sequence
*/
public interface IntervalBreak<Interval_, Point_ extends Comparable<Point_>, Difference_ extends Comparable<Difference_>> {
/**
* @return never null, the interval cluster leading directly into this
*/
IntervalCluster<Interval_, Point_, Difference_> getPreviousIntervalCluster();
/**
* @return never null, the interval cluster immediately following this
*/
IntervalCluster<Interval_, Point_, Difference_> getNextIntervalCluster();
/**
* Return the end of the sequence before this break. For the
* break between 6 and 10, this will return 6.
*
* @return never null, the item this break is directly after
*/
default Point_ getPreviousIntervalClusterEnd() {
return getPreviousIntervalCluster().getEnd();
};
/**
* Return the start of the sequence after this break. For the
* break between 6 and 10, this will return 10.
*
* @return never null, the item this break is directly before
*/
default Point_ getNextIntervalClusterStart() {
return getNextIntervalCluster().getStart();
}
/**
* Return the length of the break, which is the difference
* between {@link #getNextIntervalClusterStart()} and {@link #getPreviousIntervalClusterEnd()}. For the
* break between 6 and 10, this will return 4.
*
* @return never null, the length of this break
*/
Difference_ getLength();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental/api/IntervalCluster.java | package ai.timefold.solver.examples.common.experimental.api;
public interface IntervalCluster<Interval_, Point_ extends Comparable<Point_>, Difference_ extends Comparable<Difference_>>
extends Iterable<Interval_> {
int size();
boolean hasOverlap();
Difference_ getLength();
Point_ getStart();
Point_ getEnd();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental/impl/ConsecutiveIntervalInfoImpl.java | package ai.timefold.solver.examples.common.experimental.impl;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Objects;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.BiFunction;
import ai.timefold.solver.examples.common.experimental.api.ConsecutiveIntervalInfo;
import ai.timefold.solver.examples.common.experimental.api.IntervalBreak;
import ai.timefold.solver.examples.common.experimental.api.IntervalCluster;
public final class ConsecutiveIntervalInfoImpl<Interval_, Point_ extends Comparable<Point_>, Difference_ extends Comparable<Difference_>>
implements ConsecutiveIntervalInfo<Interval_, Point_, Difference_> {
private final NavigableMap<IntervalSplitPoint<Interval_, Point_>, IntervalClusterImpl<Interval_, Point_, Difference_>> clusterStartSplitPointToCluster;
private final NavigableSet<IntervalSplitPoint<Interval_, Point_>> splitPointSet;
private final NavigableMap<IntervalSplitPoint<Interval_, Point_>, IntervalBreakImpl<Interval_, Point_, Difference_>> clusterStartSplitPointToNextBreak;
private final BiFunction<Point_, Point_, Difference_> differenceFunction;
public ConsecutiveIntervalInfoImpl(TreeSet<IntervalSplitPoint<Interval_, Point_>> splitPointSet,
BiFunction<Point_, Point_, Difference_> differenceFunction) {
this.clusterStartSplitPointToCluster = new TreeMap<>();
this.clusterStartSplitPointToNextBreak = new TreeMap<>();
this.splitPointSet = splitPointSet;
this.differenceFunction = differenceFunction;
}
void addInterval(Interval<Interval_, Point_> interval) {
var intersectedIntervalClusterMap = clusterStartSplitPointToCluster
.subMap(Objects.requireNonNullElseGet(clusterStartSplitPointToCluster.floorKey(interval.getStartSplitPoint()),
interval::getStartSplitPoint), true, interval.getEndSplitPoint(), true);
// Case: the interval cluster before this interval does not intersect this interval
if (!intersectedIntervalClusterMap.isEmpty()
&& intersectedIntervalClusterMap.firstEntry().getValue().getEndSplitPoint()
.isBefore(interval.getStartSplitPoint())) {
// Get the tail map after the first cluster
intersectedIntervalClusterMap = intersectedIntervalClusterMap.subMap(intersectedIntervalClusterMap.firstKey(),
false, intersectedIntervalClusterMap.lastKey(), true);
}
if (intersectedIntervalClusterMap.isEmpty()) {
// Interval does not intersect anything
// Ex:
// -----
//---- -----
createNewIntervalCluster(interval);
return;
}
// Interval intersect at least one cluster
// Ex:
// -----------------
// ------ ------ --- ----
var firstIntersectedIntervalCluster = intersectedIntervalClusterMap.firstEntry().getValue();
var oldStartSplitPoint = firstIntersectedIntervalCluster.getStartSplitPoint();
firstIntersectedIntervalCluster.addInterval(interval);
// Merge all the intersected interval clusters into the first intersected
// interval cluster
intersectedIntervalClusterMap.tailMap(oldStartSplitPoint, false).values()
.forEach(firstIntersectedIntervalCluster::mergeIntervalCluster);
// Remove all the intersected interval clusters after the first intersected
// one, since they are now merged in the first
intersectedIntervalClusterMap.tailMap(oldStartSplitPoint, false).clear();
removeSpannedBreaksAndUpdateIntersectedBreaks(interval, firstIntersectedIntervalCluster);
// If the first intersected interval cluster start after the interval,
// we need to make the interval start point the key for this interval
// cluster in the map
if (oldStartSplitPoint.isAfter(firstIntersectedIntervalCluster.getStartSplitPoint())) {
clusterStartSplitPointToCluster.remove(oldStartSplitPoint);
clusterStartSplitPointToCluster.put(firstIntersectedIntervalCluster.getStartSplitPoint(),
firstIntersectedIntervalCluster);
var nextBreak = clusterStartSplitPointToNextBreak.get(firstIntersectedIntervalCluster.getStartSplitPoint());
if (nextBreak != null) {
nextBreak.setPreviousCluster(firstIntersectedIntervalCluster);
nextBreak.setLength(differenceFunction.apply(nextBreak.getPreviousIntervalClusterEnd(),
nextBreak.getNextIntervalClusterStart()));
}
}
}
private void createNewIntervalCluster(Interval<Interval_, Point_> interval) {
// Interval does not intersect anything
// Ex:
// -----
//---- -----
var startSplitPoint = splitPointSet.floor(interval.getStartSplitPoint());
var newCluster = new IntervalClusterImpl<>(splitPointSet, differenceFunction, startSplitPoint);
clusterStartSplitPointToCluster.put(startSplitPoint, newCluster);
// If there a cluster after this interval, add a new break
// between this interval and the next cluster
var nextClusterEntry = clusterStartSplitPointToCluster.higherEntry(startSplitPoint);
if (nextClusterEntry != null) {
var nextCluster = nextClusterEntry.getValue();
var difference = differenceFunction.apply(newCluster.getEnd(), nextCluster.getStart());
var newBreak = new IntervalBreakImpl<>(newCluster, nextCluster, difference);
clusterStartSplitPointToNextBreak.put(startSplitPoint, newBreak);
}
// If there a cluster before this interval, add a new break
// between this interval and the previous cluster
// (this will replace the old break, if there was one)
var previousClusterEntry = clusterStartSplitPointToCluster.lowerEntry(startSplitPoint);
if (previousClusterEntry != null) {
var previousCluster = previousClusterEntry.getValue();
var difference = differenceFunction.apply(previousCluster.getEnd(), newCluster.getStart());
var newBreak = new IntervalBreakImpl<>(previousCluster, newCluster, difference);
clusterStartSplitPointToNextBreak.put(previousClusterEntry.getKey(), newBreak);
}
}
private void removeSpannedBreaksAndUpdateIntersectedBreaks(Interval<Interval_, Point_> interval,
IntervalClusterImpl<Interval_, Point_, Difference_> intervalCluster) {
var firstBreakSplitPointBeforeInterval = Objects.requireNonNullElseGet(
clusterStartSplitPointToNextBreak.floorKey(interval.getStartSplitPoint()), interval::getStartSplitPoint);
var intersectedIntervalBreakMap = clusterStartSplitPointToNextBreak.subMap(firstBreakSplitPointBeforeInterval, true,
interval.getEndSplitPoint(), true);
if (intersectedIntervalBreakMap.isEmpty()) {
return;
}
var clusterBeforeFirstIntersectedBreak =
(IntervalClusterImpl<Interval_, Point_, Difference_>) (intersectedIntervalBreakMap.firstEntry().getValue()
.getPreviousIntervalCluster());
var clusterAfterFinalIntersectedBreak =
(IntervalClusterImpl<Interval_, Point_, Difference_>) (intersectedIntervalBreakMap.lastEntry().getValue()
.getNextIntervalCluster());
// All breaks that are not the first or last intersected breaks will
// be removed (as interval span them)
if (!interval.getStartSplitPoint()
.isAfter(clusterBeforeFirstIntersectedBreak.getEndSplitPoint())) {
if (!interval.getEndSplitPoint().isBefore(clusterAfterFinalIntersectedBreak.getStartSplitPoint())) {
// Case: interval spans all breaks
// Ex:
// -----------
//---- ------ -----
intersectedIntervalBreakMap.clear();
} else {
// Case: interval span first break, but does not span the final break
// Ex:
// -----------
//---- ------ -----
var finalBreak = intersectedIntervalBreakMap.lastEntry().getValue();
finalBreak.setPreviousCluster(intervalCluster);
finalBreak.setLength(
differenceFunction.apply(finalBreak.getPreviousIntervalClusterEnd(),
finalBreak.getNextIntervalClusterStart()));
intersectedIntervalBreakMap.clear();
clusterStartSplitPointToNextBreak.put(intervalCluster.getStartSplitPoint(), finalBreak);
}
} else if (!interval.getEndSplitPoint().isBefore(clusterAfterFinalIntersectedBreak.getStartSplitPoint())) {
// Case: interval span final break, but does not span the first break
// Ex:
// -----------
//---- ----- -----
var previousBreakEntry = intersectedIntervalBreakMap.firstEntry();
var previousBreak = previousBreakEntry.getValue();
previousBreak.setNextCluster(intervalCluster);
previousBreak.setLength(
differenceFunction.apply(previousBreak.getPreviousIntervalClusterEnd(), intervalCluster.getStart()));
intersectedIntervalBreakMap.clear();
clusterStartSplitPointToNextBreak
.put(((IntervalClusterImpl<Interval_, Point_, Difference_>) (previousBreak
.getPreviousIntervalCluster())).getStartSplitPoint(), previousBreak);
} else {
// Case: interval does not span either the first or final break
// Ex:
// ---------
//---- ------ -----
var finalBreak = intersectedIntervalBreakMap.lastEntry().getValue();
finalBreak.setLength(differenceFunction.apply(finalBreak.getPreviousIntervalClusterEnd(),
finalBreak.getNextIntervalClusterStart()));
var previousBreakEntry = intersectedIntervalBreakMap.firstEntry();
var previousBreak = previousBreakEntry.getValue();
previousBreak.setNextCluster(intervalCluster);
previousBreak.setLength(
differenceFunction.apply(previousBreak.getPreviousIntervalClusterEnd(), intervalCluster.getStart()));
intersectedIntervalBreakMap.clear();
clusterStartSplitPointToNextBreak.put(previousBreakEntry.getKey(), previousBreak);
clusterStartSplitPointToNextBreak.put(intervalCluster.getStartSplitPoint(), finalBreak);
}
}
void removeInterval(Interval<Interval_, Point_> interval) {
var intervalClusterEntry = clusterStartSplitPointToCluster.floorEntry(interval.getStartSplitPoint());
var intervalCluster = intervalClusterEntry.getValue();
clusterStartSplitPointToCluster.remove(intervalClusterEntry.getKey());
var previousBreakEntry = clusterStartSplitPointToNextBreak.lowerEntry(intervalClusterEntry.getKey());
var nextIntervalClusterEntry = clusterStartSplitPointToCluster.higherEntry(intervalClusterEntry.getKey());
clusterStartSplitPointToNextBreak.remove(intervalClusterEntry.getKey());
var previousBreak = (previousBreakEntry != null) ? previousBreakEntry.getValue() : null;
var previousIntervalCluster = (previousBreak != null)
? (IntervalClusterImpl<Interval_, Point_, Difference_>) previousBreak.getPreviousIntervalCluster()
: null;
for (var newIntervalCluster : intervalCluster.removeInterval(interval)) {
if (previousBreak != null) {
previousBreak.setNextCluster(newIntervalCluster);
previousBreak.setLength(differenceFunction.apply(previousBreak.getPreviousIntervalCluster().getEnd(),
newIntervalCluster.getStart()));
clusterStartSplitPointToNextBreak
.put(((IntervalClusterImpl<Interval_, Point_, Difference_>) previousBreak
.getPreviousIntervalCluster()).getStartSplitPoint(), previousBreak);
}
previousBreak = new IntervalBreakImpl<>(newIntervalCluster, null, null);
previousIntervalCluster = newIntervalCluster;
clusterStartSplitPointToCluster.put(newIntervalCluster.getStartSplitPoint(), newIntervalCluster);
}
if (nextIntervalClusterEntry != null && previousBreak != null) {
previousBreak.setNextCluster(nextIntervalClusterEntry.getValue());
previousBreak.setLength(differenceFunction.apply(previousIntervalCluster.getEnd(),
nextIntervalClusterEntry.getValue().getStart()));
clusterStartSplitPointToNextBreak.put(previousIntervalCluster.getStartSplitPoint(),
previousBreak);
} else if (previousBreakEntry != null && previousBreak == previousBreakEntry.getValue()) {
// i.e. interval was the last interval in the cluster,
// (previousBreak == previousBreakEntry.getValue()),
// and there is no interval cluster after it
// (previousBreak != null as previousBreakEntry != null,
// so it must be the case nextIntervalClusterEntry == null)
clusterStartSplitPointToNextBreak.remove(previousBreakEntry.getKey());
}
}
@Override
public Iterable<IntervalCluster<Interval_, Point_, Difference_>> getIntervalClusters() {
return (Iterable) clusterStartSplitPointToCluster.values();
}
@Override
public Iterable<IntervalBreak<Interval_, Point_, Difference_>> getBreaks() {
return (Iterable) clusterStartSplitPointToNextBreak.values();
}
@Override
public String toString() {
return "Clusters {" +
"intervalClusters=" + getIntervalClusters() +
", breaks=" + getBreaks() +
'}';
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental/impl/Interval.java | package ai.timefold.solver.examples.common.experimental.impl;
import java.util.function.Function;
public final class Interval<Interval_, Point_ extends Comparable<Point_>> {
private final Interval_ value;
private final IntervalSplitPoint<Interval_, Point_> startSplitPoint;
private final IntervalSplitPoint<Interval_, Point_> endSplitPoint;
public Interval(Interval_ value, Function<Interval_, Point_> startMapping, Function<Interval_, Point_> endMapping) {
this.value = value;
var start = startMapping.apply(value);
var end = endMapping.apply(value);
this.startSplitPoint = new IntervalSplitPoint<>(start);
this.endSplitPoint = (start == end) ? this.startSplitPoint : new IntervalSplitPoint<>(end);
}
public Interval_ getValue() {
return value;
}
public Point_ getStart() {
return startSplitPoint.splitPoint;
}
public Point_ getEnd() {
return endSplitPoint.splitPoint;
}
public IntervalSplitPoint<Interval_, Point_> getStartSplitPoint() {
return startSplitPoint;
}
public IntervalSplitPoint<Interval_, Point_> getEndSplitPoint() {
return endSplitPoint;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Interval<?, ?> that = (Interval<?, ?>) o;
return value == that.value;
}
@Override
public int hashCode() {
return System.identityHashCode(value);
}
@Override
public String toString() {
return "Interval{" +
"value=" + value +
", start=" + getStart() +
", end=" + getEnd() +
'}';
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental/impl/IntervalBreakImpl.java | package ai.timefold.solver.examples.common.experimental.impl;
import ai.timefold.solver.examples.common.experimental.api.IntervalBreak;
import ai.timefold.solver.examples.common.experimental.api.IntervalCluster;
final class IntervalBreakImpl<Interval_, Point_ extends Comparable<Point_>, Difference_ extends Comparable<Difference_>>
implements IntervalBreak<Interval_, Point_, Difference_> {
private IntervalCluster<Interval_, Point_, Difference_> previousCluster;
private IntervalCluster<Interval_, Point_, Difference_> nextCluster;
private Difference_ length;
IntervalBreakImpl(IntervalCluster<Interval_, Point_, Difference_> previousCluster,
IntervalCluster<Interval_, Point_, Difference_> nextCluster, Difference_ length) {
this.previousCluster = previousCluster;
this.nextCluster = nextCluster;
this.length = length;
}
@Override
public IntervalCluster<Interval_, Point_, Difference_> getPreviousIntervalCluster() {
return previousCluster;
}
@Override
public IntervalCluster<Interval_, Point_, Difference_> getNextIntervalCluster() {
return nextCluster;
}
@Override
public Difference_ getLength() {
return length;
}
void setPreviousCluster(IntervalCluster<Interval_, Point_, Difference_> previousCluster) {
this.previousCluster = previousCluster;
}
void setNextCluster(IntervalCluster<Interval_, Point_, Difference_> nextCluster) {
this.nextCluster = nextCluster;
}
void setLength(Difference_ length) {
this.length = length;
}
@Override
public String toString() {
return "IntervalBreak{" +
"previousCluster=" + previousCluster +
", nextCluster=" + nextCluster +
", length=" + length +
'}';
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental/impl/IntervalClusterImpl.java | package ai.timefold.solver.examples.common.experimental.impl;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.function.BiFunction;
import ai.timefold.solver.examples.common.experimental.api.IntervalCluster;
final class IntervalClusterImpl<Interval_, Point_ extends Comparable<Point_>, Difference_ extends Comparable<Difference_>>
implements IntervalCluster<Interval_, Point_, Difference_> {
private final NavigableSet<IntervalSplitPoint<Interval_, Point_>> splitPointSet;
private final BiFunction<Point_, Point_, Difference_> differenceFunction;
private IntervalSplitPoint<Interval_, Point_> startSplitPoint;
private IntervalSplitPoint<Interval_, Point_> endSplitPoint;
private int count;
private boolean hasOverlap;
IntervalClusterImpl(NavigableSet<IntervalSplitPoint<Interval_, Point_>> splitPointSet,
BiFunction<Point_, Point_, Difference_> differenceFunction, IntervalSplitPoint<Interval_, Point_> start) {
if (start == null) {
throw new IllegalArgumentException("start (" + start + ") is null");
}
if (differenceFunction == null) {
throw new IllegalArgumentException("differenceFunction (" + differenceFunction + ") is null");
}
this.splitPointSet = splitPointSet;
this.startSplitPoint = start;
this.endSplitPoint = start;
this.differenceFunction = differenceFunction;
this.count = 0;
var activeIntervals = 0;
var anyOverlap = false;
var current = start;
do {
this.count += current.intervalsStartingAtSplitPointSet.size();
activeIntervals += current.intervalsStartingAtSplitPointSet.size() - current.intervalsEndingAtSplitPointSet.size();
if (activeIntervals > 1) {
anyOverlap = true;
}
current = splitPointSet.higher(current);
} while (activeIntervals > 0 && current != null);
this.hasOverlap = anyOverlap;
this.endSplitPoint = (current != null) ? splitPointSet.lower(current) : splitPointSet.last();
}
IntervalClusterImpl(NavigableSet<IntervalSplitPoint<Interval_, Point_>> splitPointSet,
BiFunction<Point_, Point_, Difference_> differenceFunction, IntervalSplitPoint<Interval_, Point_> start,
IntervalSplitPoint<Interval_, Point_> end, int count, boolean hasOverlap) {
this.splitPointSet = splitPointSet;
this.startSplitPoint = start;
this.endSplitPoint = end;
this.differenceFunction = differenceFunction;
this.count = count;
this.hasOverlap = hasOverlap;
}
IntervalSplitPoint<Interval_, Point_> getStartSplitPoint() {
return startSplitPoint;
}
IntervalSplitPoint<Interval_, Point_> getEndSplitPoint() {
return endSplitPoint;
}
void addInterval(Interval<Interval_, Point_> interval) {
if (interval.getEndSplitPoint().compareTo(getStartSplitPoint()) > 0
&& interval.getStartSplitPoint().compareTo(getEndSplitPoint()) < 0) {
hasOverlap = true;
}
if (interval.getStartSplitPoint().compareTo(startSplitPoint) < 0) {
startSplitPoint = splitPointSet.floor(interval.getStartSplitPoint());
}
if (interval.getEndSplitPoint().compareTo(endSplitPoint) > 0) {
endSplitPoint = splitPointSet.ceiling(interval.getEndSplitPoint());
}
count++;
}
Iterable<IntervalClusterImpl<Interval_, Point_, Difference_>> removeInterval(Interval<Interval_, Point_> interval) {
return IntervalClusterIterator::new;
}
void mergeIntervalCluster(IntervalClusterImpl<Interval_, Point_, Difference_> laterIntervalCluster) {
if (endSplitPoint.compareTo(laterIntervalCluster.startSplitPoint) > 0) {
hasOverlap = true;
}
if (endSplitPoint.compareTo(laterIntervalCluster.endSplitPoint) < 0) {
endSplitPoint = laterIntervalCluster.endSplitPoint;
}
count += laterIntervalCluster.count;
hasOverlap |= laterIntervalCluster.hasOverlap;
}
@Override
public Iterator<Interval_> iterator() {
return new IntervalTreeIterator<>(splitPointSet.subSet(startSplitPoint, true, endSplitPoint, true));
}
@Override
public int size() {
return count;
}
@Override
public boolean hasOverlap() {
return hasOverlap;
}
@Override
public Point_ getStart() {
return startSplitPoint.splitPoint;
}
@Override
public Point_ getEnd() {
return endSplitPoint.splitPoint;
}
@Override
public Difference_ getLength() {
return differenceFunction.apply(startSplitPoint.splitPoint, endSplitPoint.splitPoint);
}
@Override
public String toString() {
return "IntervalCluster{" +
"startSplitPoint=" + startSplitPoint +
", endSplitPoint=" + endSplitPoint +
", count=" + count +
", hasOverlap=" + hasOverlap +
'}';
}
// TODO: Make this incremental by only checking between the interval's start and end points
private final class IntervalClusterIterator
implements Iterator<IntervalClusterImpl<Interval_, Point_, Difference_>> {
private IntervalSplitPoint<Interval_, Point_> current = getStart(startSplitPoint);
private IntervalSplitPoint<Interval_, Point_>
getStart(IntervalSplitPoint<Interval_, Point_> start) {
while (start != null && start.isEmpty()) {
start = splitPointSet.higher(start);
}
return start;
}
@Override
public boolean hasNext() {
return current != null && current.compareTo(endSplitPoint) <= 0 && !splitPointSet.isEmpty();
}
@Override
public IntervalClusterImpl<Interval_, Point_, Difference_> next() {
IntervalSplitPoint<Interval_, Point_> start = current;
IntervalSplitPoint<Interval_, Point_> end;
int activeIntervals = 0;
count = 0;
boolean anyOverlap = false;
do {
count += current.intervalsStartingAtSplitPointSet.size();
activeIntervals +=
current.intervalsStartingAtSplitPointSet.size() - current.intervalsEndingAtSplitPointSet.size();
if (activeIntervals > 1) {
anyOverlap = true;
}
current = splitPointSet.higher(current);
} while (activeIntervals > 0 && current != null);
hasOverlap = anyOverlap;
if (current != null) {
end = splitPointSet.lower(current);
current = getStart(current);
} else {
end = splitPointSet.last();
}
return new IntervalClusterImpl<>(splitPointSet, differenceFunction, start, end, count, hasOverlap);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental/impl/IntervalSplitPoint.java | package ai.timefold.solver.examples.common.experimental.impl;
import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.TreeSet;
import java.util.stream.IntStream;
public class IntervalSplitPoint<Interval_, Point_ extends Comparable<Point_>>
implements Comparable<IntervalSplitPoint<Interval_, Point_>> {
final Point_ splitPoint;
Map<Interval_, Integer> startIntervalToCountMap;
Map<Interval_, Integer> endIntervalToCountMap;
TreeSet<Interval<Interval_, Point_>> intervalsStartingAtSplitPointSet;
TreeSet<Interval<Interval_, Point_>> intervalsEndingAtSplitPointSet;
public IntervalSplitPoint(Point_ splitPoint) {
this.splitPoint = splitPoint;
}
protected void createCollections() {
startIntervalToCountMap = new IdentityHashMap<>();
endIntervalToCountMap = new IdentityHashMap<>();
intervalsStartingAtSplitPointSet = new TreeSet<>(
Comparator.<Interval<Interval_, Point_>, Point_> comparing(Interval::getEnd)
.thenComparingInt(interval -> System.identityHashCode(interval.getValue())));
intervalsEndingAtSplitPointSet = new TreeSet<>(
Comparator.<Interval<Interval_, Point_>, Point_> comparing(Interval::getStart)
.thenComparingInt(interval -> System.identityHashCode(interval.getValue())));
}
public boolean addIntervalStartingAtSplitPoint(Interval<Interval_, Point_> interval) {
startIntervalToCountMap.merge(interval.getValue(), 1, Integer::sum);
return intervalsStartingAtSplitPointSet.add(interval);
}
public void removeIntervalStartingAtSplitPoint(Interval<Interval_, Point_> interval) {
Integer newCount = startIntervalToCountMap.computeIfPresent(interval.getValue(), (key, count) -> {
if (count > 1) {
return count - 1;
}
return null;
});
if (null == newCount) {
intervalsStartingAtSplitPointSet.remove(interval);
}
}
public boolean addIntervalEndingAtSplitPoint(Interval<Interval_, Point_> interval) {
endIntervalToCountMap.merge(interval.getValue(), 1, Integer::sum);
return intervalsEndingAtSplitPointSet.add(interval);
}
public void removeIntervalEndingAtSplitPoint(Interval<Interval_, Point_> interval) {
Integer newCount = endIntervalToCountMap.computeIfPresent(interval.getValue(), (key, count) -> {
if (count > 1) {
return count - 1;
}
return null;
});
if (null == newCount) {
intervalsEndingAtSplitPointSet.remove(interval);
}
}
public boolean containsIntervalStarting(Interval<Interval_, Point_> interval) {
return intervalsStartingAtSplitPointSet.contains(interval);
}
public boolean containsIntervalEnding(Interval<Interval_, Point_> interval) {
return intervalsEndingAtSplitPointSet.contains(interval);
}
public Iterator<Interval_> getValuesStartingFromSplitPointIterator() {
return intervalsStartingAtSplitPointSet.stream()
.flatMap(interval -> IntStream.range(0, startIntervalToCountMap.get(interval.getValue()))
.mapToObj(index -> interval.getValue()))
.iterator();
}
public boolean isEmpty() {
return intervalsStartingAtSplitPointSet.isEmpty() && intervalsEndingAtSplitPointSet.isEmpty();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
IntervalSplitPoint<?, ?> that = (IntervalSplitPoint<?, ?>) o;
return splitPoint.equals(that.splitPoint);
}
public boolean isBefore(IntervalSplitPoint<Interval_, Point_> other) {
return compareTo(other) < 0;
}
public boolean isAfter(IntervalSplitPoint<Interval_, Point_> other) {
return compareTo(other) > 0;
}
@Override
public int hashCode() {
return Objects.hash(splitPoint);
}
@Override
public int compareTo(IntervalSplitPoint<Interval_, Point_> other) {
return splitPoint.compareTo(other.splitPoint);
}
@Override
public String toString() {
return splitPoint.toString();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental/impl/IntervalTree.java | package ai.timefold.solver.examples.common.experimental.impl;
import java.util.Iterator;
import java.util.TreeSet;
import java.util.function.BiFunction;
import java.util.function.Function;
public final class IntervalTree<Interval_, Point_ extends Comparable<Point_>, Difference_ extends Comparable<Difference_>> {
private final Function<Interval_, Point_> startMapping;
private final Function<Interval_, Point_> endMapping;
private final TreeSet<IntervalSplitPoint<Interval_, Point_>> splitPointSet;
private final ConsecutiveIntervalInfoImpl<Interval_, Point_, Difference_> consecutiveIntervalData;
public IntervalTree(Function<Interval_, Point_> startMapping, Function<Interval_, Point_> endMapping,
BiFunction<Point_, Point_, Difference_> differenceFunction) {
this.startMapping = startMapping;
this.endMapping = endMapping;
this.splitPointSet = new TreeSet<>();
this.consecutiveIntervalData = new ConsecutiveIntervalInfoImpl<>(splitPointSet, differenceFunction);
}
public Interval<Interval_, Point_> getInterval(Interval_ intervalValue) {
return new Interval<>(intervalValue, startMapping, endMapping);
}
public boolean isEmpty() {
return splitPointSet.isEmpty();
}
public boolean contains(Interval_ o) {
if (null == o || splitPointSet.isEmpty()) {
return false;
}
var interval = getInterval(o);
var floorStartSplitPoint = splitPointSet.floor(interval.getStartSplitPoint());
if (floorStartSplitPoint == null) {
return false;
}
return floorStartSplitPoint.containsIntervalStarting(interval);
}
public Iterator<Interval_> iterator() {
return new IntervalTreeIterator<>(splitPointSet);
}
public boolean add(Interval<Interval_, Point_> interval) {
var startSplitPoint = interval.getStartSplitPoint();
var endSplitPoint = interval.getEndSplitPoint();
boolean isChanged;
var flooredStartSplitPoint = splitPointSet.floor(startSplitPoint);
if (flooredStartSplitPoint == null || !flooredStartSplitPoint.equals(startSplitPoint)) {
splitPointSet.add(startSplitPoint);
startSplitPoint.createCollections();
isChanged = startSplitPoint.addIntervalStartingAtSplitPoint(interval);
} else {
isChanged = flooredStartSplitPoint.addIntervalStartingAtSplitPoint(interval);
}
var ceilingEndSplitPoint = splitPointSet.ceiling(endSplitPoint);
if (ceilingEndSplitPoint == null || !ceilingEndSplitPoint.equals(endSplitPoint)) {
splitPointSet.add(endSplitPoint);
endSplitPoint.createCollections();
isChanged |= endSplitPoint.addIntervalEndingAtSplitPoint(interval);
} else {
isChanged |= ceilingEndSplitPoint.addIntervalEndingAtSplitPoint(interval);
}
if (isChanged) {
consecutiveIntervalData.addInterval(interval);
}
return true;
}
public boolean remove(Interval<Interval_, Point_> interval) {
var startSplitPoint = interval.getStartSplitPoint();
var endSplitPoint = interval.getEndSplitPoint();
var flooredStartSplitPoint = splitPointSet.floor(startSplitPoint);
if (flooredStartSplitPoint == null || !flooredStartSplitPoint.containsIntervalStarting(interval)) {
return false;
}
flooredStartSplitPoint.removeIntervalStartingAtSplitPoint(interval);
if (flooredStartSplitPoint.isEmpty()) {
splitPointSet.remove(flooredStartSplitPoint);
}
var ceilEndSplitPoint = splitPointSet.ceiling(endSplitPoint);
// Not null since the start point contained the interval
ceilEndSplitPoint.removeIntervalEndingAtSplitPoint(interval);
if (ceilEndSplitPoint.isEmpty()) {
splitPointSet.remove(ceilEndSplitPoint);
}
consecutiveIntervalData.removeInterval(interval);
return true;
}
public ConsecutiveIntervalInfoImpl<Interval_, Point_, Difference_> getConsecutiveIntervalData() {
return consecutiveIntervalData;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/experimental/impl/IntervalTreeIterator.java | package ai.timefold.solver.examples.common.experimental.impl;
import java.util.Iterator;
final class IntervalTreeIterator<Interval_, Point_ extends Comparable<Point_>> implements Iterator<Interval_> {
private final Iterator<IntervalSplitPoint<Interval_, Point_>> splitPointSetIterator;
private Iterator<Interval_> splitPointValueIterator;
IntervalTreeIterator(Iterable<IntervalSplitPoint<Interval_, Point_>> splitPointSet) {
this.splitPointSetIterator = splitPointSet.iterator();
if (splitPointSetIterator.hasNext()) {
splitPointValueIterator = splitPointSetIterator.next().getValuesStartingFromSplitPointIterator();
}
}
@Override
public boolean hasNext() {
return splitPointValueIterator != null && splitPointValueIterator.hasNext();
}
@Override
public Interval_ next() {
var next = splitPointValueIterator.next();
while (!splitPointValueIterator.hasNext() && splitPointSetIterator.hasNext()) {
splitPointValueIterator = splitPointSetIterator.next().getValuesStartingFromSplitPointIterator();
}
if (!splitPointValueIterator.hasNext()) {
splitPointValueIterator = null;
}
return next;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence/AbstractJsonSolutionFileIO.java | package ai.timefold.solver.examples.common.persistence;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import ai.timefold.solver.examples.common.persistence.jackson.AbstractKeyDeserializer;
import ai.timefold.solver.jackson.impl.domain.solution.JacksonSolutionFileIO;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
*
* @see AbstractKeyDeserializer
*/
public class AbstractJsonSolutionFileIO<Solution_> extends JacksonSolutionFileIO<Solution_> {
public AbstractJsonSolutionFileIO(Class<Solution_> clazz) {
super(clazz);
}
public AbstractJsonSolutionFileIO(Class<Solution_> clazz, ObjectMapper mapper) {
super(clazz, mapper);
}
protected <Entity_, Id_ extends Number, Value_> void deduplicateEntities(Solution_ solution,
Function<Solution_, Collection<Entity_>> entityCollectionFunction, Function<Entity_, Id_> entityIdFunction,
Function<Entity_, Map<Entity_, Value_>> entityMapGetter,
BiConsumer<Entity_, Map<Entity_, Value_>> entityMapSetter) {
var entityCollection = entityCollectionFunction.apply(solution);
var entitiesById = entityCollection.stream()
.collect(Collectors.toMap(entityIdFunction, Function.identity()));
for (Entity_ entity : entityCollection) {
var originalMap = entityMapGetter.apply(entity);
if (originalMap.isEmpty()) {
continue;
}
var newMap = new LinkedHashMap<Entity_, Value_>(originalMap.size());
originalMap
.forEach((otherEntity, value) -> newMap.put(entitiesById.get(entityIdFunction.apply(otherEntity)), value));
entityMapSetter.accept(entity, newMap);
}
}
protected <Key_, Value_, Index_> Map<Key_, Value_> deduplicateMap(Map<Key_, Value_> originalMap, Map<Index_, Key_> index,
Function<Key_, Index_> idFunction) {
if (originalMap == null || originalMap.isEmpty()) {
return originalMap;
}
Map<Key_, Value_> newMap = new LinkedHashMap<>(originalMap.size());
originalMap.forEach((key, value) -> newMap.put(index.get(idFunction.apply(key)), value));
return newMap;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence/AbstractPngSolutionImporter.java | package ai.timefold.solver.examples.common.persistence;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.examples.common.business.SolutionBusiness;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class AbstractPngSolutionImporter<Solution_> extends AbstractSolutionImporter<Solution_> {
private static final String DEFAULT_INPUT_FILE_SUFFIX = "png";
@Override
public String getInputFileSuffix() {
return DEFAULT_INPUT_FILE_SUFFIX;
}
public abstract PngInputBuilder<Solution_> createPngInputBuilder();
@Override
public Solution_ readSolution(File inputFile) {
try {
BufferedImage image = ImageIO.read(inputFile);
PngInputBuilder<Solution_> pngInputBuilder = createPngInputBuilder();
pngInputBuilder.setInputFile(inputFile);
pngInputBuilder.setImage(image);
try {
Solution_ solution = pngInputBuilder.readSolution();
logger.info("Imported: {}", inputFile);
return solution;
} catch (IllegalArgumentException | IllegalStateException e) {
throw new IllegalArgumentException("Exception in inputFile (" + inputFile + ")", e);
}
} catch (IOException e) {
throw new IllegalArgumentException("Could not read the file (" + inputFile.getName() + ").", e);
}
}
public static abstract class PngInputBuilder<Solution_> extends InputBuilder {
protected File inputFile;
protected BufferedImage image;
public void setInputFile(File inputFile) {
this.inputFile = inputFile;
}
public void setImage(BufferedImage image) {
this.image = image;
}
public abstract Solution_ readSolution() throws IOException;
// ************************************************************************
// Helper methods
// ************************************************************************
public String getInputId() {
return SolutionBusiness.getBaseFileName(inputFile);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence/AbstractSolutionExporter.java | package ai.timefold.solver.examples.common.persistence;
import java.io.File;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.examples.common.app.LoggingMain;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class AbstractSolutionExporter<Solution_> extends LoggingMain {
public abstract String getOutputFileSuffix();
public abstract void writeSolution(Solution_ solution, File outputFile);
public static abstract class OutputBuilder extends LoggingMain {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence/AbstractSolutionImporter.java | package ai.timefold.solver.examples.common.persistence;
import java.io.File;
import java.math.BigDecimal;
import java.math.BigInteger;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.examples.common.app.LoggingMain;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class AbstractSolutionImporter<Solution_> extends LoggingMain {
public boolean acceptInputFile(File inputFile) {
return inputFile.getName().endsWith("." + getInputFileSuffix());
}
public abstract String getInputFileSuffix();
public abstract Solution_ readSolution(File inputFile);
public static abstract class InputBuilder extends LoggingMain {
}
public static BigInteger factorial(int base) {
if (base > 100000) {
// Calculation takes too long
return null;
}
BigInteger value = BigInteger.ONE;
for (int i = 1; i <= base; i++) {
value = value.multiply(BigInteger.valueOf(i));
}
return value;
}
public static String getFlooredPossibleSolutionSize(BigInteger possibleSolutionSize) {
if (possibleSolutionSize == null) {
return null;
}
if (possibleSolutionSize.compareTo(BigInteger.valueOf(1000L)) < 0) {
return possibleSolutionSize.toString();
}
BigDecimal possibleSolutionSizeBigDecimal = new BigDecimal(possibleSolutionSize);
int decimalDigits = possibleSolutionSizeBigDecimal.scale() < 0
? possibleSolutionSizeBigDecimal.precision() - possibleSolutionSizeBigDecimal.scale()
: possibleSolutionSizeBigDecimal.precision();
return "10^" + decimalDigits;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence/AbstractTxtSolutionExporter.java | package ai.timefold.solver.examples.common.persistence;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class AbstractTxtSolutionExporter<Solution_> extends AbstractSolutionExporter<Solution_> {
protected static final String DEFAULT_OUTPUT_FILE_SUFFIX = "txt";
@Override
public String getOutputFileSuffix() {
return DEFAULT_OUTPUT_FILE_SUFFIX;
}
public abstract TxtOutputBuilder<Solution_> createTxtOutputBuilder();
@Override
public void writeSolution(Solution_ solution, File outputFile) {
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"))) {
TxtOutputBuilder<Solution_> txtOutputBuilder = createTxtOutputBuilder();
txtOutputBuilder.setBufferedWriter(writer);
txtOutputBuilder.setSolution(solution);
txtOutputBuilder.writeSolution();
logger.info("Exported: {}", outputFile);
} catch (IOException e) {
throw new IllegalArgumentException("Could not write the file (" + outputFile.getName() + ").", e);
}
}
public static abstract class TxtOutputBuilder<Solution_> extends OutputBuilder {
protected BufferedWriter bufferedWriter;
protected Solution_ solution;
public void setBufferedWriter(BufferedWriter bufferedWriter) {
this.bufferedWriter = bufferedWriter;
}
public void setSolution(Solution_ solution) {
this.solution = solution;
}
public abstract void writeSolution() throws IOException;
// ************************************************************************
// Helper methods
// ************************************************************************
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence/AbstractTxtSolutionImporter.java | package ai.timefold.solver.examples.common.persistence;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.examples.common.business.SolutionBusiness;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class AbstractTxtSolutionImporter<Solution_> extends AbstractSolutionImporter<Solution_> {
private static final String DEFAULT_INPUT_FILE_SUFFIX = "txt";
@Override
public String getInputFileSuffix() {
return DEFAULT_INPUT_FILE_SUFFIX;
}
public abstract TxtInputBuilder<Solution_> createTxtInputBuilder();
@Override
public Solution_ readSolution(File inputFile) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8"))) {
TxtInputBuilder<Solution_> txtInputBuilder = createTxtInputBuilder();
txtInputBuilder.setInputFile(inputFile);
txtInputBuilder.setBufferedReader(reader);
try {
Solution_ solution = txtInputBuilder.readSolution();
logger.info("Imported: {}", inputFile);
return solution;
} catch (IllegalArgumentException | IllegalStateException e) {
throw new IllegalArgumentException("Exception in inputFile (" + inputFile + ")", e);
}
} catch (IOException e) {
throw new IllegalArgumentException("Could not read the file (" + inputFile.getName() + ").", e);
}
}
public Solution_ readSolution(URL inputURL) {
try (BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputURL.openStream(), "UTF-8"))) {
TxtInputBuilder<Solution_> txtInputBuilder = createTxtInputBuilder();
txtInputBuilder.setInputFile(new File(inputURL.getFile()));
txtInputBuilder.setBufferedReader(bufferedReader);
try {
return txtInputBuilder.readSolution();
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Exception in inputURL (" + inputURL + ")", e);
} catch (IllegalStateException e) {
throw new IllegalStateException("Exception in inputURL (" + inputURL + ")", e);
}
} catch (IOException e) {
throw new IllegalArgumentException("Could not read the inputURL (" + inputURL + ").", e);
}
}
public static abstract class TxtInputBuilder<Solution_> extends InputBuilder {
protected File inputFile;
protected BufferedReader bufferedReader;
public void setInputFile(File inputFile) {
this.inputFile = inputFile;
}
public void setBufferedReader(BufferedReader bufferedReader) {
this.bufferedReader = bufferedReader;
}
public abstract Solution_ readSolution() throws IOException;
// ************************************************************************
// Helper methods
// ************************************************************************
public String getInputId() {
return SolutionBusiness.getBaseFileName(inputFile);
}
// ************************************************************************
// Read methods
// ************************************************************************
public void readEmptyLine() throws IOException {
readConstantLine("");
}
public void readConstantLine(String constantRegex) throws IOException {
readConstantLine(bufferedReader, constantRegex);
}
public void readConstantLine(BufferedReader subBufferedReader, String constantRegex) throws IOException {
String line = subBufferedReader.readLine();
if (line == null) {
throw new IllegalArgumentException("File ends before a line is expected to be a constant regex ("
+ constantRegex + ").");
}
String value = line.trim();
if (!value.matches(constantRegex)) {
throw new IllegalArgumentException("Read line (" + line + ") is expected to be a constant regex ("
+ constantRegex + ").");
}
}
public boolean readOptionalConstantLine(String constantRegex) throws IOException {
bufferedReader.mark(1024);
boolean valid = true;
String line = bufferedReader.readLine();
if (line == null) {
valid = false;
} else {
String value = line.trim();
if (!value.matches(constantRegex)) {
valid = false;
}
}
if (!valid) {
bufferedReader.reset();
}
return valid;
}
public void skipOptionalConstantLines(String constantRegex) throws IOException {
boolean valid = true;
while (valid) {
valid = readOptionalConstantLine(constantRegex);
}
}
public void readUntilConstantLine(String constantRegex) throws IOException {
String line;
String value;
do {
line = bufferedReader.readLine();
if (line == null) {
throw new IllegalArgumentException("File ends before a line is expected to be a constant regex ("
+ constantRegex + ").");
}
value = line.trim();
} while (!value.matches(constantRegex));
}
public int readIntegerValue() throws IOException {
return readIntegerValue("");
}
public int readIntegerValue(String prefixRegex) throws IOException {
return readIntegerValue(prefixRegex, "");
}
public int readIntegerValue(String prefixRegex, String suffixRegex) throws IOException {
String line = bufferedReader.readLine();
if (line == null) {
throw new IllegalArgumentException("File ends before a line is expected to contain an integer value ("
+ prefixRegex + "<value>" + suffixRegex + ").");
}
String value = removePrefixSuffixFromLine(line, prefixRegex, suffixRegex);
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Read line (" + line + ") is expected to contain an integer value ("
+ value + ").", e);
}
}
public long readLongValue() throws IOException {
return readLongValue("");
}
public long readLongValue(String prefixRegex) throws IOException {
return readLongValue(prefixRegex, "");
}
public long readLongValue(String prefixRegex, String suffixRegex) throws IOException {
String line = bufferedReader.readLine();
if (line == null) {
throw new IllegalArgumentException("File ends before a line is expected to contain an integer value ("
+ prefixRegex + "<value>" + suffixRegex + ").");
}
String value = removePrefixSuffixFromLine(line, prefixRegex, suffixRegex);
try {
return Long.parseLong(value);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Read line (" + line + ") is expected to contain an integer value ("
+ value + ").", e);
}
}
public String readStringValue() throws IOException {
return readStringValue("");
}
public String readStringValue(String prefixRegex) throws IOException {
return readStringValue(prefixRegex, "");
}
public String readStringValue(String prefixRegex, String suffixRegex) throws IOException {
String line = bufferedReader.readLine();
if (line == null) {
throw new IllegalArgumentException("File ends before a line is expected to contain an string value ("
+ prefixRegex + "<value>" + suffixRegex + ").");
}
return removePrefixSuffixFromLine(line, prefixRegex, suffixRegex);
}
public String readOptionalStringValue(String defaultValue) throws IOException {
return readOptionalStringValue("", defaultValue);
}
public String readOptionalStringValue(String prefixRegex, String defaultValue) throws IOException {
return readOptionalStringValue(prefixRegex, "", defaultValue);
}
public String readOptionalStringValue(String prefixRegex, String suffixRegex, String defaultValue) throws IOException {
bufferedReader.mark(1024);
boolean valid = true;
String value = bufferedReader.readLine();
if (value == null) {
valid = false;
} else {
value = value.trim();
if (value.matches("^" + prefixRegex + ".*")) {
value = value.replaceAll("^" + prefixRegex + "(.*)", "$1");
} else {
valid = false;
}
if (value.matches(".*" + suffixRegex + "$")) {
value = value.replaceAll("(.*)" + suffixRegex + "$", "$1");
} else {
valid = false;
}
}
if (!valid) {
bufferedReader.reset();
return defaultValue;
}
value = value.trim();
return value;
}
public String removePrefixSuffixFromLine(String line, String prefixRegex, String suffixRegex) {
String value = line.trim();
if (!value.matches("^" + prefixRegex + ".*")) {
throw new IllegalArgumentException("Read line (" + line + ") is expected to start with prefixRegex ("
+ prefixRegex + ").");
}
value = value.replaceAll("^" + prefixRegex + "(.*)", "$1");
if (!value.matches(".*" + suffixRegex + "$")) {
throw new IllegalArgumentException("Read line (" + line + ") is expected to end with suffixRegex ("
+ suffixRegex + ").");
}
value = value.replaceAll("(.*)" + suffixRegex + "$", "$1");
value = value.trim();
return value;
}
// ************************************************************************
// Split methods
// ************************************************************************
public String[] splitBySpace(String line) {
return splitBySpace(line, null);
}
public String[] splitBySpace(String line, Integer numberOfTokens) {
return splitBy(line, "\\ ", "a space ( )", numberOfTokens, false, false);
}
public String[] splitBySpace(String line, Integer minimumNumberOfTokens, Integer maximumNumberOfTokens) {
return splitBy(line, "\\ ", "a space ( )", minimumNumberOfTokens, maximumNumberOfTokens, false, false);
}
public String[] splitBySpace(String line, Integer minimumNumberOfTokens, Integer maximumNumberOfTokens,
boolean trim, boolean removeQuotes) {
return splitBy(line, "\\ ", "a space ( )", minimumNumberOfTokens, maximumNumberOfTokens, trim, removeQuotes);
}
public String[] splitBySpacesOrTabs(String line) {
return splitBySpacesOrTabs(line, null);
}
public String[] splitBySpacesOrTabs(String line, Integer numberOfTokens) {
return splitBy(line, "[\\ \\t]+", "spaces or tabs", numberOfTokens, false, false);
}
public String[] splitBySpacesOrTabs(String line, Integer minimumNumberOfTokens, Integer maximumNumberOfTokens) {
return splitBy(line, "[\\ \\t]+", "spaces or tabs", minimumNumberOfTokens, maximumNumberOfTokens,
false, false);
}
public String[] splitByPipelineAndTrim(String line, int numberOfTokens) {
return splitBy(line, "\\|", "a pipeline (|)", numberOfTokens, true, false);
}
public String[] splitBySemicolonSeparatedValue(String line) {
return splitBy(line, ";", "a semicolon (;)", null, false, true);
}
public String[] splitBySemicolonSeparatedValue(String line, int numberOfTokens) {
return splitBy(line, ";", "a semicolon (;)", numberOfTokens, false, true);
}
public String[] splitByCommaAndTrim(String line, int numberOfTokens) {
return splitBy(line, "\\,", "a comma (,)", numberOfTokens, true, false);
}
public String[] splitByCommaAndTrim(String line, Integer minimumNumberOfTokens, Integer maximumNumberOfTokens) {
return splitBy(line, "\\,", "a comma (,)", minimumNumberOfTokens, maximumNumberOfTokens, true, false);
}
public String[] splitBy(String line, String delimiterRegex, String delimiterName,
Integer numberOfTokens, boolean trim, boolean removeQuotes) {
return splitBy(line, delimiterRegex, delimiterName, numberOfTokens, numberOfTokens, trim, removeQuotes);
}
public String[] splitBy(String line, String delimiterRegex, String delimiterName,
Integer minimumNumberOfTokens, Integer maximumNumberOfTokens, boolean trim, boolean removeQuotes) {
String[] lineTokens = line.split(delimiterRegex);
if (removeQuotes) {
List<String> lineTokenList = new ArrayList<>(lineTokens.length);
for (int i = 0; i < lineTokens.length; i++) {
String token = lineTokens[i];
while ((trim ? token.trim() : token).startsWith("\"") && !(trim ? token.trim() : token).endsWith("\"")) {
i++;
if (i >= lineTokens.length) {
throw new IllegalArgumentException("The line (" + line
+ ") has an invalid use of quotes (\").");
}
String delimiter;
switch (delimiterRegex) {
case "\\ ":
delimiter = " ";
break;
case "\\,":
delimiter = ",";
break;
default:
throw new IllegalArgumentException("Not supported delimiterRegex (" + delimiterRegex + ")");
}
token += delimiter + lineTokens[i];
}
if (trim) {
token = token.trim();
}
if (token.startsWith("\"") && token.endsWith("\"")) {
token = token.substring(1, token.length() - 1);
token = token.replaceAll("\"\"", "\"");
}
lineTokenList.add(token);
}
// Empty token == somewhere in there was an extra empty space
lineTokens = lineTokenList
.stream()
.filter(token -> !token.isEmpty())
.toArray(String[]::new);
}
if (minimumNumberOfTokens != null && lineTokens.length < minimumNumberOfTokens) {
throw new IllegalArgumentException("Read line (" + line + ") has " + lineTokens.length
+ " tokens but is expected to contain at least " + minimumNumberOfTokens
+ " tokens separated by " + delimiterName + ".");
}
if (maximumNumberOfTokens != null && lineTokens.length > maximumNumberOfTokens) {
throw new IllegalArgumentException("Read line (" + line + ") has " + lineTokens.length
+ " tokens but is expected to contain at most " + maximumNumberOfTokens
+ " tokens separated by " + delimiterName + ".");
}
if (trim) {
for (int i = 0; i < lineTokens.length; i++) {
lineTokens[i] = lineTokens[i].trim();
}
}
return lineTokens;
}
public boolean parseBooleanFromNumber(String token) {
switch (token) {
case "0":
return false;
case "1":
return true;
default:
throw new IllegalArgumentException("The token (" + token
+ ") is expected to be 0 or 1 representing a boolean.");
}
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence/AbstractXlsxSolutionFileIO.java | package ai.timefold.solver.examples.common.persistence;
import static ai.timefold.solver.examples.common.persistence.XSSFColorUtil.getXSSFColor;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.ScoreExplanation;
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.SolverFactory;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirectorFactory;
import ai.timefold.solver.core.impl.score.director.ScoreDirectorFactory;
import ai.timefold.solver.core.impl.solver.DefaultSolverFactory;
import ai.timefold.solver.persistence.common.api.domain.solution.SolutionFileIO;
import ai.timefold.solver.swing.impl.TangoColorFactory;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public abstract class AbstractXlsxSolutionFileIO<Solution_> implements SolutionFileIO<Solution_> {
public static final DateTimeFormatter DAY_FORMATTER = DateTimeFormatter.ofPattern("E yyyy-MM-dd", Locale.ENGLISH);
public static final DateTimeFormatter MONTH_FORMATTER = DateTimeFormatter.ofPattern("MMM yyyy", Locale.ENGLISH);
public static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm", Locale.ENGLISH);
public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm", Locale.ENGLISH);
protected static final Pattern VALID_TAG_PATTERN = Pattern
.compile("(?U)^[\\w&\\-\\.\\/\\(\\)\\'][\\w&\\-\\.\\/\\(\\)\\' ]*[\\w&\\-\\.\\/\\(\\)\\']?$");
protected static final Pattern VALID_NAME_PATTERN = AbstractXlsxSolutionFileIO.VALID_TAG_PATTERN;
protected static final Pattern VALID_CODE_PATTERN = Pattern.compile("(?U)^[\\w\\-\\.\\/\\(\\)]+$");
protected static final XSSFColor VIEW_TAB_COLOR = getXSSFColor(TangoColorFactory.BUTTER_1);
protected static final XSSFColor DISABLED_COLOR = getXSSFColor(TangoColorFactory.ALUMINIUM_3);
protected static final XSSFColor UNAVAILABLE_COLOR = getXSSFColor(TangoColorFactory.ALUMINIUM_5);
protected static final XSSFColor PINNED_COLOR = getXSSFColor(TangoColorFactory.PLUM_1);
protected static final XSSFColor HARD_PENALTY_COLOR = getXSSFColor(TangoColorFactory.SCARLET_1);
protected static final XSSFColor MEDIUM_PENALTY_COLOR = getXSSFColor(TangoColorFactory.SCARLET_3);
protected static final XSSFColor SOFT_PENALTY_COLOR = getXSSFColor(TangoColorFactory.ORANGE_1);
protected static final XSSFColor PLANNING_VARIABLE_COLOR = getXSSFColor(TangoColorFactory.BUTTER_1);
protected static final XSSFColor REPUBLISHED_COLOR = getXSSFColor(TangoColorFactory.MAGENTA);
@Override
public String getInputFileExtension() {
return "xlsx";
}
public static abstract class AbstractXlsxReader<Solution_, Score_ extends Score<Score_>> {
protected final XSSFWorkbook workbook;
protected final ScoreDefinition<Score_> scoreDefinition;
protected Solution_ solution;
protected XSSFSheet currentSheet;
protected Iterator<Row> currentRowIterator;
protected XSSFRow currentRow;
protected int currentRowNumber;
protected int currentColumnNumber;
public AbstractXlsxReader(XSSFWorkbook workbook, String solverConfigResource) {
this.workbook = workbook;
SolverFactory<Solution_> solverFactory = SolverFactory.createFromXmlResource(solverConfigResource);
ScoreDirectorFactory<Solution_> scoreDirectorFactory =
((DefaultSolverFactory<Solution_>) solverFactory).getScoreDirectorFactory();
scoreDefinition = ((InnerScoreDirectorFactory<Solution_, Score_>) scoreDirectorFactory).getScoreDefinition();
}
public abstract Solution_ read();
protected void readIntConstraintParameterLine(String name, Consumer<Integer> consumer, String constraintDescription) {
nextRow();
readHeaderCell(name);
XSSFCell weightCell = nextCell();
if (consumer != null) {
if (weightCell.getCellType() != CellType.NUMERIC) {
throw new IllegalArgumentException(currentPosition() + ": The value ("
+ weightCell.getStringCellValue()
+ ") for constraint (" + name + ") must be a number and the cell type must be numeric.");
}
double value = weightCell.getNumericCellValue();
if (((int) value) != value) {
throw new IllegalArgumentException(currentPosition() + ": The value (" + value
+ ") for constraint (" + name + ") must be an integer.");
}
consumer.accept((int) value);
} else {
if (weightCell.getCellType() == CellType.NUMERIC
|| !weightCell.getStringCellValue().equals("n/a")) {
throw new IllegalArgumentException(currentPosition() + ": The value ("
+ weightCell.getStringCellValue()
+ ") for constraint (" + name + ") must be an n/a.");
}
}
readHeaderCell(constraintDescription);
}
protected void readLongConstraintParameterLine(String name, Consumer<Long> consumer, String constraintDescription) {
nextRow();
readHeaderCell(name);
XSSFCell weightCell = nextCell();
if (consumer != null) {
if (weightCell.getCellType() != CellType.NUMERIC) {
throw new IllegalArgumentException(currentPosition() + ": The value ("
+ weightCell.getStringCellValue()
+ ") for constraint (" + name + ") must be a number and the cell type must be numeric.");
}
double value = weightCell.getNumericCellValue();
if (((long) value) != value) {
throw new IllegalArgumentException(currentPosition() + ": The value (" + value
+ ") for constraint (" + name + ") must be a (long) integer.");
}
consumer.accept((long) value);
} else {
if (weightCell.getCellType() == CellType.NUMERIC
|| !weightCell.getStringCellValue().equals("n/a")) {
throw new IllegalArgumentException(currentPosition() + ": The value ("
+ weightCell.getStringCellValue()
+ ") for constraint (" + name + ") must be an n/a.");
}
}
readHeaderCell(constraintDescription);
}
protected void readScoreConstraintHeaders() {
nextRow(true);
readHeaderCell("Constraint");
readHeaderCell("Score weight");
readHeaderCell("Description");
}
protected Score_ readScoreConstraintLine(String constraintName, String constraintDescription) {
nextRow();
readHeaderCell(constraintName);
String scoreString = nextStringCell().getStringCellValue();
readHeaderCell(constraintDescription);
return scoreDefinition.parseScore(scoreString);
}
protected String currentPosition() {
return "Sheet (" + currentSheet.getSheetName() + ") cell ("
+ (currentRowNumber + 1) + CellReference.convertNumToColString(currentColumnNumber) + ")";
}
protected boolean hasSheet(String sheetName) {
return workbook.getSheet(sheetName) != null;
}
protected void nextSheet(String sheetName) {
currentSheet = workbook.getSheet(sheetName);
if (currentSheet == null) {
throw new IllegalStateException("The workbook does not contain a sheet with name ("
+ sheetName + ").");
}
currentRowIterator = currentSheet.rowIterator();
if (currentRowIterator == null) {
throw new IllegalStateException(currentPosition() + ": The sheet has no rows.");
}
currentRowNumber = -1;
}
protected boolean nextRow() {
return nextRow(true);
}
protected boolean nextRow(boolean skipEmptyRows) {
currentRowNumber++;
currentColumnNumber = -1;
if (!currentRowIterator.hasNext()) {
currentRow = null;
return false;
}
currentRow = (XSSFRow) currentRowIterator.next();
while (skipEmptyRows && currentRowIsEmpty()) {
if (!currentRowIterator.hasNext()) {
currentRow = null;
return false;
}
currentRow = (XSSFRow) currentRowIterator.next();
}
if (currentRow.getRowNum() != currentRowNumber) {
if (currentRow.getRowNum() == currentRowNumber + 1) {
currentRowNumber++;
} else {
throw new IllegalStateException(currentPosition() + ": The next row (" + currentRow.getRowNum()
+ ") has a gap of more than 1 empty line with the previous.");
}
}
return true;
}
protected boolean currentRowIsEmpty() {
if (currentRow.getPhysicalNumberOfCells() == 0) {
return true;
}
for (Cell cell : currentRow) {
if (cell.getCellType() == CellType.STRING) {
if (!cell.getStringCellValue().isEmpty()) {
return false;
}
} else if (cell.getCellType() != CellType.BLANK) {
return false;
}
}
return true;
}
protected void readHeaderCell(String value) {
XSSFCell cell = currentRow == null ? null : nextStringCell();
if (cell == null || !cell.getStringCellValue().equals(value)) {
throw new IllegalStateException(currentPosition() + ": The cell ("
+ (cell == null ? null : cell.getStringCellValue())
+ ") does not contain the expected value (" + value + ").");
}
}
protected void readHeaderCell(double value) {
XSSFCell cell = currentRow == null ? null : nextNumericCell();
if (cell == null || cell.getNumericCellValue() != value) {
throw new IllegalStateException(currentPosition() + ": The cell does not contain the expected value ("
+ value + ").");
}
}
protected XSSFCell nextStringCell() {
XSSFCell cell = nextCell();
if (cell.getCellType() == CellType.NUMERIC) {
throw new IllegalStateException(currentPosition() + ": The cell with value ("
+ cell.getNumericCellValue() + ") has a numeric type but should be a string.");
}
return cell;
}
protected XSSFCell nextNumericCell() {
XSSFCell cell = nextCell();
if (cell.getCellType() == CellType.STRING) {
throw new IllegalStateException(currentPosition() + ": The cell with value ("
+ cell.getStringCellValue() + ") has a string type but should be numeric.");
}
return cell;
}
protected XSSFCell nextNumericCellOrBlank() {
XSSFCell cell = nextCell();
if (cell.getCellType() == CellType.BLANK
|| (cell.getCellType() == CellType.STRING && cell.getStringCellValue().isEmpty())) {
return null;
}
if (cell.getCellType() == CellType.STRING) {
throw new IllegalStateException(currentPosition() + ": The cell with value ("
+ cell.getStringCellValue() + ") has a string type but should be numeric.");
}
return cell;
}
protected XSSFCell nextBooleanCell() {
XSSFCell cell = nextCell();
if (cell.getCellType() == CellType.STRING) {
throw new IllegalStateException(currentPosition() + ": The cell with value ("
+ cell.getStringCellValue() + ") has a string type but should be boolean.");
}
if (cell.getCellType() == CellType.NUMERIC) {
throw new IllegalStateException(currentPosition() + ": The cell with value ("
+ cell.getNumericCellValue() + ") has a numeric type but should be a boolean.");
}
return cell;
}
protected XSSFCell nextCell() {
currentColumnNumber++;
XSSFCell cell = currentRow.getCell(currentColumnNumber);
// TODO HACK to workaround the fact that LibreOffice and Excel automatically remove empty trailing cells
if (cell == null) {
// Return dummy cell
return currentRow.createCell(currentColumnNumber);
}
return cell;
}
protected XSSFColor extractColor(XSSFCell cell, XSSFColor... acceptableColors) {
XSSFCellStyle cellStyle = cell.getCellStyle();
FillPatternType fillPattern = cellStyle.getFillPattern();
if (fillPattern == null || fillPattern == FillPatternType.NO_FILL) {
return null;
}
if (fillPattern != FillPatternType.SOLID_FOREGROUND) {
throw new IllegalStateException(currentPosition() + ": The fill pattern (" + fillPattern
+ ") should be either " + FillPatternType.NO_FILL
+ " or " + FillPatternType.SOLID_FOREGROUND + ".");
}
XSSFColor color = cellStyle.getFillForegroundColorColor();
for (XSSFColor acceptableColor : acceptableColors) {
if (acceptableColor.equals(color)) {
return acceptableColor;
}
}
throw new IllegalStateException(currentPosition() + ": The fill color (" + color
+ ") is not one of the acceptableColors (" + Arrays.toString(acceptableColors) + ").");
}
}
public static abstract class AbstractXlsxWriter<Solution_, Score_ extends Score<Score_>> {
protected final Solution_ solution;
protected final Score_ score;
protected final Map<String, ConstraintMatchTotal<Score_>> constraintMatchTotalsMap;
protected final Map<Object, Indictment<Score_>> indictmentMap;
protected XSSFWorkbook workbook;
protected CreationHelper creationHelper;
protected XSSFCellStyle headerStyle;
protected XSSFCellStyle defaultStyle;
protected XSSFCellStyle scoreStyle;
protected XSSFCellStyle disabledScoreStyle;
protected XSSFCellStyle unavailableStyle;
protected XSSFCellStyle pinnedStyle;
protected XSSFCellStyle hardPenaltyStyle;
protected XSSFCellStyle mediumPenaltyStyle;
protected XSSFCellStyle softPenaltyStyle;
protected XSSFCellStyle wrappedStyle;
protected XSSFCellStyle planningVariableStyle;
protected XSSFCellStyle republishedStyle;
protected XSSFSheet currentSheet;
protected Drawing currentDrawing;
protected XSSFRow currentRow;
protected int currentRowNumber;
protected int currentColumnNumber;
protected int headerCellCount;
public AbstractXlsxWriter(Solution_ solution, String solverConfigResource) {
this.solution = solution;
SolverFactory<Solution_> solverFactory = SolverFactory.createFromXmlResource(solverConfigResource);
SolutionManager<Solution_, Score_> solutionManager = SolutionManager.create(solverFactory);
ScoreExplanation<Solution_, Score_> scoreExplanation = solutionManager.explain(solution);
score = scoreExplanation.getScore();
constraintMatchTotalsMap = scoreExplanation.getConstraintMatchTotalMap();
indictmentMap = scoreExplanation.getIndictmentMap();
}
public abstract Workbook write();
public void writeSetup() {
workbook = new XSSFWorkbook();
creationHelper = workbook.getCreationHelper();
createStyles();
}
protected void createStyles() {
headerStyle = createStyle(null);
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerStyle.setFont(headerFont);
defaultStyle = createStyle(null);
scoreStyle = createStyle(null);
scoreStyle.setAlignment(HorizontalAlignment.RIGHT);
disabledScoreStyle = createStyle(DISABLED_COLOR);
disabledScoreStyle.setAlignment(HorizontalAlignment.RIGHT);
unavailableStyle = createStyle(UNAVAILABLE_COLOR);
pinnedStyle = createStyle(PINNED_COLOR);
hardPenaltyStyle = createStyle(HARD_PENALTY_COLOR);
mediumPenaltyStyle = createStyle(MEDIUM_PENALTY_COLOR);
softPenaltyStyle = createStyle(SOFT_PENALTY_COLOR);
wrappedStyle = createStyle(null);
planningVariableStyle = createStyle(PLANNING_VARIABLE_COLOR);
republishedStyle = createStyle(REPUBLISHED_COLOR);
}
protected XSSFCellStyle createStyle(XSSFColor color) {
XSSFCellStyle style = workbook.createCellStyle();
if (color != null) {
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillForegroundColor(color);
}
style.setWrapText(true);
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
protected void writeIntConstraintParameterLine(String name, int value, String constraintDescription) {
nextRow();
nextHeaderCell(name);
XSSFCell weightCell = nextCell();
weightCell.setCellValue(value);
nextHeaderCell(constraintDescription);
}
protected void writeIntConstraintParameterLine(String name, Supplier<Integer> supplier, String constraintDescription) {
nextRow();
nextHeaderCell(name);
XSSFCell weightCell = nextCell();
if (supplier != null) {
weightCell.setCellValue(supplier.get());
} else {
weightCell.setCellValue("n/a");
}
nextHeaderCell(constraintDescription);
}
protected void writeLongConstraintParameterLine(String name, Supplier<Long> supplier, String constraintDescription) {
nextRow();
nextHeaderCell(name);
XSSFCell weightCell = nextCell();
if (supplier != null) {
weightCell.setCellValue(supplier.get());
} else {
weightCell.setCellValue("n/a");
}
nextHeaderCell(constraintDescription);
}
protected void writeScoreConstraintHeaders() {
nextRow();
nextHeaderCell("Constraint");
nextHeaderCell("Score weight");
nextHeaderCell("Description");
}
protected void writeScoreConstraintLine(String constraintName, Score_ constraintScore,
String constraintDescription) {
nextRow();
nextHeaderCell(constraintName);
nextCell(constraintScore.isZero() ? disabledScoreStyle : scoreStyle)
.setCellValue(constraintScore.toString());
nextHeaderCell(constraintDescription);
}
protected void writeScoreView(Function<Collection<?>, String> indictmentListFormatter) {
nextSheet("Score view", 1, 3, true);
nextRow();
nextHeaderCell("Score");
nextCell().setCellValue(score.toShortString());
nextRow();
nextRow();
nextHeaderCell("Constraint name");
nextHeaderCell("Constraint weight");
nextHeaderCell("Match count");
nextHeaderCell("Score");
nextHeaderCell("");
nextHeaderCell("Match score");
nextHeaderCell("Justifications");
if (!score.isSolutionInitialized()) {
nextRow();
nextHeaderCell("Unassigned variables");
nextCell();
nextCell();
nextCell().setCellValue(score.initScore());
}
Comparator<ConstraintMatchTotal<Score_>> constraintWeightComparator = Comparator.comparing(
ConstraintMatchTotal::getConstraintWeight, Comparator.nullsLast(Comparator.reverseOrder()));
constraintMatchTotalsMap.values().stream()
.sorted(constraintWeightComparator
.thenComparing(ConstraintMatchTotal::getConstraintRef))
.forEach(constraintMatchTotal -> {
nextRow();
nextHeaderCell(constraintMatchTotal.getConstraintRef().constraintName());
Score_ constraintWeight = constraintMatchTotal.getConstraintWeight();
nextCell(scoreStyle).setCellValue(constraintWeight == null ? "N/A" : constraintWeight.toShortString());
nextCell().setCellValue(constraintMatchTotal.getConstraintMatchSet().size());
nextCell(scoreStyle).setCellValue(constraintMatchTotal.getScore().toShortString());
});
nextRow();
nextRow();
Comparator<ConstraintMatchTotal<Score_>> constraintMatchTotalComparator = Comparator
.comparing(ConstraintMatchTotal::getScore);
constraintMatchTotalComparator = constraintMatchTotalComparator
.thenComparing(ConstraintMatchTotal::getConstraintRef);
Comparator<ConstraintMatch<Score_>> constraintMatchComparator = Comparator
.comparing(ConstraintMatch::getScore);
constraintMatchTotalsMap.values().stream()
.sorted(constraintMatchTotalComparator)
.forEach(constraintMatchTotal -> {
nextRow();
nextHeaderCell(constraintMatchTotal.getConstraintRef().constraintName());
Score_ constraintWeight = constraintMatchTotal.getConstraintWeight();
nextCell(scoreStyle).setCellValue(constraintWeight == null ? "N/A" : constraintWeight.toShortString());
nextCell().setCellValue(constraintMatchTotal.getConstraintMatchSet().size());
nextCell(scoreStyle).setCellValue(constraintMatchTotal.getScore().toShortString());
constraintMatchTotal.getConstraintMatchSet().stream()
.sorted(constraintMatchComparator)
.forEach(constraintMatch -> {
nextRow();
nextCell();
nextCell();
nextCell();
nextCell();
nextCell();
nextCell(scoreStyle).setCellValue(constraintMatch.getScore().toShortString());
nextCell().setCellValue(
indictmentListFormatter.apply(constraintMatch.getIndictedObjectList()));
});
});
autoSizeColumnsWithHeader();
}
protected void nextSheet(String sheetName, int colSplit, int rowSplit, boolean view) {
currentSheet = workbook.createSheet(sheetName);
currentDrawing = currentSheet.createDrawingPatriarch();
currentSheet.createFreezePane(colSplit, rowSplit);
currentRowNumber = -1;
headerCellCount = 0;
if (view) {
currentSheet.setTabColor(VIEW_TAB_COLOR);
}
}
protected void nextRow() {
currentRowNumber++;
currentRow = currentSheet.createRow(currentRowNumber);
currentColumnNumber = -1;
}
protected void nextHeaderCell(String value) {
nextCell(headerStyle).setCellValue(value);
headerCellCount++;
}
protected void nextHeaderCell(double value) {
nextCell(headerStyle).setCellValue(value);
headerCellCount++;
}
protected XSSFCell nextCell() {
return nextCell(defaultStyle);
}
protected XSSFCell nextCell(XSSFCellStyle cellStyle) {
currentColumnNumber++;
XSSFCell cell = currentRow.createCell(currentColumnNumber);
cell.setCellStyle(cellStyle);
return cell;
}
protected void nextHeaderCellVertically(String value) {
nextCellVertically(headerStyle).setCellValue(value);
headerCellCount++;
}
protected XSSFCell nextCellVertically() {
return nextCellVertically(defaultStyle);
}
protected XSSFCell nextCellVertically(XSSFCellStyle cellStyle) {
currentRowNumber++;
currentRow = currentSheet.getRow(currentRowNumber);
XSSFCell cell = currentRow.createCell(currentColumnNumber);
cell.setCellStyle(cellStyle);
return cell;
}
protected void autoSizeColumnsWithHeader() {
for (int i = 0; i < headerCellCount; i++) {
currentSheet.autoSizeColumn(i);
}
}
protected void setSizeColumnsWithHeader(int width) {
for (int i = 0; i < headerCellCount; i++) {
currentSheet.setColumnWidth(i, width);
}
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence/AbstractXmlSolutionExporter.java | package ai.timefold.solver.examples.common.persistence;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class AbstractXmlSolutionExporter<Solution_> extends AbstractSolutionExporter<Solution_> {
protected static final String DEFAULT_OUTPUT_FILE_SUFFIX = "xml";
@Override
public String getOutputFileSuffix() {
return DEFAULT_OUTPUT_FILE_SUFFIX;
}
public abstract XmlOutputBuilder<Solution_> createXmlOutputBuilder();
@Override
public void writeSolution(Solution_ solution, File outputFile) {
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile))) {
Document document = new Document();
XmlOutputBuilder<Solution_> xmlOutputBuilder = createXmlOutputBuilder();
xmlOutputBuilder.setDocument(document);
xmlOutputBuilder.setSolution(solution);
xmlOutputBuilder.writeSolution();
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(document, out);
logger.info("Exported: {}", outputFile);
} catch (IOException e) {
throw new IllegalArgumentException("Could not write the file (" + outputFile.getName() + ").", e);
} catch (JDOMException e) {
throw new IllegalArgumentException("Could not format the XML file (" + outputFile.getName() + ").", e);
}
}
public static abstract class XmlOutputBuilder<Solution_> extends OutputBuilder {
protected Document document;
public void setDocument(Document document) {
this.document = document;
}
public abstract void setSolution(Solution_ solution);
public abstract void writeSolution() throws IOException, JDOMException;
// ************************************************************************
// Helper methods
// ************************************************************************
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence/AbstractXmlSolutionImporter.java | package ai.timefold.solver.examples.common.persistence;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.XMLConstants;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.examples.common.business.SolutionBusiness;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.input.sax.XMLReaders;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class AbstractXmlSolutionImporter<Solution_> extends AbstractSolutionImporter<Solution_> {
private static final String DEFAULT_INPUT_FILE_SUFFIX = "xml";
@Override
public String getInputFileSuffix() {
return DEFAULT_INPUT_FILE_SUFFIX;
}
public abstract XmlInputBuilder<Solution_> createXmlInputBuilder();
@Override
public Solution_ readSolution(File inputFile) {
try (InputStream in = new BufferedInputStream(new FileInputStream(inputFile))) {
// CVE-2021-33813
SAXBuilder builder = new SAXBuilder(XMLReaders.NONVALIDATING);
builder.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
builder.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
builder.setExpandEntities(false);
Document document = builder.build(in);
XmlInputBuilder<Solution_> xmlInputBuilder = createXmlInputBuilder();
xmlInputBuilder.setInputFile(inputFile);
xmlInputBuilder.setDocument(document);
try {
Solution_ solution = xmlInputBuilder.readSolution();
logger.info("Imported: {}", inputFile);
return solution;
} catch (IllegalArgumentException | IllegalStateException e) {
throw new IllegalArgumentException("Exception in inputFile (" + inputFile + ")", e);
}
} catch (IOException e) {
throw new IllegalArgumentException("Could not read the file (" + inputFile.getName() + ").", e);
} catch (JDOMException e) {
throw new IllegalArgumentException("Could not parse the XML file (" + inputFile.getName() + ").", e);
}
}
public static abstract class XmlInputBuilder<Solution_> extends InputBuilder {
protected File inputFile;
protected Document document;
public void setInputFile(File inputFile) {
this.inputFile = inputFile;
}
public void setDocument(Document document) {
this.document = document;
}
public abstract Solution_ readSolution() throws IOException, JDOMException;
// ************************************************************************
// Helper methods
// ************************************************************************
public String getInputId() {
return SolutionBusiness.getBaseFileName(inputFile);
}
protected void assertElementName(Element element, String name) {
if (!element.getName().equals(name)) {
throw new IllegalStateException("Element name (" + element.getName()
+ ") should be " + name + ".");
}
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence/SolutionConverter.java |
package ai.timefold.solver.examples.common.persistence;
import java.io.File;
import java.util.Arrays;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.examples.common.app.CommonApp;
import ai.timefold.solver.examples.common.app.LoggingMain;
import ai.timefold.solver.examples.common.business.ProblemFileComparator;
import ai.timefold.solver.persistence.common.api.domain.solution.SolutionFileIO;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class SolutionConverter<Solution_> extends LoggingMain {
public static <Solution_> SolutionConverter<Solution_> createImportConverter(String dataDirName,
AbstractSolutionImporter<Solution_> importer, SolutionFileIO<Solution_> outputSolutionFileIO) {
SolutionFileIO<Solution_> inputSolutionFileIO = new SolutionFileIO<>() {
@Override
public String getInputFileExtension() {
return importer.getInputFileSuffix();
}
@Override
public Solution_ read(File inputSolutionFile) {
return importer.readSolution(inputSolutionFile);
}
@Override
public void write(Solution_ solution_, File outputSolutionFile) {
throw new UnsupportedOperationException();
}
};
return new SolutionConverter<>(CommonApp.determineDataDir(dataDirName).getName(), inputSolutionFileIO, "import",
outputSolutionFileIO, "unsolved");
}
public static <Solution_> SolutionConverter<Solution_> createExportConverter(String dataDirName,
AbstractSolutionExporter<Solution_> exporter, SolutionFileIO<Solution_> inputSolutionFileIO) {
SolutionFileIO<Solution_> outputSolutionFileIO = new SolutionFileIO<>() {
@Override
public String getInputFileExtension() {
throw new UnsupportedOperationException();
}
@Override
public String getOutputFileExtension() {
return exporter.getOutputFileSuffix();
}
@Override
public Solution_ read(File inputSolutionFile) {
throw new UnsupportedOperationException();
}
@Override
public void write(Solution_ solution, File outputSolutionFile) {
exporter.writeSolution(solution, outputSolutionFile);
}
};
return new SolutionConverter<>(dataDirName, inputSolutionFileIO, "solved", outputSolutionFileIO, "export");
}
protected SolutionFileIO<Solution_> inputSolutionFileIO;
protected final File inputDir;
protected SolutionFileIO<Solution_> outputSolutionFileIO;
protected final File outputDir;
private SolutionConverter(String dataDirName,
SolutionFileIO<Solution_> inputSolutionFileIO, String inputDirName,
SolutionFileIO<Solution_> outputSolutionFileIO, String outputDirName) {
this.inputSolutionFileIO = inputSolutionFileIO;
this.outputSolutionFileIO = outputSolutionFileIO;
File dataDir = CommonApp.determineDataDir(dataDirName);
inputDir = new File(dataDir, inputDirName);
if (!inputDir.exists() || !inputDir.isDirectory()) {
throw new IllegalStateException("The directory inputDir (" + inputDir.getAbsolutePath()
+ ") does not exist or is not a directory.");
}
outputDir = new File(dataDir, outputDirName);
}
public void convertAll() {
File[] inputFiles = inputDir.listFiles();
if (inputFiles == null) {
throw new IllegalStateException("Unable to list the files in the inputDirectory ("
+ inputDir.getAbsolutePath() + ").");
}
Arrays.sort(inputFiles, new ProblemFileComparator());
Arrays.stream(inputFiles)
.parallel()
.filter(this::acceptInputFile)
.forEach(this::convert);
}
public boolean acceptInputFile(File inputFile) {
return inputFile.getName().endsWith("." + inputSolutionFileIO.getInputFileExtension());
}
public void convert(String inputFileName) {
String outputFileName = inputFileName.substring(0,
inputFileName.length() - inputSolutionFileIO.getInputFileExtension().length())
+ outputSolutionFileIO.getOutputFileExtension();
convert(inputFileName, outputFileName);
}
public void convert(String inputFileName, String outputFileName) {
File inputFile = new File(inputDir, inputFileName);
if (!inputFile.exists()) {
throw new IllegalStateException("The file inputFile (" + inputFile.getAbsolutePath()
+ ") does not exist.");
}
File outputFile = new File(outputDir, outputFileName);
outputFile.getParentFile().mkdirs();
convert(inputFile, outputFile);
}
public void convert(File inputFile) {
String inputFileName = inputFile.getName();
String outputFileName = inputFileName.substring(0,
inputFileName.length() - inputSolutionFileIO.getInputFileExtension().length())
+ outputSolutionFileIO.getOutputFileExtension();
File outputFile = new File(outputDir, outputFileName);
convert(inputFile, outputFile);
}
protected void convert(File inputFile, File outputFile) {
Solution_ solution = inputSolutionFileIO.read(inputFile);
outputSolutionFileIO.write(solution, outputFile);
logger.info("Saved: {}", outputFile);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence/XSSFColorUtil.java | package ai.timefold.solver.examples.common.persistence;
import java.awt.Color;
import org.apache.poi.xssf.usermodel.DefaultIndexedColorMap;
import org.apache.poi.xssf.usermodel.IndexedColorMap;
import org.apache.poi.xssf.usermodel.XSSFColor;
public final class XSSFColorUtil {
private static final IndexedColorMap INDEXED_COLOR_MAP = new DefaultIndexedColorMap();
public static XSSFColor getXSSFColor(Color awtColor) {
byte[] rgb = new byte[] {
intToByte(awtColor.getRed()),
intToByte(awtColor.getGreen()),
intToByte(awtColor.getBlue())
};
return new XSSFColor(rgb, INDEXED_COLOR_MAP);
}
private static byte intToByte(int integer) {
return ((Integer) integer).byteValue();
}
private XSSFColorUtil() {
// No external instances.
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence/generator/LocationDataGenerator.java | package ai.timefold.solver.examples.common.persistence.generator;
import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableList;
import java.util.List;
public class LocationDataGenerator {
public static final List<LocationData> EUROPE_BUSIEST_AIRPORTS = unmodifiableList(asList(
new LocationData("BRU", 50.901389, 4.484444),
new LocationData("LHR", 51.4775, -0.461389),
new LocationData("CDG", 49.009722, 2.547778),
new LocationData("AMS", 52.308056, 4.764167),
new LocationData("FRA", 50.033333, 8.570556),
new LocationData("IST", 40.976111, 28.814167),
new LocationData("MAD", 40.472222, -3.560833),
new LocationData("BCN", 41.296944, 2.078333),
new LocationData("LGW", 51.148056, -0.190278),
new LocationData("MUC", 48.353889, 11.786111),
new LocationData("FCO", 41.800278, 12.238889),
new LocationData("SVO", 55.972778, 37.414722),
new LocationData("ORY", 48.723333, 2.379444),
new LocationData("DME", 55.408611, 37.906111),
new LocationData("DUB", 53.421389, -6.27),
new LocationData("SRH", 47.464722, 8.549167),
new LocationData("CPH", 55.618056, 12.656111),
new LocationData("PMI", 39.551667, 2.738889),
new LocationData("MAN", 53.353889, -2.275),
new LocationData("OSL", 60.202778, 11.083889),
new LocationData("LIS", 38.774167, -9.134167),
new LocationData("ARN", 59.651944, 17.918611),
new LocationData("STN", 51.885, 0.235),
new LocationData("DUS", 51.289444, 6.766667),
new LocationData("VIE", 48.110833, 16.570833),
new LocationData("MXP", 45.63, 8.723056),
new LocationData("ATH", 37.936389, 23.947222),
new LocationData("TXL", 52.559722, 13.287778),
new LocationData("HEL", 60.317222, 24.963333),
new LocationData("AGP", 36.675, -4.499167),
new LocationData("VKO", 55.596111, 37.2675),
new LocationData("HAM", 53.630278, 9.991111),
new LocationData("GVA", 46.238333, 6.109444),
new LocationData("LED", 59.800278, 30.2625),
new LocationData("LTN", 51.874722, -0.368333),
new LocationData("WAW", 52.165833, 20.967222),
new LocationData("PRG", 50.100833, 14.26),
new LocationData("ALC", 38.282222, -0.558056),
new LocationData("EDI", 55.95, -3.3725),
new LocationData("NCE", 43.665278, 7.215),
new LocationData("BUD", 47.439444, 19.261944),
new LocationData("BHX", 52.453889, -1.748056),
new LocationData("SXF", 52.378611, 13.520556),
new LocationData("OTP", 44.571111, 26.085),
new LocationData("CGN", 50.865833, 7.142778),
new LocationData("BGY", 45.668889, 9.700278),
new LocationData("STR", 48.69, 9.221944),
new LocationData("OPO", 41.235556, -8.678056),
new LocationData("KBP", 50.344722, 30.893333),
new LocationData("VCE", 45.505278, 12.351944)));
// Unused, but we're keeping it around if we ever need to recreate the europe40 data set.
public static final List<LocationData> EUROPE_CAPITALS = unmodifiableList(asList(
new LocationData("Brussels", 50.797140, 4.361572),
new LocationData("Dublin", 53.309435, -6.284180),
new LocationData("London", 51.465872, -0.131836),
new LocationData("Paris", 48.797698, 2.351074),
new LocationData("Reykjavik", 64.133219, -21.886139),
new LocationData("Luxembourg", 49.537568, 6.130371),
new LocationData("Amsterdam", 52.320120, 4.888916),
new LocationData("Berlin", 52.480996, 13.414307),
new LocationData("Copenhagen", 55.620139, 12.579346),
new LocationData("Oslo", 59.876442, 10.766602),
new LocationData("Stockholm", 59.292446, 18.061523),
new LocationData("Helsinki", 60.134576, 24.949951),
new LocationData("Tallinn", 59.363808, 24.763184),
new LocationData("Riga", 56.845768, 24.082031),
new LocationData("Vilnius", 54.581401, 25.268555),
new LocationData("Minsk", 53.810166, 27.553711),
new LocationData("Warsaw", 52.129891, 21.005859),
new LocationData("Moscow", 55.661888, 37.617188),
new LocationData("Kiev", 50.355742, 30.541992),
new LocationData("Chisinau", 46.916253, 28.828125),
new LocationData("Bucharest", 44.319656, 26.059570),
new LocationData("Sofia", 42.581130, 23.312988),
new LocationData("Ankara", 39.943436, 32.857132),
new LocationData("Athens", 37.852881, 23.730469),
new LocationData("Nicosia", 35.099537, 33.365479),
new LocationData("Tirana", 41.283861, 19.808350),
new LocationData("Skopje", 41.949141, 21.456299),
new LocationData("Podgorica", 42.380730, 19.281006),
new LocationData("Belgrade", 44.752455, 20.456543),
new LocationData("Sarajevo", 43.784843, 18.347168),
new LocationData("Zagreb", 45.757815, 15.974121),
new LocationData("Ljubljana", 45.994926, 14.490967),
new LocationData("Rome", 41.842830, 12.491455),
new LocationData("Madrid", 40.369427, -3.691406),
new LocationData("Lisbon", 38.648910, -9.140625),
new LocationData("Bern", 46.895737, 7.437744),
new LocationData("Vienna", 48.142143, 16.380615),
new LocationData("Prague", 50.066778, 14.419556),
new LocationData("Bratislava", 48.098138, 17.105713),
new LocationData("Budapest", 47.440969, 19.039307)));
public static final List<LocationData> US_MAINLAND_STATE_CAPITALS = unmodifiableList(asList(
new LocationData("Montgomery, Alabama", 32.377716, -86.300568),
// new LocationData("Juneau, Alaska", 58.301598, -134.420212),
new LocationData("Phoenix, Arizona", 33.448143, -112.096962),
new LocationData("Little Rock, Arkansas", 34.746613, -92.288986),
new LocationData("Sacramento, California", 38.576668, -121.493629),
new LocationData("Denver, Colorado", 39.739227, -104.984856),
new LocationData("Hartford, Connecticut", 41.764046, -72.682198),
new LocationData("Dover, Delaware", 39.157307, -75.519722),
new LocationData("Tallahassee, Florida", 30.438118, -84.281296),
new LocationData("Atlanta, Georgia", 33.749027, -84.388229),
// new LocationData("Honolulu, Hawaii", 21.307442, -157.857376),
new LocationData("Boise, Idaho", 43.617775, -116.199722),
new LocationData("Springfield, Illinois", 39.798363, -89.654961),
new LocationData("Indianapolis, Indiana", 39.768623, -86.162643),
new LocationData("Des Moines, Iowa", 41.591087, -93.603729),
new LocationData("Topeka, Kansas", 39.048191, -95.677956),
new LocationData("Frankfort, Kentucky", 38.186722, -84.875374),
new LocationData("Baton Rouge, Louisiana", 30.457069, -91.187393),
new LocationData("Augusta, Maine", 44.307167, -69.781693),
new LocationData("Annapolis, Maryland", 38.978764, -76.490936),
new LocationData("Boston, Massachusetts", 42.358162, -71.063698),
new LocationData("Lansing, Michigan", 42.733635, -84.555328),
new LocationData("St. Paul, Minnesota", 44.955097, -93.102211),
new LocationData("Jackson, Mississippi", 32.303848, -90.182106),
new LocationData("Jefferson City, Missouri", 38.579201, -92.172935),
new LocationData("Helena, Montana", 46.585709, -112.018417),
new LocationData("Lincoln, Nebraska", 40.808075, -96.699654),
new LocationData("Carson City, Nevada", 39.163914, -119.766121),
new LocationData("Concord, New Hampshire", 43.206898, -71.537994),
new LocationData("Trenton, New Jersey", 40.220596, -74.769913),
new LocationData("Santa Fe, New Mexico", 35.68224, -105.939728),
new LocationData("Raleigh, North Carolina", 35.78043, -78.639099),
new LocationData("Bismarck, North Dakota", 46.82085, -100.783318),
new LocationData("Albany, New York", 42.652843, -73.757874),
new LocationData("Columbus, Ohio", 39.961346, -82.999069),
new LocationData("Oklahoma City, Oklahoma", 35.492207, -97.503342),
new LocationData("Salem, Oregon", 44.938461, -123.030403),
new LocationData("Harrisburg, Pennsylvania", 40.264378, -76.883598),
new LocationData("Providence, Rhode Island", 41.830914, -71.414963),
new LocationData("Columbia, South Carolina", 34.000343, -81.033211),
new LocationData("Pierre, South Dakota", 44.367031, -100.346405),
new LocationData("Nashville, Tennessee", 36.16581, -86.784241),
new LocationData("Austin, Texas", 30.27467, -97.740349),
new LocationData("Salt Lake City, Utah", 40.777477, -111.888237),
new LocationData("Montpelier, Vermont", 44.262436, -72.580536),
new LocationData("Richmond, Virginia", 37.538857, -77.43364),
new LocationData("Olympia, Washington", 47.035805, -122.905014),
new LocationData("Charleston, West Virginia", 38.336246, -81.612328),
new LocationData("Madison, Wisconsin", 43.074684, -89.384445),
new LocationData("Cheyenne, Wyoming", 41.140259, -104.820236)));
public static class LocationData {
private final String name;
protected final double latitude;
protected final double longitude;
public LocationData(String name, double latitude, double longitude) {
this.name = name;
this.latitude = latitude;
this.longitude = longitude;
}
public String getName() {
return name;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
}
private LocationDataGenerator() {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence/generator/StringDataGenerator.java | package ai.timefold.solver.examples.common.persistence.generator;
import java.util.ArrayList;
import java.util.List;
public class StringDataGenerator {
public static StringDataGenerator buildFullNames() {
return new StringDataGenerator()
.addPart(true, 0,
"Amy",
"Beth",
"Chad",
"Dan",
"Elsa",
"Flo",
"Gus",
"Hugo",
"Ivy",
"Jay")
.addPart(false, 1,
"A.",
"B.",
"C.",
"D.",
"E.",
"F.",
"G.",
"H.",
"I.",
"J.")
.addPart(false, 1,
"O.",
"P.",
"Q.",
"R.",
"S.",
"T.",
"U.",
"V.",
"W.",
"X.")
.addPart(false, 1,
"Cole",
"Fox",
"Green",
"Jones",
"King",
"Li",
"Poe",
"Rye",
"Smith",
"Watt");
}
public static StringDataGenerator buildCompanyNames() {
return new StringDataGenerator()
.addPart(true, 0,
"Steel",
"Paper",
"Stone",
"Wood",
"Water",
"Food",
"Oil",
"Car",
"Power",
"Computer")
.addPart(true, 1,
"Inc",
"Corp",
"Limited",
"Express",
"Telco",
"Mobile",
"Soft",
"Mart",
"Bank",
"Labs")
.addPart(false, 2,
"US",
"UK",
"JP",
"DE",
"FR",
"BE",
"NL",
"BR",
"IN",
"ES");
}
/**
* Determines how to go through the unique combinations to maximize uniqueness, even on small subsets.
* It does not scroll per digit (0000, 1111, 2222, 0001, 1112, 2220, 0002, 1110, 2221, ...).
* Instead, it scrolls per half (0000, 1111, 2222, 0011, 1122, 2200, 0022, 1100, 2211, ...).
*/
private final static int[][] HALF_SEQUENCE_MAP = new int[][] { {}, { 0 }, { 0, 1 }, { 0, 2, 1 }, { 0, 2, 1, 3 } };
/**
* Determines which parts to eliminate first if maximumSize prediction doesn't need all parts.
*/
private final static int[] DEFAULT_ELIMINATION_INDEX_MAP = new int[] { 0, 1, 1, 1 };
private final boolean capitalizeFirstLetter;
private final String delimiter;
private final List<String[]> partValuesList = new ArrayList<>();
private int partValuesLength;
private final List<Integer> eliminationIndexMap = new ArrayList<>();
private int requiredSize = 0;
private List<String[]> filteredPartValuesList = partValuesList;
private int index = 0;
private int indexLimit;
public StringDataGenerator() {
this(false);
}
public StringDataGenerator(boolean capitalizeFirstLetter) {
this(capitalizeFirstLetter, " ");
}
public StringDataGenerator(String delimiter) {
this(false, delimiter);
}
public StringDataGenerator(boolean capitalizeFirstLetter, String delimiter) {
this.capitalizeFirstLetter = capitalizeFirstLetter;
this.delimiter = delimiter;
}
public StringDataGenerator addPart(String... partValues) {
return addPart(false, DEFAULT_ELIMINATION_INDEX_MAP[partValuesList.size()], partValues);
}
public StringDataGenerator addAToZPart() {
return addAToZPart(false, DEFAULT_ELIMINATION_INDEX_MAP[partValuesList.size()]);
}
public StringDataGenerator addAToZPart(boolean required, int eliminationIndex) {
return addPart(required, eliminationIndex,
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z");
}
public StringDataGenerator addNumericPart(boolean required, int eliminationIndex, int from, int to) {
String[] partValues = new String[to - from];
for (int i = from; i < to; i++) {
partValues[i - from] = Integer.toString(i);
}
return addPart(required, eliminationIndex, partValues);
}
public StringDataGenerator addPart(boolean required, int eliminationIndex, String... partValues) {
if (partValuesList.isEmpty()) {
partValuesLength = partValues.length;
} else {
if (partValues.length != partValuesLength) {
throw new IllegalStateException("The partValues length (" + partValues.length
+ ") is not the same as the partValuesLength (" + partValuesLength + ") of the others.");
}
}
if (required) {
requiredSize++;
}
partValuesList.add(partValues);
eliminationIndexMap.add(eliminationIndex);
indexLimit = (int) Math.pow(partValuesLength, partValuesList.size());
filteredPartValuesList = partValuesList;
return this;
}
public void reset() {
filteredPartValuesList = partValuesList;
index = 0;
}
public void predictMaximumSizeAndReset(int maximumSize) {
indexLimit = (int) Math.pow(partValuesLength, partValuesList.size());
filteredPartValuesList = partValuesList;
for (int i = 1; i < partValuesList.size(); i++) {
int proposedIndexLimit = (int) Math.pow(partValuesLength, i);
if (maximumSize <= proposedIndexLimit) {
filteredPartValuesList = new ArrayList<>(partValuesList);
while (i < filteredPartValuesList.size() && filteredPartValuesList.size() > requiredSize) {
int eliminationIndex = eliminationIndexMap.get(filteredPartValuesList.size() - 1);
filteredPartValuesList.remove(eliminationIndex);
}
indexLimit = proposedIndexLimit;
break;
}
}
index = 0;
}
public String generateNextValue() {
if (index >= indexLimit) {
throw new IllegalStateException("No more elements: the index (" + index
+ ") is higher than the indexLimit (" + indexLimit + ").\n"
+ "Maybe predictMaximumSizeAndReset() was called with a too low maximumSize.");
}
int listSize = filteredPartValuesList.size();
StringBuilder result = new StringBuilder(listSize * 80);
// Make sure we have a unique combination
if (listSize >= HALF_SEQUENCE_MAP.length) {
throw new IllegalStateException("A listSize (" + listSize + ") is not yet supported.");
}
int[] halfSequence = HALF_SEQUENCE_MAP[listSize];
int[] chosens = new int[listSize];
int previousChosen = 0;
for (int i = 0; i < listSize; i++) {
int chosen = (previousChosen
+ (index % (int) Math.pow(partValuesLength, halfSequence[i] + 1)
/ (int) Math.pow(partValuesLength, halfSequence[i])))
% partValuesLength;
chosens[i] = chosen;
previousChosen = chosen;
}
for (int i = 0; i < listSize; i++) {
if (i > 0) {
result.append(delimiter);
}
String[] partValues = filteredPartValuesList.get(i);
result.append(partValues[chosens[i]]);
}
index++;
if (capitalizeFirstLetter) {
result.setCharAt(0, Character.toUpperCase(result.charAt(0)));
}
return result.toString();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence/jackson/AbstractKeyDeserializer.java | package ai.timefold.solver.examples.common.persistence.jackson;
import java.util.Objects;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.AbstractJsonSolutionFileIO;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.KeyDeserializer;
/**
* Deserializes map key defined by {@link JacksonUniqueIdGenerator} to a child of {@link AbstractPersistable}.
* <p>
* Deserialization will create new instances of the map key type.
* Duplicate instances will be created if any other part of the JSON is also referencing the same type.
* In that case, a custom implementation of {@link AbstractJsonSolutionFileIO} must be used later
* to resolve the duplicates by comparing IDs of such objects and making sure only one instance exists with each ID.
* <p>
* Example: let us consider a "Location" object that has a field of type Map<Location, Distance>.
* When the outer Location object gets deserialized from List<Location>,
* the nested map needs to be deserialized as well.
* However, at this point, the Location objects used as keys in the map do not yet exist.
* (The rest of the list has not been read yet.)
* Therefore the deserializer needs to create a temporary dummy Location object to use as the map key.
* This object later needs to be replaced by the actual Location object by the {@link AbstractJsonSolutionFileIO}.
*
* @param <E> The type must have a {@link com.fasterxml.jackson.annotation.JsonIdentityInfo} annotation with
* {@link JacksonUniqueIdGenerator} as its generator.
*/
public abstract class AbstractKeyDeserializer<E extends AbstractPersistable> extends KeyDeserializer {
private final Class<E> persistableClass;
protected AbstractKeyDeserializer(Class<E> persistableClass) {
this.persistableClass = Objects.requireNonNull(persistableClass);
}
@Override
public final E deserializeKey(String value, DeserializationContext deserializationContext) {
String[] parts = value.split("#");
String className = parts[0];
if (!Objects.equals(className, persistableClass.getSimpleName())) {
throw new IllegalStateException("Impossible state: not the correct type (" + value + ").");
}
String idString = parts[1];
try {
long id = Long.parseLong(idString);
return createInstance(id); // Need to be de-duplicated in solution IO.
} catch (NumberFormatException e) {
throw new IllegalStateException("Impossible state: id is not a number (" + idString + ")");
}
}
protected abstract E createInstance(long id);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence/jackson/JacksonUniqueIdGenerator.java | package ai.timefold.solver.examples.common.persistence.jackson;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.AbstractJsonSolutionFileIO;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerator;
import com.fasterxml.jackson.annotation.ObjectIdGenerators.PropertyGenerator;
import com.fasterxml.jackson.annotation.ObjectIdGenerators.UUIDGenerator;
/**
* Exists so that complex data models (such as TSP chaining) can be serialized/deserialized.
* These complexities include:
*
* <ul>
* <li>Serializing maps where keys are themselves serialized objects that need to be referenced later.</li>
* <li>Serializing polymorphic types.</li>
* <li>Serializing self-referential and/or recursive types.</li>
* </ul>
*
* Jackson can easily handle any of these problems individually,
* but struggles when they are all combined.
* <p>
* This class and other classes in this package aim to solve those issues
* by introducing a new ID field on all serialized objects,
* typically called "@id".
* This field is used exclusively for referencing objects in the serialized JSON,
* it never enters the Java data model.
* Therefore it is not related to {@link AbstractPersistable#getId()},
* which is the actual object ID used in the Java examples.
* See Vehicle Routing example to learn how to use this pattern.
* <p>
* For use cases without these advanced needs,
* the less complex way of using {@link JsonIdentityInfo} with {@link PropertyGenerator} is preferred.
* See Cloud Balancing example to learn how to use this pattern.
* <p>
* The implementation is similar in principle to {@link UUIDGenerator}, but without the long and undescriptive UUIDs.
* Works only for children of {@link AbstractPersistable}.
* No two such classes must have the same {@link Class#getSimpleName()}.
*
* @see KeySerializer
* @see AbstractKeyDeserializer
* @see AbstractJsonSolutionFileIO
*/
public final class JacksonUniqueIdGenerator extends ObjectIdGenerator<String> {
private final Class<?> scope;
public JacksonUniqueIdGenerator() {
this.scope = Object.class;
}
@Override
public Class<?> getScope() {
return scope;
}
@Override
public boolean canUseFor(ObjectIdGenerator<?> gen) {
return (gen.getClass() == getClass());
}
@Override
public ObjectIdGenerator<String> forScope(Class<?> scope) {
return this;
}
@Override
public ObjectIdGenerator<String> newForSerialization(Object context) {
return this;
}
@Override
public IdKey key(Object key) {
if (key == null) {
return null;
}
return new IdKey(getClass(), null, key);
}
@Override
public String generateId(Object forPojo) {
return forPojo.getClass().getSimpleName() + "#" + ((AbstractPersistable) forPojo).getId();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence/jackson/KeySerializer.java | package ai.timefold.solver.examples.common.persistence.jackson;
import java.io.IOException;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import com.fasterxml.jackson.annotation.ObjectIdGenerator;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
/**
* Serializes a child of {@link AbstractPersistable} to a JSON map key using {@link JacksonUniqueIdGenerator}.
*
* @param <E> The type must have a {@link com.fasterxml.jackson.annotation.JsonIdentityInfo} annotation with
* {@link JacksonUniqueIdGenerator} as its generator.
*/
public final class KeySerializer<E extends AbstractPersistable> extends JsonSerializer<E> {
private final ObjectIdGenerator<String> idGenerator = new JacksonUniqueIdGenerator();
@Override
public void serialize(E persistable, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
Object jsonId = serializerProvider.findObjectId(persistable, idGenerator)
.generateId(persistable);
jsonGenerator.writeFieldName(jsonId.toString());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/persistence/jackson/package-info.java | /**
* Contains classes necessary in order to maintain a consistent JSON model with referential integrity and as little
* object duplication as possible.
*/
package ai.timefold.solver.examples.common.persistence.jackson; |
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/swingui/CommonIcons.java | package ai.timefold.solver.examples.common.swingui;
import javax.swing.ImageIcon;
public class CommonIcons {
public final static ImageIcon PINNED_ICON = new ImageIcon(CommonIcons.class.getResource("pinned.png"));
private CommonIcons() {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/swingui/ConstraintMatchesDialog.java | package ai.timefold.solver.examples.common.swingui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.util.List;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumnModel;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatch;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal;
import ai.timefold.solver.examples.common.business.SolutionBusiness;
final class ConstraintMatchesDialog extends JDialog {
private final SolutionBusiness solutionBusiness;
public ConstraintMatchesDialog(SolverAndPersistenceFrame solverAndPersistenceFrame,
SolutionBusiness solutionBusiness) {
super(solverAndPersistenceFrame, "Constraint matches", true);
this.solutionBusiness = solutionBusiness;
}
public void resetContentPanel() {
JPanel buttonPanel = new JPanel(new FlowLayout());
Action okAction = new AbstractAction("OK") {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
};
buttonPanel.add(new JButton(okAction));
if (!solutionBusiness.isConstraintMatchEnabled()) {
JPanel unsupportedPanel = new JPanel(new BorderLayout());
JLabel unsupportedLabel = new JLabel("Constraint matches are not supported with this ScoreDirector.");
unsupportedPanel.add(unsupportedLabel, BorderLayout.CENTER);
unsupportedPanel.add(buttonPanel, BorderLayout.SOUTH);
setContentPane(unsupportedPanel);
} else {
final List<ConstraintMatchTotal<?>> constraintMatchTotalList = solutionBusiness.getConstraintMatchTotalList();
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
final JTable table = new JTable(new ConstraintMatchTotalTableModel(constraintMatchTotalList));
TableColumnModel columnModel = table.getColumnModel();
columnModel.getColumn(0).setPreferredWidth(300);
columnModel.getColumn(1).setPreferredWidth(80);
columnModel.getColumn(2).setPreferredWidth(80);
columnModel.getColumn(3).setPreferredWidth(80);
DefaultTableCellRenderer rightCellRenderer = new DefaultTableCellRenderer();
rightCellRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
columnModel.getColumn(1).setCellRenderer(rightCellRenderer);
columnModel.getColumn(3).setCellRenderer(rightCellRenderer);
JScrollPane tableScrollPane = new JScrollPane(table);
tableScrollPane.setPreferredSize(new Dimension(700, 300));
splitPane.setTopComponent(tableScrollPane);
JPanel bottomPanel = new JPanel(new BorderLayout());
JLabel detailLabel = new JLabel("Constraint matches of selected constraint type");
detailLabel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
bottomPanel.add(detailLabel, BorderLayout.NORTH);
final JTextArea detailTextArea = new JTextArea(10, 80);
JScrollPane detailScrollPane = new JScrollPane(detailTextArea);
bottomPanel.add(detailScrollPane, BorderLayout.CENTER);
table.getSelectionModel().addListSelectionListener(
event -> {
int selectedRow = table.getSelectedRow();
if (selectedRow < 0) {
detailTextArea.setText("");
} else {
ConstraintMatchTotal<?> constraintMatchTotal = constraintMatchTotalList.get(selectedRow);
detailTextArea.setText(buildConstraintMatchSetText(constraintMatchTotal));
detailTextArea.setCaretPosition(0);
}
});
bottomPanel.add(buttonPanel, BorderLayout.SOUTH);
splitPane.setBottomComponent(bottomPanel);
splitPane.setResizeWeight(1.0);
setContentPane(splitPane);
}
pack();
setLocationRelativeTo(getParent());
}
public String buildConstraintMatchSetText(ConstraintMatchTotal<?> constraintMatchTotal) {
Set<? extends ConstraintMatch<?>> constraintMatchSet = constraintMatchTotal.getConstraintMatchSet();
StringBuilder text = new StringBuilder(constraintMatchSet.size() * 80);
for (ConstraintMatch<?> constraintMatch : constraintMatchSet) {
text.append(constraintMatch.getIndictedObjectList().toString())
.append(" = ")
.append(constraintMatch.getScore().toShortString()).append("\n");
}
return text.toString();
}
public static class ConstraintMatchTotalTableModel extends AbstractTableModel {
private final List<ConstraintMatchTotal<?>> constraintMatchTotalList;
public ConstraintMatchTotalTableModel(List<ConstraintMatchTotal<?>> constraintMatchTotalList) {
this.constraintMatchTotalList = constraintMatchTotalList;
}
@Override
public int getRowCount() {
return constraintMatchTotalList.size();
}
@Override
public int getColumnCount() {
return 4;
}
@Override
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case 0:
return "Constraint name";
case 1:
return "Constraint weight";
case 2:
return "Match count";
case 3:
return "Score";
default:
throw new IllegalStateException("The columnIndex (" + columnIndex + ") is invalid.");
}
}
@Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return String.class;
default:
throw new IllegalStateException("The columnIndex (" + columnIndex + ") is invalid.");
}
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
ConstraintMatchTotal<?> constraintMatchTotal = constraintMatchTotalList.get(rowIndex);
switch (columnIndex) {
case 0:
return constraintMatchTotal.getConstraintRef().constraintName();
case 1:
Score<?> constraintWeight = constraintMatchTotal.getConstraintWeight();
return constraintWeight == null ? "N/A" : constraintWeight.toShortString();
case 2:
return constraintMatchTotal.getConstraintMatchCount();
case 3:
return constraintMatchTotal.getScore().toShortString();
default:
throw new IllegalStateException("The columnIndex (" + columnIndex + ") is invalid.");
}
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/swingui/OpenBrowserAction.java | package ai.timefold.solver.examples.common.swingui;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
public final class OpenBrowserAction extends AbstractAction {
private final URI uri;
public OpenBrowserAction(String title, String urlString) {
super(title);
try {
uri = new URI(urlString);
} catch (URISyntaxException e) {
throw new IllegalStateException("Failed creating URI for urlString (" + urlString + ").", e);
}
}
@Override
public void actionPerformed(ActionEvent event) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop == null || !desktop.isSupported(Desktop.Action.BROWSE)) {
JOptionPane.showMessageDialog(null, "Cannot open a browser automatically."
+ "\nPlease open this url manually:\n" + uri.toString(),
"Cannot open browser", JOptionPane.INFORMATION_MESSAGE);
return;
}
try {
desktop.browse(uri);
} catch (IOException e) {
throw new IllegalStateException("Failed showing uri (" + uri + ") in the default browser.", e);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/swingui/SolutionPanel.java | package ai.timefold.solver.examples.common.swingui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.JViewport;
import javax.swing.Scrollable;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatch;
import ai.timefold.solver.core.api.score.constraint.Indictment;
import ai.timefold.solver.core.api.solver.change.ProblemChange;
import ai.timefold.solver.examples.common.business.SolutionBusiness;
import ai.timefold.solver.swing.impl.TangoColorFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class SolutionPanel<Solution_> extends JPanel implements Scrollable {
protected static final String USAGE_EXPLANATION_PATH =
"/ai/timefold/solver/examples/common/swingui/exampleUsageExplanation.png";
// Size fits into screen resolution 1024*768
public static final Dimension PREFERRED_SCROLLABLE_VIEWPORT_SIZE = new Dimension(800, 600);
protected static final Color[][] INDICTMENT_COLORS = {
{ TangoColorFactory.SCARLET_3, TangoColorFactory.SCARLET_1 },
{ TangoColorFactory.ORANGE_3, TangoColorFactory.ORANGE_1 },
{ TangoColorFactory.BUTTER_3, TangoColorFactory.BUTTER_1 },
{ TangoColorFactory.CHAMELEON_3, TangoColorFactory.CHAMELEON_1 },
{ TangoColorFactory.SKY_BLUE_3, TangoColorFactory.SKY_BLUE_1 },
{ TangoColorFactory.PLUM_3, TangoColorFactory.PLUM_1 }
};
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected SolverAndPersistenceFrame<Solution_> solverAndPersistenceFrame;
protected SolutionBusiness<Solution_, ?> solutionBusiness;
protected boolean useIndictmentColor = false;
protected TangoColorFactory normalColorFactory;
protected double[] indictmentMinimumLevelNumbers;
public SolverAndPersistenceFrame<Solution_> getSolverAndPersistenceFrame() {
return solverAndPersistenceFrame;
}
public void setSolverAndPersistenceFrame(SolverAndPersistenceFrame<Solution_> solverAndPersistenceFrame) {
this.solverAndPersistenceFrame = solverAndPersistenceFrame;
}
public SolutionBusiness<Solution_, ?> getSolutionBusiness() {
return solutionBusiness;
}
public void setSolutionBusiness(SolutionBusiness<Solution_, ?> solutionBusiness) {
this.solutionBusiness = solutionBusiness;
}
public boolean isUseIndictmentColor() {
return useIndictmentColor;
}
public void setUseIndictmentColor(boolean useIndictmentColor) {
this.useIndictmentColor = useIndictmentColor;
}
public String getUsageExplanationPath() {
return USAGE_EXPLANATION_PATH;
}
public boolean isWrapInScrollPane() {
return true;
}
public abstract void resetPanel(Solution_ solution);
public void updatePanel(Solution_ solution) {
resetPanel(solution);
}
public Solution_ getSolution() {
return solutionBusiness.getSolution();
}
@Override
public Dimension getPreferredScrollableViewportSize() {
return PREFERRED_SCROLLABLE_VIEWPORT_SIZE;
}
@Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 20;
}
@Override
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return 20;
}
@Override
public boolean getScrollableTracksViewportWidth() {
if (getParent() instanceof JViewport) {
return (getParent().getWidth() > getPreferredSize().width);
}
return false;
}
@Override
public boolean getScrollableTracksViewportHeight() {
if (getParent() instanceof JViewport) {
return (getParent().getHeight() > getPreferredSize().height);
}
return false;
}
public boolean isIndictmentHeatMapEnabled() {
return false;
}
protected void preparePlanningEntityColors(List<?> planningEntityList) {
if (useIndictmentColor) {
indictmentMinimumLevelNumbers = null;
for (Object planningEntity : planningEntityList) {
Indictment<?> indictment = solutionBusiness.getIndictmentMap().get(planningEntity);
if (indictment != null) {
Number[] levelNumbers = indictment.getScore().toLevelNumbers();
if (indictmentMinimumLevelNumbers == null) {
indictmentMinimumLevelNumbers = new double[levelNumbers.length];
for (int i = 0; i < levelNumbers.length; i++) {
indictmentMinimumLevelNumbers[i] = levelNumbers[i].doubleValue();
}
} else {
for (int i = 0; i < levelNumbers.length; i++) {
double levelNumber = levelNumbers[i].doubleValue();
if (levelNumber < indictmentMinimumLevelNumbers[i]) {
indictmentMinimumLevelNumbers[i] = levelNumber;
}
}
}
}
}
} else {
normalColorFactory = new TangoColorFactory();
}
}
public Color determinePlanningEntityColor(Object planningEntity, Object normalColorObject) {
if (useIndictmentColor) {
Indictment<?> indictment = solutionBusiness.getIndictmentMap().get(planningEntity);
if (indictment != null) {
Number[] levelNumbers = indictment.getScore().toLevelNumbers();
for (int i = 0; i < levelNumbers.length; i++) {
if (i > INDICTMENT_COLORS.length) {
return TangoColorFactory.ALUMINIUM_3;
}
double levelNumber = levelNumbers[i].doubleValue();
if (levelNumber < 0.0) {
return TangoColorFactory.buildPercentageColor(
INDICTMENT_COLORS[i][0], INDICTMENT_COLORS[i][1],
1.0 - (levelNumber / indictmentMinimumLevelNumbers[i]));
}
}
}
return Color.WHITE;
} else {
return normalColorFactory.pickColor(normalColorObject);
}
}
public String determinePlanningEntityTooltip(Object planningEntity) {
Indictment<?> indictment = solutionBusiness.getIndictmentMap().get(planningEntity);
if (indictment == null) {
return "<html>No indictment</html>";
}
StringBuilder s = new StringBuilder("<html>Indictment: ").append(indictment.getScore().toShortString());
for (ConstraintMatch<?> constraintMatch : indictment.getConstraintMatchSet()) {
s.append("<br/> ")
.append(constraintMatch.getConstraintRef().constraintName())
.append(" = ")
.append(constraintMatch.getScore().toShortString());
}
s.append("</html>");
return s.toString();
}
public void doProblemChange(ProblemChange<Solution_> problemChange) {
doProblemChange(problemChange, false);
}
public void doProblemChange(ProblemChange<Solution_> problemChange, boolean reset) {
solutionBusiness.doProblemChange(problemChange);
Solution_ solution = getSolution();
Score score = solutionBusiness.getScore();
if (reset) {
resetPanel(solution);
} else {
updatePanel(solution);
}
validate();
solverAndPersistenceFrame.refreshScoreField(score);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/swingui/SolverAndPersistenceFrame.java | package ai.timefold.solver.examples.common.swingui;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.LayoutStyle;
import javax.swing.ListSelectionModel;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileFilter;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.examples.common.app.CommonApp;
import ai.timefold.solver.examples.common.business.SolutionBusiness;
import ai.timefold.solver.examples.common.persistence.AbstractSolutionExporter;
import ai.timefold.solver.examples.common.persistence.AbstractSolutionImporter;
import ai.timefold.solver.swing.impl.TangoColorFactory;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public final class SolverAndPersistenceFrame<Solution_>
extends JFrame {
public static final ImageIcon TIMEFOLD_ICON = new ImageIcon(
SolverAndPersistenceFrame.class.getResource("timefold-logomark.png"));
private final SolutionBusiness<Solution_, ?> solutionBusiness;
private final ImageIcon indictmentHeatMapTrueIcon;
private final ImageIcon indictmentHeatMapFalseIcon;
private final ImageIcon refreshScreenDuringSolvingTrueIcon;
private final ImageIcon refreshScreenDuringSolvingFalseIcon;
private final SolutionPanel<Solution_> solutionPanel;
private final ConstraintMatchesDialog constraintMatchesDialog;
private JList<QuickOpenAction> quickOpenUnsolvedJList;
private JList<QuickOpenAction> quickOpenSolvedJList;
private Action openAction;
private Action saveAction;
private Action importAction;
private Action exportAction;
private final Action[] extraActions;
private JToggleButton refreshScreenDuringSolvingToggleButton;
private JToggleButton indictmentHeatMapToggleButton;
private Action solveAction;
private JButton solveButton;
private Action terminateSolvingEarlyAction;
private JButton terminateSolvingEarlyButton;
private JPanel middlePanel;
private JProgressBar progressBar;
private JTextField scoreField;
private ShowConstraintMatchesDialogAction showConstraintMatchesDialogAction;
public SolverAndPersistenceFrame(SolutionBusiness<Solution_, ?> solutionBusiness,
SolutionPanel<Solution_> solutionPanel, CommonApp.ExtraAction<Solution_>[] extraActions) {
super(solutionBusiness.getAppName() + " Timefold example");
this.solutionBusiness = solutionBusiness;
this.solutionPanel = solutionPanel;
setIconImage(TIMEFOLD_ICON.getImage());
solutionPanel.setSolutionBusiness(solutionBusiness);
solutionPanel.setSolverAndPersistenceFrame(this);
this.extraActions = Arrays.stream(extraActions)
.map(a -> new AbstractAction(a.getName()) {
@Override
public void actionPerformed(ActionEvent e) {
a.accept(solutionBusiness, solutionPanel);
}
})
.toArray(Action[]::new);
indictmentHeatMapTrueIcon = new ImageIcon(getClass().getResource("indictmentHeatMapTrueIcon.png"));
indictmentHeatMapFalseIcon = new ImageIcon(getClass().getResource("indictmentHeatMapFalseIcon.png"));
refreshScreenDuringSolvingTrueIcon = new ImageIcon(getClass().getResource("refreshScreenDuringSolvingTrueIcon.png"));
refreshScreenDuringSolvingFalseIcon = new ImageIcon(getClass().getResource("refreshScreenDuringSolvingFalseIcon.png"));
registerListeners();
constraintMatchesDialog = new ConstraintMatchesDialog(this, solutionBusiness);
}
private void registerListeners() {
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// This async, so it doesn't stop the solving immediately
solutionBusiness.close();
}
});
}
private void bestSolutionChanged(Solution_ solution) {
Score score = solutionBusiness.getScore();
if (refreshScreenDuringSolvingToggleButton.isSelected()) {
solutionPanel.updatePanel(solution);
validate(); // TODO remove me?
}
refreshScoreField(score);
}
public void init(Component centerForComponent) {
setContentPane(createContentPane());
pack();
setLocationRelativeTo(centerForComponent);
}
private JComponent createContentPane() {
JComponent quickOpenPanel = createQuickOpenPanel();
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(createToolBar(), BorderLayout.NORTH);
mainPanel.add(createMiddlePanel(), BorderLayout.CENTER);
mainPanel.add(createScorePanel(), BorderLayout.SOUTH);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, quickOpenPanel, mainPanel);
splitPane.setOneTouchExpandable(true);
splitPane.setResizeWeight(0.2);
return splitPane;
}
private JComponent createQuickOpenPanel() {
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
createQuickOpenUnsolvedPanel(), createQuickOpenSolvedPanel());
splitPane.setResizeWeight(0.8);
splitPane.setBorder(null);
return splitPane;
}
private JComponent createQuickOpenUnsolvedPanel() {
quickOpenUnsolvedJList = new JList<>(new DefaultListModel<>());
List<File> unsolvedFileList = solutionBusiness.getUnsolvedFileList();
return createQuickOpenPanel(quickOpenUnsolvedJList, "Unsolved dataset shortcuts", unsolvedFileList);
}
private JComponent createQuickOpenSolvedPanel() {
quickOpenSolvedJList = new JList<>(new DefaultListModel<>());
List<File> solvedFileList = solutionBusiness.getSolvedFileList();
return createQuickOpenPanel(quickOpenSolvedJList, "Solved dataset shortcuts", solvedFileList);
}
private JComponent createQuickOpenPanel(JList<QuickOpenAction> listPanel, String title, List<File> fileList) {
listPanel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listPanel.addListSelectionListener(event -> {
if (event.getValueIsAdjusting()) {
return;
}
int selectedIndex = listPanel.getSelectedIndex();
if (selectedIndex < 0) {
return;
}
QuickOpenAction action = listPanel.getModel().getElementAt(selectedIndex);
action.actionPerformed(new ActionEvent(listPanel, -1, null));
});
refreshQuickOpenPanel(listPanel, fileList);
JScrollPane scrollPane = new JScrollPane(listPanel);
scrollPane.getVerticalScrollBar().setUnitIncrement(25);
scrollPane.setMinimumSize(new Dimension(100, 80));
// Size fits into screen resolution 1024*768
scrollPane.setPreferredSize(new Dimension(180, 200));
JPanel titlePanel = new JPanel(new BorderLayout());
titlePanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
JLabel titleLabel = new JLabel(title);
titleLabel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
titlePanel.add(titleLabel, BorderLayout.NORTH);
titlePanel.add(scrollPane, BorderLayout.CENTER);
return titlePanel;
}
private void refreshQuickOpenPanel(JList<QuickOpenAction> listPanel, List<File> fileList) {
DefaultListModel<QuickOpenAction> model = (DefaultListModel<QuickOpenAction>) listPanel.getModel();
model.clear();
for (File file : fileList) {
QuickOpenAction action = new QuickOpenAction(file);
model.addElement(action);
listPanel.clearSelection();
}
}
private class QuickOpenAction extends AbstractAction {
private final File file;
public QuickOpenAction(File file) {
super(file.getName().replaceAll("\\.json$|\\.xml$", ""));
this.file = file;
}
@Override
public void actionPerformed(ActionEvent e) {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
solutionBusiness.openSolution(file);
setSolutionLoaded(e.getSource());
} finally {
setCursor(Cursor.getDefaultCursor());
}
}
@Override
public String toString() {
return getValue(Action.NAME).toString();
}
}
private JComponent createToolBar() {
// JToolBar looks ugly in Nimbus LookAndFeel
JPanel toolBar = new JPanel();
GroupLayout toolBarLayout = new GroupLayout(toolBar);
toolBar.setLayout(toolBarLayout);
JButton importButton;
if (solutionBusiness.hasImporter()) {
importAction = new ImportAction();
importButton = new JButton(importAction);
} else {
importButton = null;
}
openAction = new OpenAction();
openAction.setEnabled(true);
JButton openButton = new JButton(openAction);
saveAction = new SaveAction();
saveAction.setEnabled(false);
JButton saveButton = new JButton(saveAction);
JButton exportButton;
if (solutionBusiness.hasExporter()) {
exportAction = new ExportAction();
exportAction.setEnabled(false);
exportButton = new JButton(exportAction);
} else {
exportButton = null;
}
JButton[] extraButtons = new JButton[extraActions.length];
for (int i = 0; i < extraActions.length; i++) {
extraButtons[i] = new JButton(extraActions[i]);
}
progressBar = new JProgressBar(0, 100);
JPanel solvePanel = new JPanel(new CardLayout());
solveAction = new SolveAction();
solveAction.setEnabled(false);
solveButton = new JButton(solveAction);
terminateSolvingEarlyAction = new TerminateSolvingEarlyAction();
terminateSolvingEarlyAction.setEnabled(false);
terminateSolvingEarlyButton = new JButton(terminateSolvingEarlyAction);
terminateSolvingEarlyButton.setVisible(false);
solvePanel.add(solveButton, "solveAction");
solvePanel.add(terminateSolvingEarlyButton, "terminateSolvingEarlyAction");
solveButton.setMinimumSize(terminateSolvingEarlyButton.getMinimumSize());
solveButton.setPreferredSize(terminateSolvingEarlyButton.getPreferredSize());
GroupLayout.SequentialGroup horizontalGroup = toolBarLayout.createSequentialGroup();
if (solutionBusiness.hasImporter()) {
horizontalGroup.addComponent(importButton);
}
horizontalGroup.addComponent(openButton);
horizontalGroup.addComponent(saveButton);
if (solutionBusiness.hasExporter()) {
horizontalGroup.addComponent(exportButton);
}
for (JButton extraButton : extraButtons) {
horizontalGroup.addComponent(extraButton);
}
horizontalGroup.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE);
horizontalGroup.addComponent(solvePanel, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE,
GroupLayout.PREFERRED_SIZE);
horizontalGroup.addComponent(progressBar, 20, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE);
toolBarLayout.setHorizontalGroup(horizontalGroup);
GroupLayout.ParallelGroup verticalGroup = toolBarLayout.createParallelGroup(GroupLayout.Alignment.CENTER);
if (solutionBusiness.hasImporter()) {
verticalGroup.addComponent(importButton);
}
verticalGroup.addComponent(openButton);
verticalGroup.addComponent(saveButton);
if (solutionBusiness.hasExporter()) {
verticalGroup.addComponent(exportButton);
}
for (JButton extraButton : extraButtons) {
verticalGroup.addComponent(extraButton);
}
verticalGroup.addComponent(solvePanel);
verticalGroup.addComponent(progressBar);
toolBarLayout.setVerticalGroup(verticalGroup);
return toolBar;
}
private class SolveAction extends AbstractAction {
public SolveAction() {
super("Solve", new ImageIcon(SolverAndPersistenceFrame.class.getResource("solveAction.png")));
}
@Override
public void actionPerformed(ActionEvent e) {
setSolvingState(true);
Solution_ problem = solutionBusiness.getSolution();
new SolveWorker(problem).execute();
}
}
protected class SolveWorker extends SwingWorker<Solution_, Void> {
protected final Solution_ problem;
public SolveWorker(Solution_ problem) {
this.problem = problem;
}
@Override
protected Solution_ doInBackground() {
return solutionBusiness.solve(problem, SolverAndPersistenceFrame.this::bestSolutionChanged);
}
@Override
protected void done() {
try {
Solution_ bestSolution = get();
solutionBusiness.setSolution(bestSolution);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Solving was interrupted.", e);
} catch (ExecutionException e) {
throw new IllegalStateException("Solving failed.", e.getCause());
} finally {
setSolvingState(false);
resetScreen();
}
}
}
private class TerminateSolvingEarlyAction extends AbstractAction {
public TerminateSolvingEarlyAction() {
super("Terminate solving early",
new ImageIcon(SolverAndPersistenceFrame.class.getResource("terminateSolvingEarlyAction.png")));
}
@Override
public void actionPerformed(ActionEvent e) {
terminateSolvingEarlyAction.setEnabled(false);
progressBar.setString("Terminating...");
// This async, so it doesn't stop the solving immediately
solutionBusiness.terminateSolvingEarly();
}
}
private class OpenAction extends AbstractAction {
private static final String NAME = "Open...";
private final JFileChooser fileChooser;
public OpenAction() {
super(NAME, new ImageIcon(SolverAndPersistenceFrame.class.getResource("openAction.png")));
fileChooser = new JFileChooser(solutionBusiness.getSolvedDataDir());
final String inputFileExtension = solutionBusiness.getSolutionFileIO().getOutputFileExtension();
fileChooser.setFileFilter(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isDirectory() || file.getName().endsWith("." + inputFileExtension);
}
@Override
public String getDescription() {
return "Solution files (*." + inputFileExtension + ")";
}
});
fileChooser.setDialogTitle(NAME);
}
@Override
public void actionPerformed(ActionEvent e) {
int approved = fileChooser.showOpenDialog(SolverAndPersistenceFrame.this);
if (approved == JFileChooser.APPROVE_OPTION) {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
solutionBusiness.openSolution(fileChooser.getSelectedFile());
setSolutionLoaded(e.getSource());
} finally {
setCursor(Cursor.getDefaultCursor());
}
}
}
}
private class SaveAction extends AbstractAction {
private static final String NAME = "Save as...";
private JFileChooser fileChooser;
public SaveAction() {
super(NAME, new ImageIcon(SolverAndPersistenceFrame.class.getResource("saveAction.png")));
fileChooser = new JFileChooser(solutionBusiness.getSolvedDataDir());
final String outputFileExtension = solutionBusiness.getSolutionFileIO().getOutputFileExtension();
fileChooser.setFileFilter(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isDirectory() || file.getName().endsWith("." + outputFileExtension);
}
@Override
public String getDescription() {
return "Solution files (*." + outputFileExtension + ")";
}
});
fileChooser.setDialogTitle(NAME);
}
@Override
public void actionPerformed(ActionEvent e) {
final String outputFileExtension = solutionBusiness.getSolutionFileIO().getOutputFileExtension();
fileChooser.setSelectedFile(new File(solutionBusiness.getSolvedDataDir(),
SolutionBusiness.getBaseFileName(solutionBusiness.getSolutionFileName()) + "." + outputFileExtension));
int approved = fileChooser.showSaveDialog(SolverAndPersistenceFrame.this);
if (approved == JFileChooser.APPROVE_OPTION) {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
solutionBusiness.saveSolution(fileChooser.getSelectedFile());
} finally {
setCursor(Cursor.getDefaultCursor());
}
refreshQuickOpenPanel(quickOpenUnsolvedJList, solutionBusiness.getUnsolvedFileList());
refreshQuickOpenPanel(quickOpenSolvedJList, solutionBusiness.getSolvedFileList());
SolverAndPersistenceFrame.this.validate();
}
}
}
private class ImportAction extends AbstractAction {
private static final String NAME = "Import...";
private final JFileChooser fileChooser;
public ImportAction() {
super(NAME, new ImageIcon(SolverAndPersistenceFrame.class.getResource("importAction.png")));
if (!solutionBusiness.hasImporter()) {
fileChooser = null;
return;
}
fileChooser = new JFileChooser(solutionBusiness.getImportDataDir());
boolean firstFilter = true;
for (final AbstractSolutionImporter importer : solutionBusiness.getImporters()) {
FileFilter filter = new FileFilter() {
@Override
public boolean accept(File file) {
return file.isDirectory() || importer.acceptInputFile(file);
}
@Override
public String getDescription() {
return "Import files (*." + importer.getInputFileSuffix() + ")";
}
};
fileChooser.addChoosableFileFilter(filter);
if (firstFilter) {
fileChooser.setFileFilter(filter);
firstFilter = false;
}
}
fileChooser.setDialogTitle(NAME);
}
@Override
public void actionPerformed(ActionEvent e) {
int approved = fileChooser.showOpenDialog(SolverAndPersistenceFrame.this);
if (approved == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
solutionBusiness.importSolution(file);
setSolutionLoaded(e.getSource());
} finally {
setCursor(Cursor.getDefaultCursor());
}
}
}
}
private class ExportAction extends AbstractAction {
private static final String NAME = "Export as...";
private final JFileChooser fileChooser;
public ExportAction() {
super(NAME, new ImageIcon(SolverAndPersistenceFrame.class.getResource("exportAction.png")));
if (!solutionBusiness.hasExporter()) {
fileChooser = null;
return;
}
fileChooser = new JFileChooser(solutionBusiness.getExportDataDir());
for (AbstractSolutionExporter<Solution_> exporter : solutionBusiness.getExporters()) {
fileChooser.addChoosableFileFilter(new ExporterFileFilter(exporter));
}
fileChooser.setDialogTitle(NAME);
}
@Override
public void actionPerformed(ActionEvent e) {
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.addPropertyChangeListener(
new FileNameSetter(fileChooser,
solutionBusiness.getExportDataDir(),
SolutionBusiness.getBaseFileName(solutionBusiness.getSolutionFileName())));
int approved = fileChooser.showSaveDialog(SolverAndPersistenceFrame.this);
if (approved == JFileChooser.APPROVE_OPTION) {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
AbstractSolutionExporter<Solution_> exporter =
((ExporterFileFilter) fileChooser.getFileFilter()).getExporter();
File exportFile = fileChooser.getSelectedFile();
solutionBusiness.exportSolution(exporter, exportFile);
} finally {
setCursor(Cursor.getDefaultCursor());
}
}
// Reset file name
fileChooser.setSelectedFile(null);
}
}
private JPanel createMiddlePanel() {
middlePanel = new JPanel(new CardLayout());
JPanel usageExplanationPanel = new JPanel(new BorderLayout(5, 5));
ImageIcon usageExplanationIcon = new ImageIcon(getClass().getResource(solutionPanel.getUsageExplanationPath()));
JLabel usageExplanationLabel = new JLabel(usageExplanationIcon);
// Allow splitPane divider to be moved to the right
usageExplanationLabel.setMinimumSize(new Dimension(100, 100));
usageExplanationPanel.add(usageExplanationLabel, BorderLayout.CENTER);
JPanel descriptionPanel = new JPanel(new BorderLayout(2, 2));
descriptionPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
descriptionPanel.add(new JLabel("Example description"), BorderLayout.NORTH);
JTextArea descriptionTextArea = new JTextArea(8, 70);
descriptionTextArea.setEditable(false);
descriptionTextArea.setText(solutionBusiness.getAppDescription());
descriptionPanel.add(new JScrollPane(descriptionTextArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER);
usageExplanationPanel.add(descriptionPanel, BorderLayout.SOUTH);
middlePanel.add(usageExplanationPanel, "usageExplanationPanel");
JComponent wrappedSolutionPanel;
if (solutionPanel.isWrapInScrollPane()) {
wrappedSolutionPanel = new JScrollPane(solutionPanel);
} else {
wrappedSolutionPanel = solutionPanel;
}
middlePanel.add(wrappedSolutionPanel, "solutionPanel");
return middlePanel;
}
private JPanel createScorePanel() {
JPanel scorePanel = new JPanel(new BorderLayout(5, 0));
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
showConstraintMatchesDialogAction = new ShowConstraintMatchesDialogAction();
showConstraintMatchesDialogAction.setEnabled(false);
buttonPanel.add(new JButton(showConstraintMatchesDialogAction));
indictmentHeatMapToggleButton = new JToggleButton(
solutionPanel.isUseIndictmentColor() ? indictmentHeatMapTrueIcon : indictmentHeatMapFalseIcon,
solutionPanel.isUseIndictmentColor());
indictmentHeatMapToggleButton.setEnabled(false);
indictmentHeatMapToggleButton.setToolTipText("Show indictment heat map");
indictmentHeatMapToggleButton.addActionListener(e -> {
boolean selected = indictmentHeatMapToggleButton.isSelected();
indictmentHeatMapToggleButton.setIcon(selected ? indictmentHeatMapTrueIcon : indictmentHeatMapFalseIcon);
solutionPanel.setUseIndictmentColor(selected);
resetScreen();
});
buttonPanel.add(indictmentHeatMapToggleButton);
scorePanel.add(buttonPanel, BorderLayout.WEST);
scoreField = new JTextField("Score:");
scoreField.setEditable(false);
scoreField.setForeground(Color.BLACK);
scoreField.setBorder(BorderFactory.createLoweredBevelBorder());
scorePanel.add(scoreField, BorderLayout.CENTER);
refreshScreenDuringSolvingToggleButton = new JToggleButton(refreshScreenDuringSolvingTrueIcon, true);
refreshScreenDuringSolvingToggleButton.setToolTipText("Refresh screen during solving");
refreshScreenDuringSolvingToggleButton.addActionListener(e -> {
refreshScreenDuringSolvingToggleButton
.setIcon(refreshScreenDuringSolvingToggleButton.isSelected() ? refreshScreenDuringSolvingTrueIcon
: refreshScreenDuringSolvingFalseIcon);
});
scorePanel.add(refreshScreenDuringSolvingToggleButton, BorderLayout.EAST);
return scorePanel;
}
private class ShowConstraintMatchesDialogAction extends AbstractAction {
public ShowConstraintMatchesDialogAction() {
super("Constraint matches",
new ImageIcon(SolverAndPersistenceFrame.class.getResource("showConstraintMatchesDialogAction.png")));
}
@Override
public void actionPerformed(ActionEvent e) {
constraintMatchesDialog.resetContentPanel();
constraintMatchesDialog.setVisible(true);
}
}
public void setSolutionLoaded(Object eventSource) {
if (eventSource != quickOpenUnsolvedJList) {
quickOpenUnsolvedJList.clearSelection();
}
if (eventSource != quickOpenSolvedJList) {
quickOpenSolvedJList.clearSelection();
}
setTitle(solutionBusiness.getAppName() + " - " + solutionBusiness.getSolutionFileName());
((CardLayout) middlePanel.getLayout()).show(middlePanel, "solutionPanel");
setSolvingState(false);
resetScreen();
}
private void setSolvingState(boolean solving) {
quickOpenUnsolvedJList.setEnabled(!solving);
quickOpenSolvedJList.setEnabled(!solving);
if (solutionBusiness.hasImporter()) {
importAction.setEnabled(!solving);
}
openAction.setEnabled(!solving);
saveAction.setEnabled(!solving);
if (solutionBusiness.hasExporter()) {
exportAction.setEnabled(!solving);
}
solveAction.setEnabled(!solving);
solveButton.setVisible(!solving);
terminateSolvingEarlyAction.setEnabled(solving);
terminateSolvingEarlyButton.setVisible(solving);
if (solving) {
terminateSolvingEarlyButton.requestFocus();
} else {
solveButton.requestFocus();
}
solutionPanel.setEnabled(!solving);
progressBar.setIndeterminate(solving);
progressBar.setStringPainted(solving);
progressBar.setString(solving ? "Solving..." : null);
indictmentHeatMapToggleButton.setEnabled(solutionPanel.isIndictmentHeatMapEnabled() && !solving);
showConstraintMatchesDialogAction.setEnabled(!solving);
}
public void resetScreen() {
Solution_ solution = solutionBusiness.getSolution();
Score score = solutionBusiness.getScore();
solutionPanel.resetPanel(solution);
validate();
refreshScoreField(score);
}
public void refreshScoreField(Score score) {
scoreField.setForeground(determineScoreFieldForeground(score));
scoreField.setText("Latest best score: " + score);
}
private Color determineScoreFieldForeground(Score<?> score) {
if (!score.isSolutionInitialized()) {
return TangoColorFactory.SCARLET_3;
} else {
return score.isFeasible() ? TangoColorFactory.CHAMELEON_3 : TangoColorFactory.ORANGE_3;
}
}
private final class ExporterFileFilter extends FileFilter {
private final AbstractSolutionExporter<Solution_> exporter;
public ExporterFileFilter(AbstractSolutionExporter<Solution_> exporter) {
this.exporter = exporter;
}
@Override
public boolean accept(File file) {
return file.isDirectory() || file.getName().endsWith("." + exporter.getOutputFileSuffix());
}
@Override
public String getDescription() {
return "Export files (*." + exporter.getOutputFileSuffix() + ")";
}
public AbstractSolutionExporter<Solution_> getExporter() {
return exporter;
}
}
// Does the creation of the file name + setting it in the file chooser
private final class FileNameSetter implements PropertyChangeListener {
private JFileChooser fileChooser;
private File exportDataDir;
private String baseName;
public FileNameSetter(JFileChooser fileChooser, File exportDataDir, String baseName) {
this.fileChooser = fileChooser;
this.exportDataDir = exportDataDir;
this.baseName = baseName;
setFileName();
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
String prop = evt.getPropertyName();
//If a file became selected, find out which one.
if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
File file = (File) evt.getNewValue();
if (file == null) {
setFileName();
}
} else if (prop.equals(JFileChooser.FILE_FILTER_CHANGED_PROPERTY)) {
setFileName();
}
}
void setFileName() {
AbstractSolutionExporter<Solution_> exporter = ((ExporterFileFilter) fileChooser.getFileFilter()).getExporter();
fileChooser.setSelectedFile(
new File(this.exportDataDir, this.baseName + "." + exporter.getOutputFileSuffix()));
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/swingui | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/swingui/components/Labeled.java | package ai.timefold.solver.examples.common.swingui.components;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* @see LabeledComboBoxRenderer
*/
public interface Labeled {
@JsonIgnore
String getLabel();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/swingui | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/swingui/components/LabeledComboBoxRenderer.java | package ai.timefold.solver.examples.common.swingui.components;
import java.awt.Component;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
/**
* Display the user-friendly {@link Labeled#getLabel()} instead of the developer-friendly {@link Object#toString()}.
*/
public class LabeledComboBoxRenderer implements ListCellRenderer {
public static void applyToComboBox(JComboBox comboBox) {
comboBox.setRenderer(new LabeledComboBoxRenderer(comboBox.getRenderer()));
}
private final ListCellRenderer originalListCellRenderer;
public LabeledComboBoxRenderer(ListCellRenderer originalListCellRenderer) {
this.originalListCellRenderer = originalListCellRenderer;
}
@Override
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
String label = (value == null) ? "" : ((Labeled) value).getLabel();
return originalListCellRenderer.getListCellRendererComponent(list, label, index, isSelected, cellHasFocus);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/swingui | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/swingui/latitudelongitude/LatitudeLongitudeTranslator.java | package ai.timefold.solver.examples.common.swingui.latitudelongitude;
import java.awt.Graphics2D;
import java.awt.geom.CubicCurve2D;
import ai.timefold.solver.swing.impl.TangoColorFactory;
public final class LatitudeLongitudeTranslator {
public static final double MARGIN_RATIO = 0.04;
private double minimumLatitude = Double.MAX_VALUE;
private double maximumLatitude = -Double.MAX_VALUE;
private double minimumLongitude = Double.MAX_VALUE;
private double maximumLongitude = -Double.MAX_VALUE;
private double latitudeLength = 0.0;
private double longitudeLength = 0.0;
private double innerWidth = 0.0;
private double innerHeight = 0.0;
private double innerWidthMargin = 0.0;
private double innerHeightMargin = 0.0;
private int imageWidth = -1;
private int imageHeight = -1;
public void addCoordinates(double latitude, double longitude) {
if (latitude < minimumLatitude) {
minimumLatitude = latitude;
}
if (latitude > maximumLatitude) {
maximumLatitude = latitude;
}
if (longitude < minimumLongitude) {
minimumLongitude = longitude;
}
if (longitude > maximumLongitude) {
maximumLongitude = longitude;
}
}
public void prepareFor(double width, double height) {
latitudeLength = maximumLatitude - minimumLatitude;
longitudeLength = maximumLongitude - minimumLongitude;
innerWidthMargin = width * MARGIN_RATIO;
innerHeightMargin = height * MARGIN_RATIO;
innerWidth = width - (2.0 * innerWidthMargin);
innerHeight = height - (2.0 * innerHeightMargin);
// Keep ratio visually correct
if (innerWidth > innerHeight * longitudeLength / latitudeLength) {
innerWidth = innerHeight * longitudeLength / latitudeLength;
} else {
innerHeight = innerWidth * latitudeLength / longitudeLength;
}
imageWidth = (int) Math.floor((2.0 * innerWidthMargin) + innerWidth);
imageHeight = (int) Math.floor((2.0 * innerHeightMargin) + innerHeight);
}
public int translateLongitudeToX(double longitude) {
return (int) Math.floor(((longitude - minimumLongitude) * innerWidth / longitudeLength) + innerWidthMargin);
}
public int translateLatitudeToY(double latitude) {
return (int) Math.floor(((maximumLatitude - latitude) * innerHeight / latitudeLength) + innerHeightMargin);
}
public double translateXToLongitude(int x) {
return minimumLongitude + ((x - innerWidthMargin) * longitudeLength / innerWidth);
}
public double translateYToLatitude(double y) {
return maximumLatitude - ((y - innerHeightMargin) * latitudeLength / innerHeight);
}
public int getImageWidth() {
return imageWidth;
}
public int getImageHeight() {
return imageHeight;
}
public void drawRoute(Graphics2D g, double lon1, double lat1, double lon2, double lat2, boolean straight, boolean dashed) {
int x1 = translateLongitudeToX(lon1);
int y1 = translateLatitudeToY(lat1);
int x2 = translateLongitudeToX(lon2);
int y2 = translateLatitudeToY(lat2);
if (dashed) {
g.setStroke(TangoColorFactory.FAT_DASHED_STROKE);
}
if (straight) {
g.drawLine(x1, y1, x2, y2);
} else {
double xDistPart = (x2 - x1) / 3.0;
double yDistPart = (y2 - y1) / 3.0;
double ctrlx1 = x1 + xDistPart + yDistPart;
double ctrly1 = y1 - xDistPart + yDistPart;
double ctrlx2 = x2 - xDistPart - yDistPart;
double ctrly2 = y2 + xDistPart - yDistPart;
g.draw(new CubicCurve2D.Double(x1, y1, ctrlx1, ctrly1, ctrlx2, ctrly2, x2, y2));
}
if (dashed) {
g.setStroke(TangoColorFactory.NORMAL_STROKE);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/swingui | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/swingui/timetable/TimeTableLayout.java | package ai.timefold.solver.examples.common.swingui.timetable;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
final class TimeTableLayout implements LayoutManager2 {
public static final int FILL_COLLISIONS_FLAG = -1;
private List<Column> columns;
private List<Row> rows;
private List<List<Cell>> cells;
private Map<Component, ComponentSpan> spanMap;
private boolean stale;
private int totalColumnWidth;
private int totalRowHeight;
public TimeTableLayout() {
reset();
}
public void reset() {
columns = new ArrayList<>();
rows = new ArrayList<>();
cells = new ArrayList<>();
spanMap = new HashMap<>();
stale = false;
totalColumnWidth = 0;
totalRowHeight = 0;
}
public int addColumn() {
return addColumn(true, 0);
}
public int addColumn(int baseWidth) {
if (baseWidth < 0) {
throw new IllegalArgumentException("Invalid baseWidth (" + baseWidth + ").");
}
return addColumn(false, baseWidth);
}
private int addColumn(boolean autoWidth, int baseWidth) {
if (rows.size() > 0) {
throw new IllegalStateException("Add all columns before adding rows");
}
stale = true;
int index = columns.size();
Column column = new Column(index, autoWidth, baseWidth);
columns.add(column);
cells.add(new ArrayList<>());
return index;
}
public int addRow() {
return addRow(true, 0);
}
public int addRow(int baseHeight) {
if (baseHeight < 0) {
throw new IllegalArgumentException("Invalid baseHeight (" + baseHeight + ").");
}
return addRow(false, baseHeight);
}
public int addRow(boolean autoHeight, int baseHeight) {
stale = true;
int index = rows.size();
Row row = new Row(index, autoHeight, baseHeight);
rows.add(row);
for (int i = 0; i < columns.size(); i++) {
Column column = columns.get(i);
cells.get(i).add(new Cell(column, row));
}
return index;
}
@Override
public void addLayoutComponent(Component component, Object o) {
TimeTableLayoutConstraints c = (TimeTableLayoutConstraints) o;
if (c.getXEnd() > columns.size()) {
throw new IllegalArgumentException("The xEnd (" + c.getXEnd()
+ ") is > columnsSize (" + columns.size() + ").");
}
if (c.getYEnd() > rows.size()) {
throw new IllegalArgumentException("The yEnd (" + c.getYEnd()
+ ") is > rowsSize (" + rows.size() + ").");
}
stale = true;
ComponentSpan span = new ComponentSpan(component);
spanMap.put(component, span);
span.topLeftCell = cells.get(c.getX()).get(c.getY());
span.bottomRightCell = cells.get(c.getXEnd() - 1).get(c.getYEnd() - 1);
Set<Integer> occupiedCollisionIndexes = new HashSet<>();
for (int i = c.getX(); i < c.getXEnd(); i++) {
for (int j = c.getY(); j < c.getYEnd(); j++) {
Cell cell = cells.get(i).get(j);
cell.column.stale = true;
cell.row.stale = true;
cell.spans.add(span);
span.cells.add(cell);
occupiedCollisionIndexes.addAll(cell.occupiedCollisionIndexes);
}
}
Integer collisionIndex = 0;
while (occupiedCollisionIndexes.contains(collisionIndex)) {
collisionIndex++;
}
if (c.isFillCollisions()) {
if (collisionIndex != 0 || occupiedCollisionIndexes.contains(FILL_COLLISIONS_FLAG)) {
throw new IllegalArgumentException("There is a collision in the cell range ("
+ (c.getX() == c.getXEnd() - 1 ? c.getX() : c.getX() + "-" + (c.getXEnd() - 1))
+ ", " + (c.getY() == c.getYEnd() - 1 ? c.getY() : c.getY() + "-" + (c.getYEnd() - 1))
+ ").");
}
collisionIndex = FILL_COLLISIONS_FLAG;
}
span.collisionIndex = collisionIndex;
for (Cell cell : span.cells) {
cell.occupiedCollisionIndexes.add(collisionIndex);
}
}
@Override
public void addLayoutComponent(String name, Component component) {
// No effect
}
@Override
public void removeLayoutComponent(Component component) {
stale = true;
ComponentSpan span = spanMap.remove(component);
for (Cell cell : span.cells) {
cell.spans.remove(span);
cell.column.stale = true;
cell.row.stale = true;
cell.occupiedCollisionIndexes.remove(span.collisionIndex);
}
}
@Override
public Dimension minimumLayoutSize(Container parent) {
update();
return new Dimension(totalColumnWidth, totalRowHeight);
}
@Override
public Dimension preferredLayoutSize(Container parent) {
update();
return new Dimension(totalColumnWidth, totalRowHeight);
}
@Override
public Dimension maximumLayoutSize(Container target) {
update();
return new Dimension(totalColumnWidth, totalRowHeight);
}
@Override
public float getLayoutAlignmentX(Container target) {
return 0.5f;
}
@Override
public float getLayoutAlignmentY(Container target) {
return 0.5f;
}
@Override
public void invalidateLayout(Container target) {
// No effect
}
@Override
public void layoutContainer(Container parent) {
update();
synchronized (parent.getTreeLock()) {
for (ComponentSpan span : spanMap.values()) {
int x1 = span.topLeftCell.column.boundX;
int collisionIndexStart = (span.collisionIndex == FILL_COLLISIONS_FLAG)
? 0
: span.collisionIndex;
int y1 = span.topLeftCell.row.boundY + (collisionIndexStart * span.topLeftCell.row.baseHeight);
int x2 = span.bottomRightCell.column.boundX + span.bottomRightCell.column.baseWidth;
int collisionIndexEnd = (span.collisionIndex == FILL_COLLISIONS_FLAG)
? span.bottomRightCell.row.collisionCount
: span.collisionIndex + 1;
int y2 = span.bottomRightCell.row.boundY + (collisionIndexEnd * span.bottomRightCell.row.baseHeight);
span.component.setBounds(x1, y1, x2 - x1, y2 - y1);
}
}
}
public void update() {
if (!stale) {
return;
}
refreshColumns();
refreshRows();
stale = false;
}
private void refreshColumns() {
for (Column column : columns) {
if (column.stale) {
if (column.autoWidth) {
column.baseWidth = getMaxCellWidth(column);
}
column.stale = false;
}
}
refreshColumnsBoundX();
}
private int getMaxCellWidth(Column column) {
int maxCellWidth = 0;
for (int i = 0; i < rows.size(); i++) {
Cell cell = cells.get(column.index).get(i);
for (ComponentSpan span : cell.spans) {
int width = span.getPreferredWidthPerCell();
if (width > maxCellWidth) {
maxCellWidth = width;
}
}
}
return maxCellWidth;
}
private void refreshColumnsBoundX() {
int nextColumnBoundX = 0;
for (Column column : columns) {
column.boundX = nextColumnBoundX;
nextColumnBoundX += column.baseWidth;
}
totalColumnWidth = nextColumnBoundX;
}
private void refreshRows() {
for (Row row : rows) {
if (row.stale) {
if (row.autoHeight) {
row.baseHeight = getMaxCellHeight(row);
}
row.collisionCount = getMaxCollisionCount(row);
}
row.stale = false;
}
freshRowsBoundY();
}
private int getMaxCellHeight(Row row) {
int maxCellHeight = 0;
for (int i = 0; i < columns.size(); i++) {
Cell cell = cells.get(i).get(row.index);
for (ComponentSpan span : cell.spans) {
int height = span.getPreferredHeightPerCell();
if (height > maxCellHeight) {
maxCellHeight = height;
}
}
}
return maxCellHeight;
}
private int getMaxCollisionCount(Row row) {
int maxCollisionCount = 1;
for (int i = 0; i < columns.size(); i++) {
Cell cell = cells.get(i).get(row.index);
if (cell.occupiedCollisionIndexes.size() > maxCollisionCount) {
maxCollisionCount = cell.occupiedCollisionIndexes.size();
}
}
return maxCollisionCount;
}
private void freshRowsBoundY() {
int nextRowBoundY = 0;
for (Row row : rows) {
row.boundY = nextRowBoundY;
nextRowBoundY += row.baseHeight * row.collisionCount;
}
totalRowHeight = nextRowBoundY;
}
private static final class Column {
private final int index;
private final boolean autoWidth;
private boolean stale;
private int baseWidth;
private int boundX = -1;
private Column(int index, boolean autoWidth, int baseWidth) {
this.index = index;
this.autoWidth = autoWidth;
stale = true;
this.baseWidth = baseWidth;
}
}
private static final class Row {
private final int index;
private final boolean autoHeight;
private boolean stale;
private int baseHeight;
private int collisionCount = 1;
private int boundY = -1;
private Row(int index, boolean autoHeight, int baseHeight) {
this.index = index;
this.autoHeight = autoHeight;
stale = true;
this.baseHeight = baseHeight;
}
}
private static final class Cell {
private final Column column;
private final Row row;
private final Set<ComponentSpan> spans = new HashSet<>();
private final Set<Integer> occupiedCollisionIndexes = new HashSet<>();
private Cell(Column column, Row row) {
this.column = column;
this.row = row;
}
}
private static final class ComponentSpan {
private final Component component;
private final Set<Cell> cells = new HashSet<>();
private Cell topLeftCell;
private Cell bottomRightCell;
private Integer collisionIndex;
private ComponentSpan(Component component) {
this.component = component;
}
public int getPreferredWidthPerCell() {
int width = component.getPreferredSize().width;
int horizontalCellSize = bottomRightCell.column.index - topLeftCell.column.index + 1;
return (width + (horizontalCellSize - 1)) / horizontalCellSize; // Ceil rounding
}
public int getPreferredHeightPerCell() {
int height = component.getPreferredSize().height;
int verticalCellSize = bottomRightCell.row.index - topLeftCell.row.index + 1;
return (height + (verticalCellSize - 1)) / verticalCellSize; // Ceil rounding
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/swingui | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/swingui/timetable/TimeTableLayoutConstraints.java | package ai.timefold.solver.examples.common.swingui.timetable;
final class TimeTableLayoutConstraints {
private final int x;
private final int y;
private final int width;
private final int height;
private final boolean fillCollisions;
public TimeTableLayoutConstraints(int x, int y) {
this(x, y, 1, 1, false);
}
public TimeTableLayoutConstraints(int x, int y, int width, int height) {
this(x, y, width, height, false);
}
public TimeTableLayoutConstraints(int x, int y, boolean fillCollisions) {
this(x, y, 1, 1, fillCollisions);
}
public TimeTableLayoutConstraints(int x, int y, int width, int height, boolean fillCollisions) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.fillCollisions = fillCollisions;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public boolean isFillCollisions() {
return fillCollisions;
}
public int getXEnd() {
return x + width;
}
public int getYEnd() {
return y + height;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/swingui | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/common/swingui/timetable/TimeTablePanel.java | package ai.timefold.solver.examples.common.swingui.timetable;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JViewport;
import javax.swing.Scrollable;
import ai.timefold.solver.examples.common.swingui.SolutionPanel;
public final class TimeTablePanel<XObject, YObject> extends JPanel implements Scrollable {
private final TimeTableLayout layout = new TimeTableLayout();
private final Map<Object, Integer> xMap = new HashMap<>();
private final Map<Object, Integer> yMap = new HashMap<>();
public TimeTablePanel() {
setLayout(layout);
}
public void reset() {
removeAll();
layout.reset();
xMap.clear();
yMap.clear();
}
// ************************************************************************
// Define methods
// ************************************************************************
public void defineColumnHeaderByKey(HeaderColumnKey xObject) {
int x = layout.addColumn();
xMap.put(xObject, x);
}
public void defineColumnHeader(XObject xObject) {
int x = layout.addColumn();
xMap.put(xObject, x);
}
public void defineColumnHeader(XObject xObject, int width) {
int x = layout.addColumn(width);
xMap.put(xObject, x);
}
public void defineRowHeaderByKey(HeaderRowKey yObject) {
int y = layout.addRow();
yMap.put(yObject, y);
}
public void defineRowHeader(YObject yObject) {
int y = layout.addRow();
yMap.put(yObject, y);
}
public void defineRowHeader(YObject yObject, int height) {
int y = layout.addRow(height);
yMap.put(yObject, y);
}
// ************************************************************************
// Add methods
// ************************************************************************
public void addCornerHeader(HeaderColumnKey xObject, HeaderRowKey yObject, JComponent component) {
int x = xMap.get(xObject);
int y = yMap.get(yObject);
add(component, new TimeTableLayoutConstraints(x, y, true));
}
public void addColumnHeader(XObject xObject, HeaderRowKey yObject, JComponent component) {
int x = xMap.get(xObject);
int y = yMap.get(yObject);
add(component, new TimeTableLayoutConstraints(x, y, true));
}
public void addColumnHeader(XObject xObject1, HeaderRowKey yObject1, XObject xObject2, HeaderRowKey yObject2,
JComponent component) {
int x1 = xMap.get(xObject1);
int y1 = yMap.get(yObject1);
int x2 = xMap.get(xObject2);
int y2 = yMap.get(yObject2);
add(component, new TimeTableLayoutConstraints(x1, y1, x2 - x1 + 1, y2 - y1 + 1, true));
}
public void addRowHeader(HeaderColumnKey xObject, YObject yObject, JComponent component) {
int x = xMap.get(xObject);
int y = yMap.get(yObject);
add(component, new TimeTableLayoutConstraints(x, y, true));
}
public void addRowHeader(HeaderColumnKey xObject1, YObject yObject1, HeaderColumnKey xObject2, YObject yObject2,
JComponent component) {
int x1 = xMap.get(xObject1);
int y1 = yMap.get(yObject1);
int x2 = xMap.get(xObject2);
int y2 = yMap.get(yObject2);
add(component, new TimeTableLayoutConstraints(x1, y1, x2 - x1 + 1, y2 - y1 + 1, true));
}
public void addCell(XObject xObject, YObject yObject, JComponent component) {
int x = xMap.get(xObject);
int y = yMap.get(yObject);
add(component, new TimeTableLayoutConstraints(x, y));
}
public void addCell(XObject xObject1, YObject yObject1, XObject xObject2, YObject yObject2, JComponent component) {
int x1 = xMap.get(xObject1);
int y1 = yMap.get(yObject1);
int x2 = xMap.get(xObject2);
int y2 = yMap.get(yObject2);
add(component, new TimeTableLayoutConstraints(x1, y1, x2 - x1 + 1, y2 - y1 + 1));
}
// ************************************************************************
// Scrollable methods
// ************************************************************************
@Override
public Dimension getPreferredScrollableViewportSize() {
return SolutionPanel.PREFERRED_SCROLLABLE_VIEWPORT_SIZE;
}
@Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 20;
}
@Override
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return 20;
}
@Override
public boolean getScrollableTracksViewportWidth() {
if (getParent() instanceof JViewport) {
return (getParent().getWidth() > getPreferredSize().width);
}
return false;
}
@Override
public boolean getScrollableTracksViewportHeight() {
if (getParent() instanceof JViewport) {
return (getParent().getHeight() > getPreferredSize().height);
}
return false;
}
public enum HeaderColumnKey {
HEADER_COLUMN_GROUP2,
HEADER_COLUMN_GROUP1,
HEADER_COLUMN,
HEADER_COLUMN_EXTRA_PROPERTY_1,
HEADER_COLUMN_EXTRA_PROPERTY_2,
HEADER_COLUMN_EXTRA_PROPERTY_3,
HEADER_COLUMN_EXTRA_PROPERTY_4,
HEADER_COLUMN_EXTRA_PROPERTY_5,
TRAILING_HEADER_COLUMN;
}
public enum HeaderRowKey {
HEADER_ROW_GROUP2,
HEADER_ROW_GROUP1,
HEADER_ROW,
TRAILING_HEADER_ROW;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/app/NurseRosteringApp.java | package ai.timefold.solver.examples.nurserostering.app;
import java.util.Collections;
import java.util.Set;
import ai.timefold.solver.examples.common.app.CommonApp;
import ai.timefold.solver.examples.common.persistence.AbstractSolutionExporter;
import ai.timefold.solver.examples.common.persistence.AbstractSolutionImporter;
import ai.timefold.solver.examples.nurserostering.domain.NurseRoster;
import ai.timefold.solver.examples.nurserostering.persistence.NurseRosterSolutionFileIO;
import ai.timefold.solver.examples.nurserostering.persistence.NurseRosteringExporter;
import ai.timefold.solver.examples.nurserostering.persistence.NurseRosteringImporter;
import ai.timefold.solver.examples.nurserostering.swingui.NurseRosteringPanel;
import ai.timefold.solver.persistence.common.api.domain.solution.SolutionFileIO;
public class NurseRosteringApp extends CommonApp<NurseRoster> {
public static final String SOLVER_CONFIG = "ai/timefold/solver/examples/nurserostering/nurseRosteringSolverConfig.xml";
public static final String DATA_DIR_NAME = "nurserostering";
public static void main(String[] args) {
prepareSwingEnvironment();
new NurseRosteringApp().init();
}
public NurseRosteringApp() {
super("Nurse rostering",
"Official competition name: INRC2010 - Nurse rostering\n\n" +
"Assign shifts to nurses.",
SOLVER_CONFIG, DATA_DIR_NAME,
NurseRosteringPanel.LOGO_PATH);
}
@Override
protected NurseRosteringPanel createSolutionPanel() {
return new NurseRosteringPanel();
}
@Override
public SolutionFileIO<NurseRoster> createSolutionFileIO() {
return new NurseRosterSolutionFileIO();
}
@Override
protected Set<AbstractSolutionImporter<NurseRoster>> createSolutionImporters() {
return Collections.singleton(new NurseRosteringImporter());
}
@Override
protected Set<AbstractSolutionExporter<NurseRoster>> createSolutionExporters() {
return Collections.singleton(new NurseRosteringExporter());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/Employee.java | package ai.timefold.solver.examples.nurserostering.domain;
import java.util.Map;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.common.persistence.jackson.KeySerializer;
import ai.timefold.solver.examples.common.swingui.components.Labeled;
import ai.timefold.solver.examples.nurserostering.domain.contract.Contract;
import ai.timefold.solver.examples.nurserostering.domain.request.DayOffRequest;
import ai.timefold.solver.examples.nurserostering.domain.request.DayOnRequest;
import ai.timefold.solver.examples.nurserostering.domain.request.ShiftOffRequest;
import ai.timefold.solver.examples.nurserostering.domain.request.ShiftOnRequest;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class Employee extends AbstractPersistable implements Labeled, Comparable<Employee> {
private String code;
private String name;
private Contract contract;
public Employee() {
}
public Employee(long id, String code, String name, Contract contract) {
super(id);
this.code = code;
this.name = name;
this.contract = contract;
}
@JsonSerialize(keyUsing = KeySerializer.class)
@JsonDeserialize(keyUsing = ShiftDateKeyDeserializer.class)
private Map<ShiftDate, DayOffRequest> dayOffRequestMap;
@JsonSerialize(keyUsing = KeySerializer.class)
@JsonDeserialize(keyUsing = ShiftDateKeyDeserializer.class)
private Map<ShiftDate, DayOnRequest> dayOnRequestMap;
@JsonSerialize(keyUsing = KeySerializer.class)
@JsonDeserialize(keyUsing = ShiftKeyDeserializer.class)
private Map<Shift, ShiftOffRequest> shiftOffRequestMap;
@JsonSerialize(keyUsing = KeySerializer.class)
@JsonDeserialize(keyUsing = ShiftKeyDeserializer.class)
private Map<Shift, ShiftOnRequest> shiftOnRequestMap;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Contract getContract() {
return contract;
}
public void setContract(Contract contract) {
this.contract = contract;
}
@JsonIgnore
public int getWeekendLength() {
return getContract().getWeekendLength();
}
public Map<ShiftDate, DayOffRequest> getDayOffRequestMap() {
return dayOffRequestMap;
}
public void setDayOffRequestMap(Map<ShiftDate, DayOffRequest> dayOffRequestMap) {
this.dayOffRequestMap = dayOffRequestMap;
}
public Map<ShiftDate, DayOnRequest> getDayOnRequestMap() {
return dayOnRequestMap;
}
public void setDayOnRequestMap(Map<ShiftDate, DayOnRequest> dayOnRequestMap) {
this.dayOnRequestMap = dayOnRequestMap;
}
public Map<Shift, ShiftOffRequest> getShiftOffRequestMap() {
return shiftOffRequestMap;
}
public void setShiftOffRequestMap(Map<Shift, ShiftOffRequest> shiftOffRequestMap) {
this.shiftOffRequestMap = shiftOffRequestMap;
}
public Map<Shift, ShiftOnRequest> getShiftOnRequestMap() {
return shiftOnRequestMap;
}
public void setShiftOnRequestMap(Map<Shift, ShiftOnRequest> shiftOnRequestMap) {
this.shiftOnRequestMap = shiftOnRequestMap;
}
@Override
public String getLabel() {
return "Employee " + name;
}
@Override
public String toString() {
if (name == null) {
return super.toString();
}
return name;
}
@Override
public int compareTo(Employee employee) {
return name.compareTo(employee.name);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/NurseRoster.java | package ai.timefold.solver.examples.nurserostering.domain;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty;
import ai.timefold.solver.core.api.domain.solution.PlanningScore;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty;
import ai.timefold.solver.core.api.domain.solution.ProblemFactProperty;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.nurserostering.domain.contract.Contract;
import ai.timefold.solver.examples.nurserostering.domain.contract.ContractLine;
import ai.timefold.solver.examples.nurserostering.domain.contract.PatternContractLine;
import ai.timefold.solver.examples.nurserostering.domain.pattern.Pattern;
import ai.timefold.solver.examples.nurserostering.domain.request.DayOffRequest;
import ai.timefold.solver.examples.nurserostering.domain.request.DayOnRequest;
import ai.timefold.solver.examples.nurserostering.domain.request.ShiftOffRequest;
import ai.timefold.solver.examples.nurserostering.domain.request.ShiftOnRequest;
@PlanningSolution
public class NurseRoster extends AbstractPersistable {
private String code;
public NurseRoster() {
}
public NurseRoster(long id) {
super(id);
}
@ProblemFactProperty
private NurseRosterParametrization nurseRosterParametrization;
@ProblemFactCollectionProperty
private List<Skill> skillList;
@ProblemFactCollectionProperty
private List<ShiftType> shiftTypeList;
@ProblemFactCollectionProperty
private List<ShiftTypeSkillRequirement> shiftTypeSkillRequirementList;
@ProblemFactCollectionProperty
private List<Pattern> patternList;
@ProblemFactCollectionProperty
private List<Contract> contractList;
@ProblemFactCollectionProperty
private List<ContractLine> contractLineList;
@ProblemFactCollectionProperty
private List<PatternContractLine> patternContractLineList;
@ValueRangeProvider
@ProblemFactCollectionProperty
private List<Employee> employeeList;
@ProblemFactCollectionProperty
private List<SkillProficiency> skillProficiencyList;
@ProblemFactCollectionProperty
private List<ShiftDate> shiftDateList;
@ProblemFactCollectionProperty
private List<Shift> shiftList;
@ProblemFactCollectionProperty
private List<DayOffRequest> dayOffRequestList;
@ProblemFactCollectionProperty
private List<DayOnRequest> dayOnRequestList;
@ProblemFactCollectionProperty
private List<ShiftOffRequest> shiftOffRequestList;
@ProblemFactCollectionProperty
private List<ShiftOnRequest> shiftOnRequestList;
@PlanningEntityCollectionProperty
private List<ShiftAssignment> shiftAssignmentList;
@PlanningScore
private HardSoftScore score;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public NurseRosterParametrization getNurseRosterParametrization() {
return nurseRosterParametrization;
}
public void setNurseRosterParametrization(NurseRosterParametrization nurseRosterParametrization) {
this.nurseRosterParametrization = nurseRosterParametrization;
}
public List<Skill> getSkillList() {
return skillList;
}
public void setSkillList(List<Skill> skillList) {
this.skillList = skillList;
}
public List<ShiftType> getShiftTypeList() {
return shiftTypeList;
}
public void setShiftTypeList(List<ShiftType> shiftTypeList) {
this.shiftTypeList = shiftTypeList;
}
public List<ShiftTypeSkillRequirement> getShiftTypeSkillRequirementList() {
return shiftTypeSkillRequirementList;
}
public void setShiftTypeSkillRequirementList(List<ShiftTypeSkillRequirement> shiftTypeSkillRequirementList) {
this.shiftTypeSkillRequirementList = shiftTypeSkillRequirementList;
}
public List<Pattern> getPatternList() {
return patternList;
}
public void setPatternList(List<Pattern> patternList) {
this.patternList = patternList;
}
public List<Contract> getContractList() {
return contractList;
}
public void setContractList(List<Contract> contractList) {
this.contractList = contractList;
}
public List<ContractLine> getContractLineList() {
return contractLineList;
}
public void setContractLineList(List<ContractLine> contractLineList) {
this.contractLineList = contractLineList;
}
public List<PatternContractLine> getPatternContractLineList() {
return patternContractLineList;
}
public void setPatternContractLineList(List<PatternContractLine> patternContractLineList) {
this.patternContractLineList = patternContractLineList;
}
public List<Employee> getEmployeeList() {
return employeeList;
}
public void setEmployeeList(List<Employee> employeeList) {
this.employeeList = employeeList;
}
public List<SkillProficiency> getSkillProficiencyList() {
return skillProficiencyList;
}
public void setSkillProficiencyList(List<SkillProficiency> skillProficiencyList) {
this.skillProficiencyList = skillProficiencyList;
}
public List<ShiftDate> getShiftDateList() {
return shiftDateList;
}
public void setShiftDateList(List<ShiftDate> shiftDateList) {
this.shiftDateList = shiftDateList;
}
public List<Shift> getShiftList() {
return shiftList;
}
public void setShiftList(List<Shift> shiftList) {
this.shiftList = shiftList;
}
public List<DayOffRequest> getDayOffRequestList() {
return dayOffRequestList;
}
public void setDayOffRequestList(List<DayOffRequest> dayOffRequestList) {
this.dayOffRequestList = dayOffRequestList;
}
public List<DayOnRequest> getDayOnRequestList() {
return dayOnRequestList;
}
public void setDayOnRequestList(List<DayOnRequest> dayOnRequestList) {
this.dayOnRequestList = dayOnRequestList;
}
public List<ShiftOffRequest> getShiftOffRequestList() {
return shiftOffRequestList;
}
public void setShiftOffRequestList(List<ShiftOffRequest> shiftOffRequestList) {
this.shiftOffRequestList = shiftOffRequestList;
}
public List<ShiftOnRequest> getShiftOnRequestList() {
return shiftOnRequestList;
}
public void setShiftOnRequestList(List<ShiftOnRequest> shiftOnRequestList) {
this.shiftOnRequestList = shiftOnRequestList;
}
public List<ShiftAssignment> getShiftAssignmentList() {
return shiftAssignmentList;
}
public void setShiftAssignmentList(List<ShiftAssignment> shiftAssignmentList) {
this.shiftAssignmentList = shiftAssignmentList;
}
public HardSoftScore getScore() {
return score;
}
public void setScore(HardSoftScore score) {
this.score = score;
}
// ************************************************************************
// Complex methods
// ************************************************************************
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/NurseRosterParametrization.java | package ai.timefold.solver.examples.nurserostering.domain;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class NurseRosterParametrization extends AbstractPersistable {
private ShiftDate firstShiftDate;
private ShiftDate lastShiftDate;
private ShiftDate planningWindowStart;
public NurseRosterParametrization() {
}
public NurseRosterParametrization(long id, ShiftDate firstShiftDate, ShiftDate lastShiftDate,
ShiftDate planningWindowStart) {
super(id);
this.firstShiftDate = firstShiftDate;
this.lastShiftDate = lastShiftDate;
this.planningWindowStart = planningWindowStart;
}
public ShiftDate getFirstShiftDate() {
return firstShiftDate;
}
public void setFirstShiftDate(ShiftDate firstShiftDate) {
this.firstShiftDate = firstShiftDate;
}
public ShiftDate getLastShiftDate() {
return lastShiftDate;
}
public void setLastShiftDate(ShiftDate lastShiftDate) {
this.lastShiftDate = lastShiftDate;
}
@JsonIgnore
public int getFirstShiftDateDayIndex() {
return firstShiftDate.getDayIndex();
}
@JsonIgnore
public int getLastShiftDateDayIndex() {
return lastShiftDate.getDayIndex();
}
public ShiftDate getPlanningWindowStart() {
return planningWindowStart;
}
public void setPlanningWindowStart(ShiftDate planningWindowStart) {
this.planningWindowStart = planningWindowStart;
}
// ************************************************************************
// Worker methods
// ************************************************************************
public boolean isInPlanningWindow(ShiftDate shiftDate) {
return planningWindowStart.getDayIndex() <= shiftDate.getDayIndex();
}
@Override
public String toString() {
return firstShiftDate + " - " + lastShiftDate;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/Shift.java | package ai.timefold.solver.examples.nurserostering.domain;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.common.swingui.components.Labeled;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class Shift extends AbstractPersistable implements Labeled {
private ShiftDate shiftDate;
private ShiftType shiftType;
private int index;
private int requiredEmployeeSize;
public Shift() {
}
public Shift(long id) {
super(id);
}
public Shift(long id, ShiftDate shiftDate, ShiftType shiftType, int index, int requiredEmployeeSize) {
this(id);
this.shiftDate = shiftDate;
this.shiftType = shiftType;
this.index = index;
this.requiredEmployeeSize = requiredEmployeeSize;
}
public ShiftDate getShiftDate() {
return shiftDate;
}
public void setShiftDate(ShiftDate shiftDate) {
this.shiftDate = shiftDate;
}
public ShiftType getShiftType() {
return shiftType;
}
public void setShiftType(ShiftType shiftType) {
this.shiftType = shiftType;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public int getRequiredEmployeeSize() {
return requiredEmployeeSize;
}
public void setRequiredEmployeeSize(int requiredEmployeeSize) {
this.requiredEmployeeSize = requiredEmployeeSize;
}
@Override
public String getLabel() {
return shiftType.getLabel() + " of " + shiftDate.getLabel();
}
@Override
public String toString() {
return shiftDate + "/" + shiftType;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/ShiftAssignment.java | package ai.timefold.solver.examples.nurserostering.domain;
import java.time.DayOfWeek;
import java.util.Comparator;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.nurserostering.domain.contract.Contract;
import ai.timefold.solver.examples.nurserostering.domain.solver.EmployeeStrengthComparator;
import ai.timefold.solver.examples.nurserostering.domain.solver.ShiftAssignmentDifficultyComparator;
import ai.timefold.solver.examples.nurserostering.domain.solver.ShiftAssignmentPinningFilter;
import com.fasterxml.jackson.annotation.JsonIgnore;
@PlanningEntity(pinningFilter = ShiftAssignmentPinningFilter.class,
difficultyComparatorClass = ShiftAssignmentDifficultyComparator.class)
public class ShiftAssignment extends AbstractPersistable implements Comparable<ShiftAssignment> {
private static final Comparator<Shift> COMPARATOR = Comparator.comparing(Shift::getShiftDate)
.thenComparing(a -> a.getShiftType().getStartTimeString())
.thenComparing(a -> a.getShiftType().getEndTimeString());
private Shift shift;
private int indexInShift;
public ShiftAssignment() {
}
public ShiftAssignment(long id, Shift shift, int indexInShift) {
super(id);
this.shift = shift;
this.indexInShift = indexInShift;
}
// Planning variables: changes during planning, between score calculations.
@PlanningVariable(strengthComparatorClass = EmployeeStrengthComparator.class)
private Employee employee;
public Shift getShift() {
return shift;
}
public void setShift(Shift shift) {
this.shift = shift;
}
public int getIndexInShift() {
return indexInShift;
}
public void setIndexInShift(int indexInShift) {
this.indexInShift = indexInShift;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
// ************************************************************************
// Complex methods
// ************************************************************************
@JsonIgnore
public ShiftDate getShiftDate() {
return shift.getShiftDate();
}
@JsonIgnore
public ShiftType getShiftType() {
return shift.getShiftType();
}
@JsonIgnore
public int getShiftDateDayIndex() {
return shift.getShiftDate().getDayIndex();
}
@JsonIgnore
public DayOfWeek getShiftDateDayOfWeek() {
return shift.getShiftDate().getDayOfWeek();
}
@JsonIgnore
public Contract getContract() {
if (employee == null) {
return null;
}
return employee.getContract();
}
@JsonIgnore
public boolean isWeekend() {
if (employee == null) {
return false;
}
WeekendDefinition weekendDefinition = employee.getContract().getWeekendDefinition();
DayOfWeek dayOfWeek = shift.getShiftDate().getDayOfWeek();
return weekendDefinition.isWeekend(dayOfWeek);
}
@JsonIgnore
public int getWeekendSundayIndex() {
return shift.getShiftDate().getWeekendSundayIndex();
}
@Override
public String toString() {
return shift.toString();
}
@Override
public int compareTo(ShiftAssignment o) {
return COMPARATOR.compare(shift, o.shift);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/ShiftDate.java | package ai.timefold.solver.examples.nurserostering.domain;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.common.swingui.components.Labeled;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class ShiftDate extends AbstractPersistable implements Labeled, Comparable<ShiftDate> {
private static final DateTimeFormatter LABEL_FORMATTER = DateTimeFormatter.ofPattern("E d MMM");
private int dayIndex; // TODO check if still needed/faster now that we use LocalDate instead of java.util.Date
private LocalDate date;
private List<Shift> shiftList;
public ShiftDate() {
}
public ShiftDate(long id) {
super(id);
}
public ShiftDate(long id, int dayIndex, LocalDate date) {
this(id);
this.dayIndex = dayIndex;
this.date = date;
}
public int getDayIndex() {
return dayIndex;
}
public void setDayIndex(int dayIndex) {
this.dayIndex = dayIndex;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
@JsonIgnore
public DayOfWeek getDayOfWeek() {
return date.getDayOfWeek();
}
public List<Shift> getShiftList() {
return shiftList;
}
public void setShiftList(List<Shift> shiftList) {
this.shiftList = shiftList;
}
@JsonIgnore
public int getWeekendSundayIndex() {
switch (date.getDayOfWeek()) {
case MONDAY:
return dayIndex - 1;
case TUESDAY:
return dayIndex - 2;
case WEDNESDAY:
return dayIndex - 3;
case THURSDAY:
return dayIndex + 3;
case FRIDAY:
return dayIndex + 2;
case SATURDAY:
return dayIndex + 1;
case SUNDAY:
return dayIndex;
default:
throw new IllegalArgumentException("The dayOfWeek (" + date.getDayOfWeek() + ") is not valid.");
}
}
@Override
public String getLabel() {
return date.format(LABEL_FORMATTER);
}
@Override
public String toString() {
return date.format(DateTimeFormatter.ISO_DATE);
}
@Override
public int compareTo(ShiftDate o) {
return this.getDate().compareTo(o.getDate());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/ShiftDateKeyDeserializer.java | package ai.timefold.solver.examples.nurserostering.domain;
import ai.timefold.solver.examples.common.persistence.jackson.AbstractKeyDeserializer;
final class ShiftDateKeyDeserializer extends AbstractKeyDeserializer<ShiftDate> {
public ShiftDateKeyDeserializer() {
super(ShiftDate.class);
}
@Override
protected ShiftDate createInstance(long id) {
return new ShiftDate(id);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/ShiftKeyDeserializer.java | package ai.timefold.solver.examples.nurserostering.domain;
import ai.timefold.solver.examples.common.persistence.jackson.AbstractKeyDeserializer;
final class ShiftKeyDeserializer extends AbstractKeyDeserializer<Shift> {
public ShiftKeyDeserializer() {
super(Shift.class);
}
@Override
protected Shift createInstance(long id) {
return new Shift(id);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/ShiftType.java | package ai.timefold.solver.examples.nurserostering.domain;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.common.swingui.components.Labeled;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class ShiftType extends AbstractPersistable implements Labeled {
private String code;
private int index;
private String startTimeString;
private String endTimeString;
private boolean night;
private String description;
public ShiftType() {
}
public ShiftType(long id) {
super(id);
}
public ShiftType(long id, String code, int index, String startTimeString, String endTimeString, boolean night,
String description) {
super(id);
this.code = code;
this.index = index;
this.startTimeString = startTimeString;
this.endTimeString = endTimeString;
this.night = night;
this.description = description;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getStartTimeString() {
return startTimeString;
}
public void setStartTimeString(String startTimeString) {
this.startTimeString = startTimeString;
}
public String getEndTimeString() {
return endTimeString;
}
public void setEndTimeString(String endTimeString) {
this.endTimeString = endTimeString;
}
public boolean isNight() {
return night;
}
public void setNight(boolean night) {
this.night = night;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String getLabel() {
return code + " (" + description + ")";
}
@Override
public String toString() {
return code;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.