Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions core/src/build/revapi-differences.json
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,17 @@
"code": "java.method.addedToInterface",
"new": "method ai.timefold.solver.core.api.solver.SolverRunResult<Solution_> ai.timefold.solver.core.api.solver.SolverJob<Solution_>::getResult() throws java.lang.InterruptedException, java.util.concurrent.ExecutionException",
"justification": "Return end-of-run statistics; SolverJob is implemented by the solver, not by user code."
},
{
"ignore": true,
"code": "java.annotation.attributeValueChanged",
"old": "class ai.timefold.solver.core.config.score.director.ScoreDirectorFactoryConfig",
"new": "class ai.timefold.solver.core.config.score.director.ScoreDirectorFactoryConfig",
"annotationType": "jakarta.xml.bind.annotation.XmlType",
"attribute": "propOrder",
"oldValue": "{\"easyScoreCalculatorClass\", \"easyScoreCalculatorCustomProperties\", \"constraintProviderClass\", \"constraintProviderCustomProperties\", \"constraintStreamAutomaticNodeSharing\", \"constraintStreamProfilingEnabled\", \"incrementalScoreCalculatorClass\", \"incrementalScoreCalculatorCustomProperties\", \"initializingScoreTrend\", \"assertionScoreDirectorFactory\"}",
"newValue": "{\"easyScoreCalculatorClass\", \"easyScoreCalculatorCustomProperties\", \"constraintProviderClass\", \"constraintProviderCustomProperties\", \"constraintStreamAutomaticNodeSharing\", \"constraintStreamProfilingEnabled\", \"constraintStreamTieredScoreCalculation\", \"incrementalScoreCalculatorClass\", \"incrementalScoreCalculatorCustomProperties\", \"initializingScoreTrend\", \"assertionScoreDirectorFactory\"}",
"justification": "Add new tiered score calculation enterprise feature."
}
]
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"constraintProviderCustomProperties",
"constraintStreamAutomaticNodeSharing",
"constraintStreamProfilingEnabled",
"constraintStreamTieredScoreCalculation",
"incrementalScoreCalculatorClass",
"incrementalScoreCalculatorCustomProperties",
"initializingScoreTrend",
Expand All @@ -43,6 +44,8 @@ public final class ScoreDirectorFactoryConfig extends AbstractConfig<ScoreDirect
@Nullable
private Boolean constraintStreamAutomaticNodeSharing;
private Boolean constraintStreamProfilingEnabled;
@Nullable
private Boolean constraintStreamTieredScoreCalculation;

private String incrementalScoreCalculatorClass = null;

Expand Down Expand Up @@ -110,6 +113,14 @@ public void setConstraintStreamProfilingEnabled(Boolean constraintStreamProfilin
this.constraintStreamProfilingEnabled = constraintStreamProfilingEnabled;
}

public @Nullable Boolean getConstraintStreamTieredScoreCalculation() {
return constraintStreamTieredScoreCalculation;
}

public void setConstraintStreamTieredScoreCalculation(@Nullable Boolean constraintStreamTieredScoreCalculation) {
this.constraintStreamTieredScoreCalculation = constraintStreamTieredScoreCalculation;
}

public @Nullable Class<? extends IncrementalScoreCalculator> getIncrementalScoreCalculatorClass() {
return ConfigUtils.resolveClass(incrementalScoreCalculatorClass, "incrementalScoreCalculatorClass", this);
}
Expand Down Expand Up @@ -187,6 +198,12 @@ public void setAssertionScoreDirectorFactory(@Nullable ScoreDirectorFactoryConfi
return this;
}

public @NonNull ScoreDirectorFactoryConfig
withConstraintStreamTieredScoreCalculation(@NonNull Boolean constraintStreamTieredScoreCalculation) {
this.constraintStreamTieredScoreCalculation = constraintStreamTieredScoreCalculation;
return this;
}

public @NonNull ScoreDirectorFactoryConfig
withIncrementalScoreCalculatorClass(
@NonNull Class<? extends IncrementalScoreCalculator> incrementalScoreCalculatorClass) {
Expand Down Expand Up @@ -226,6 +243,9 @@ public void setAssertionScoreDirectorFactory(@Nullable ScoreDirectorFactoryConfi
inheritedConfig.getConstraintStreamAutomaticNodeSharing());
constraintStreamProfilingEnabled = ConfigUtils.inheritOverwritableProperty(constraintStreamProfilingEnabled,
inheritedConfig.getConstraintStreamProfilingEnabled());
constraintStreamTieredScoreCalculation = ConfigUtils.inheritOverwritableProperty(
constraintStreamTieredScoreCalculation,
inheritedConfig.getConstraintStreamTieredScoreCalculation());
incrementalScoreCalculatorClass = ConfigUtils.inheritOverwritableProperty(
incrementalScoreCalculatorClass, inheritedConfig.incrementalScoreCalculatorClass);
incrementalScoreCalculatorCustomProperties = ConfigUtils.inheritMergeableMapProperty(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,10 @@
import ai.timefold.solver.core.impl.partitionedsearch.PartitionedSearchPhase;
import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchTotal;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
import ai.timefold.solver.core.impl.score.director.AbstractScoreDirector;
import ai.timefold.solver.core.impl.score.director.InnerScore;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.score.director.stream.BavetConstraintStreamScoreDirectorFactory;
import ai.timefold.solver.core.impl.solver.DefaultSolverFactory;
import ai.timefold.solver.core.impl.solver.termination.PhaseTermination;
import ai.timefold.solver.core.impl.solver.termination.SolverTermination;
Expand Down Expand Up @@ -190,6 +192,11 @@ static <T> T loadOrDefault(Function<TimefoldSolverEnterpriseService, T> builder,
*/
ConstraintProviderNodeSharer createNodeSharer();

<Solution_, Score_ extends Score<Score_>>
AbstractScoreDirector.AbstractScoreDirectorBuilder<Solution_, Score_, BavetConstraintStreamScoreDirectorFactory<Solution_, Score_>, ?>
createTieredBavetScoreDirectorBuilder(BavetConstraintStreamScoreDirectorFactory<Solution_, Score_> factory,
EnvironmentMode environmentMode);

<Solution_> ConstructionHeuristicDecider<Solution_> buildConstructionHeuristic(PhaseTermination<Solution_> termination,
ConstructionHeuristicForager<Solution_> forager, HeuristicConfigPolicy<Solution_> configPolicy);

Expand Down Expand Up @@ -255,7 +262,8 @@ enum Feature {
"remove multistageMoveSelector and/or listMultistageMoveSelector from the solver configuration"),
CONSTRAINT_PROFILING("Constraint profiling", "remove constraintStreamProfilingEnabled from the solver configuration"),
SCORE_ANALYSIS("Score analysis", "do not use SolutionManager's analyze() method"),
RECOMMENDATIONS("Recommendations", "do not use SolutionManager's recommendAssignment() method");
RECOMMENDATIONS("Recommendations", "do not use SolutionManager's recommendAssignment() method"),
TIERED_SCORE_CALCULATION("Tiered score calculation", "remove tiered score calculation from solver configuration");

private final String name;
private final String workaround;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,36 +7,42 @@
/**
* A unique identifier for a constraint node profile.
*
* @param key the unique key of the constraint node
* @param key the unique key of the constraint node in a given network
* @param networkId the network the constraint node belongs to
* @param streamKind the kind of stream (e.g., JOIN, FILTER)
* @param qualifier an optional qualifier to distinguish parts of the same node, such as left and right input
* @param locationSet the set of locations where this constraint node is defined
*/
@NullMarked
public record ConstraintNodeProfileId(int key, StreamKind streamKind, Qualifier qualifier,
public record ConstraintNodeProfileId(int key, int networkId, StreamKind streamKind, Qualifier qualifier,
SortedSet<ConstraintNodeLocation> locationSet)
implements
Comparable<ConstraintNodeProfileId> {

public ConstraintNodeProfileId(int key, StreamKind streamKind, SortedSet<ConstraintNodeLocation> locationSet) {
this(key, streamKind, Qualifier.NONE, locationSet);
public ConstraintNodeProfileId(int key, int networkId, StreamKind streamKind,
SortedSet<ConstraintNodeLocation> locationSet) {
this(key, networkId, streamKind, Qualifier.NONE, locationSet);
}

@Override
public boolean equals(Object object) {
if (!(object instanceof ConstraintNodeProfileId that))
return false;
return key == that.key;
return key == that.key && networkId == that.networkId;
}

@Override
public int hashCode() {
return Integer.hashCode(key);
return Long.hashCode(key | ((long) networkId) << Integer.SIZE);
}

@Override
public int compareTo(ConstraintNodeProfileId other) {
return Integer.compare(key, other.key);
var keyComparisonResult = Integer.compare(key, other.key);
if (keyComparisonResult == 0) {
return Integer.compare(networkId, other.networkId);
}
return keyComparisonResult;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ static <Tuple_ extends Tuple> TupleLifecycle<Tuple_> recording() {
}

static <Stream_ extends BavetStream, Tuple_ extends Tuple> TupleLifecycle<Tuple_> profiling(
InnerConstraintProfiler constraintProfiler, int lifecycleId, Stream_ stream,
InnerConstraintProfiler constraintProfiler, int lifecycleId,
int networkId, Stream_ stream,
TupleLifecycle<Tuple_> delegate) {
if (delegate instanceof AggregatedTupleLifecycle) {
// Do not profile aggregated tuple lifecycles; that will double
Expand Down Expand Up @@ -98,7 +99,7 @@ static <Stream_ extends BavetStream, Tuple_ extends Tuple> TupleLifecycle<Tuple_
"Impossible state: encounter tuple lifecycle (%s) which is not a node and is not a known lifecycle implementation."
.formatted(delegate.getClass()));
}
var profileId = new ConstraintNodeProfileId(lifecycleId, streamKind, qualifier, stream.getLocationSet());
var profileId = new ConstraintNodeProfileId(lifecycleId, networkId, streamKind, qualifier, stream.getLocationSet());
return new ProfilingTupleLifecycle<>(constraintProfiler, profileId, delegate);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ protected DefaultConstructionHeuristicPhaseBuilder<Solution_> createBuilder(
return new DefaultConstructionHeuristicPhaseBuilder<>(phaseIndex, lastInitializingPhase,
phaseConfigPolicy.getEnvironmentMode(), phaseConfigPolicy.getLogIndentation(), phaseTermination, entityPlacer,
buildDecider(phaseConfigPolicy, phaseTermination))
.withIsTieredScoreCalculationEnabled(phaseConfigPolicy.isTieredScoreCalculationEnabled())
.enableAssertions();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
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.config.solver.EnvironmentMode;
import ai.timefold.solver.core.impl.constructionheuristic.decider.forager.ConstructionHeuristicForager;
import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicMoveScope;
Expand All @@ -12,10 +13,12 @@
import ai.timefold.solver.core.impl.heuristic.move.SelectorBasedNoChangeMove;
import ai.timefold.solver.core.impl.heuristic.selector.move.generic.SelectorBasedChangeMove;
import ai.timefold.solver.core.impl.phase.scope.SolverLifecyclePoint;
import ai.timefold.solver.core.impl.score.director.InnerScore;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.termination.PhaseTermination;
import ai.timefold.solver.core.preview.api.move.Move;

import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -33,6 +36,8 @@
protected boolean assertMoveScoreFromScratch = false;
protected boolean assertExpectedUndoMoveScore = false;

private @Nullable Score stepMaxScore = null;

public ConstructionHeuristicDecider(String logIndentation, PhaseTermination<Solution_> termination,
ConstructionHeuristicForager<Solution_> forager) {
this.logIndentation = logIndentation;
Expand Down Expand Up @@ -88,6 +93,7 @@
public void decideNextStep(ConstructionHeuristicStepScope<Solution_> stepScope, Iterator<Move<Solution_>> moveIterator) {
var moveIndex = 0;
var terminatedPrematurely = false;
stepMaxScore = null;
while (moveIterator.hasNext()) {
var move = moveIterator.next();
var allowedNonDoableMove = isAllowedNonDoableMove(move);
Expand Down Expand Up @@ -137,7 +143,7 @@

protected void pickMove(ConstructionHeuristicStepScope<Solution_> stepScope) {
var pickedMoveScope = forager.pickMove(stepScope);
if (pickedMoveScope != null) {

Check warning on line 146 in core/src/main/java/ai/timefold/solver/core/impl/constructionheuristic/decider/ConstructionHeuristicDecider.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove this expression which always evaluates to "true"

See more on https://sonarcloud.io/project/issues?id=ai.timefold%3Atimefold-solver&issues=AaDVNCrl8plyudwPpIdF&open=AaDVNCrl8plyudwPpIdF&pullRequest=2694
var step = pickedMoveScope.getMove();
stepScope.setStep(step);
if (isLoggingEnabled() && logger.isDebugEnabled()) {
Expand All @@ -147,9 +153,13 @@
}
}

protected void doMove(ConstructionHeuristicMoveScope<Solution_> moveScope) {
var scoreDirector = moveScope.getScoreDirector();
var score = scoreDirector.executeTemporaryMove(moveScope.getMove(), assertMoveScoreFromScratch);
protected <Score_ extends Score<Score_>> void doMove(ConstructionHeuristicMoveScope<Solution_> moveScope) {
var scoreDirector = moveScope.<Score_> getScoreDirector();
InnerScore<?> score;
score = scoreDirector.executeTemporaryMove(moveScope.getMove(), (Score_) stepMaxScore, assertMoveScoreFromScratch);
if (!score.isStructurallyFlawed() && (stepMaxScore == null || ((Score) score.raw()).compareTo(stepMaxScore) > 0)) {
stepMaxScore = score.raw();
}
moveScope.setScore(score);
forager.addMove(moveScope);
if (assertExpectedUndoMoveScore) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@
import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicMoveScope;
import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicStepScope;

import org.jspecify.annotations.NullMarked;

/**
* @see AbstractConstructionHeuristicForager
*/
@NullMarked
public interface ConstructionHeuristicForager<Solution_>
extends ConstructionHeuristicPhaseLifecycleListener<Solution_> {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,6 @@ private static boolean hasAnyAnnotatedMembers(Class<?> solutionClass) {
private ListVariableDescriptor<Solution_> listVariableDescriptor;
@Nullable
private List<DeclarativeShadowVariableDescriptor<Solution_>> declarativeShadowVariableDescriptorList;

// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@
}

@Override
public InnerScore<Score_> innerCalculateScore() {
public InnerScore<Score_> innerCalculateScore(Score_ lowerBound) {

Check failure on line 311 in core/src/main/java/ai/timefold/solver/core/impl/domain/variable/ShadowVariableUpdateHelper.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Fix the incompatibility of the annotation @NullMarked at class level to honor @Nullable of the overridden method.

See more on https://sonarcloud.io/project/issues?id=ai.timefold%3Atimefold-solver&issues=AaHTOfvqsV8EUeGAaAlA&open=AaHTOfvqsV8EUeGAaAlA&pullRequest=2694
throw new UnsupportedOperationException();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ EntitySelectorFactory.<Solution_> create(entitySelectorConfig)
}
return new DefaultExhaustiveSearchPhase.Builder<>(phaseIndex, environmentMode, solverConfigPolicy.getLogIndentation(),
phaseTermination, nodeExplorationType.buildNodeComparator(scoreBounderEnabled), decider)
.withIsTieredScoreCalculationEnabled(solverConfigPolicy.isTieredScoreCalculationEnabled())
.enableAssertions().build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public class HeuristicConfigPolicy<Solution_> {
private final @Nullable Class<? extends NeighborhoodProvider<Solution_>> neighborhoodProviderClass;
private final @Nullable Supplier<MoveSelectionStrategy<Solution_>> moveSelectionStrategyFactory;
private final RandomSource random;
private final boolean isTieredScoreCalculationEnabled;

private final Map<String, EntityMimicRecorder<Solution_>> entityMimicRecorderMap = new HashMap<>();
private final Map<String, SubListMimicRecorder<Solution_>> subListMimicRecorderMap = new HashMap<>();
Expand All @@ -73,6 +74,7 @@ private HeuristicConfigPolicy(Builder<Solution_> builder) {
this.neighborhoodProviderClass = builder.neighborhoodProviderClass;
this.moveSelectionStrategyFactory = builder.moveSelectionStrategyFactory;
this.random = builder.random;
this.isTieredScoreCalculationEnabled = builder.isTieredScoreCalculationEnabled;
}

public EnvironmentMode getEnvironmentMode() {
Expand Down Expand Up @@ -145,6 +147,10 @@ public RandomSource getRandom() {
return random;
}

public boolean isTieredScoreCalculationEnabled() {
return isTieredScoreCalculationEnabled;
}

// ************************************************************************
// Builder methods
// ************************************************************************
Expand All @@ -163,7 +169,8 @@ public Builder<Solution_> cloneBuilder() {
.withNearbyDistanceMeterClass(nearbyDistanceMeterClass)
.withNeighborhoodProviderClass(neighborhoodProviderClass)
.withMoveSelectionStrategyFactory(moveSelectionStrategyFactory)
.withRandom(random);
.withRandom(random)
.withTieredScoreCalculationEnabled(isTieredScoreCalculationEnabled);
}

public HeuristicConfigPolicy<Solution_> copyConfigPolicy() {
Expand Down Expand Up @@ -319,6 +326,8 @@ public static class Builder<Solution_> {
private @Nullable Supplier<MoveSelectionStrategy<Solution_>> moveSelectionStrategyFactory;
private RandomSource random;

private boolean isTieredScoreCalculationEnabled = false;

public Builder<Solution_> withPreviewFeatureSet(Set<PreviewFeature> previewFeatureSet) {
this.previewFeatureSet = previewFeatureSet;
return this;
Expand Down Expand Up @@ -408,6 +417,11 @@ public Builder<Solution_> withUnassignedValuesAllowed(boolean unassignedValuesAl
return this;
}

public Builder<Solution_> withTieredScoreCalculationEnabled(boolean isTieredScoreCalculationEnabled) {
this.isTieredScoreCalculationEnabled = isTieredScoreCalculationEnabled;
return this;
}

public HeuristicConfigPolicy<Solution_> build() {
return new HeuristicConfigPolicy<>(this);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,9 @@ public LocalSearchPhase<Solution_> buildPhase(int phaseIndex, boolean lastInitia
var phaseTermination = buildPhaseTermination(phaseConfigPolicy, solverTermination, phaseIndex);
var decider = buildDecider(phaseConfigPolicy, phaseTermination);
return new DefaultLocalSearchPhase.Builder<>(phaseIndex, environmentMode, solverConfigPolicy.getLogIndentation(),
phaseTermination, decider).enableAssertions().build();
phaseTermination, decider)
.withIsTieredScoreCalculationEnabled(solverConfigPolicy.isTieredScoreCalculationEnabled())
.enableAssertions().build();
}

@SuppressWarnings({ "unchecked", "rawtypes" })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@ protected <Score_ extends Score<Score_>> void doMove(LocalSearchMoveScope<Soluti
throw new IllegalStateException("Impossible state: Local search move selector (%s) provided a non-doable move (%s)."
.formatted(moveRepository, move));
}
var score = scoreDirector.executeTemporaryMove(moveScope.getMove(), assertMoveScoreFromScratch);
var lowerBound = acceptor.<Score_> getMinimumScoreBound().getMinimumRequiredScoreForMove();
var score = scoreDirector.executeTemporaryMove(move, lowerBound, assertMoveScoreFromScratch);
moveScope.setScore(score);
moveScope.setAccepted(acceptor.isAccepted(moveScope));
forager.addMove(moveScope);
Expand Down
Loading
Loading