index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/HardMediumSoftLongScoreInliner.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import java.util.Map; import ai.timefold.solver.core.api.score.buildin.hardmediumsoftlong.HardMediumSoftLongScore; import ai.timefold.solver.core.api.score.stream.Constraint; import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint; final class HardMediumSoftLongScoreInliner extends AbstractScoreInliner<HardMediumSoftLongScore> { long hardScore; long mediumScore; long softScore; HardMediumSoftLongScoreInliner(Map<Constraint, HardMediumSoftLongScore> constraintWeightMap, ConstraintMatchPolicy constraintMatchPolicy) { super(constraintWeightMap, constraintMatchPolicy); } @Override public WeightedScoreImpacter<HardMediumSoftLongScore, ?> buildWeightedScoreImpacter(AbstractConstraint<?, ?, ?> constraint) { HardMediumSoftLongScore constraintWeight = constraintWeightMap.get(constraint); long hardConstraintWeight = constraintWeight.hardScore(); long mediumConstraintWeight = constraintWeight.mediumScore(); long softConstraintWeight = constraintWeight.softScore(); HardMediumSoftLongScoreContext context = new HardMediumSoftLongScoreContext(this, constraint, constraintWeight); if (mediumConstraintWeight == 0L && softConstraintWeight == 0L) { return WeightedScoreImpacter.of(context, (HardMediumSoftLongScoreContext ctx, long matchWeight, ConstraintMatchSupplier<HardMediumSoftLongScore> constraintMatchSupplier) -> ctx .changeHardScoreBy(matchWeight, constraintMatchSupplier)); } else if (hardConstraintWeight == 0L && softConstraintWeight == 0L) { return WeightedScoreImpacter.of(context, (HardMediumSoftLongScoreContext ctx, long matchWeight, ConstraintMatchSupplier<HardMediumSoftLongScore> constraintMatchSupplier) -> ctx .changeMediumScoreBy(matchWeight, constraintMatchSupplier)); } else if (hardConstraintWeight == 0L && mediumConstraintWeight == 0L) { return WeightedScoreImpacter.of(context, (HardMediumSoftLongScoreContext ctx, long matchWeight, ConstraintMatchSupplier<HardMediumSoftLongScore> constraintMatchSupplier) -> ctx .changeSoftScoreBy(matchWeight, constraintMatchSupplier)); } else { return WeightedScoreImpacter.of(context, (HardMediumSoftLongScoreContext ctx, long matchWeight, ConstraintMatchSupplier<HardMediumSoftLongScore> constraintMatchSupplier) -> ctx .changeScoreBy(matchWeight, constraintMatchSupplier)); } } @Override public HardMediumSoftLongScore extractScore() { return HardMediumSoftLongScore.of(hardScore, mediumScore, softScore); } @Override public String toString() { return HardMediumSoftLongScore.class.getSimpleName() + " inliner"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/HardMediumSoftScoreContext.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint; final class HardMediumSoftScoreContext extends ScoreContext<HardMediumSoftScore, HardMediumSoftScoreInliner> { public HardMediumSoftScoreContext(HardMediumSoftScoreInliner parent, AbstractConstraint<?, ?, ?> constraint, HardMediumSoftScore constraintWeight) { super(parent, constraint, constraintWeight); } public UndoScoreImpacter changeSoftScoreBy(int matchWeight, ConstraintMatchSupplier<HardMediumSoftScore> constraintMatchSupplier) { int softImpact = constraintWeight.softScore() * matchWeight; parent.softScore += softImpact; UndoScoreImpacter undoScoreImpact = () -> parent.softScore -= softImpact; if (!constraintMatchPolicy.isEnabled()) { return undoScoreImpact; } return impactWithConstraintMatch(undoScoreImpact, HardMediumSoftScore.ofSoft(softImpact), constraintMatchSupplier); } public UndoScoreImpacter changeMediumScoreBy(int matchWeight, ConstraintMatchSupplier<HardMediumSoftScore> constraintMatchSupplier) { int mediumImpact = constraintWeight.mediumScore() * matchWeight; parent.mediumScore += mediumImpact; UndoScoreImpacter undoScoreImpact = () -> parent.mediumScore -= mediumImpact; if (!constraintMatchPolicy.isEnabled()) { return undoScoreImpact; } return impactWithConstraintMatch(undoScoreImpact, HardMediumSoftScore.ofMedium(mediumImpact), constraintMatchSupplier); } public UndoScoreImpacter changeHardScoreBy(int matchWeight, ConstraintMatchSupplier<HardMediumSoftScore> constraintMatchSupplier) { int hardImpact = constraintWeight.hardScore() * matchWeight; parent.hardScore += hardImpact; UndoScoreImpacter undoScoreImpact = () -> parent.hardScore -= hardImpact; if (!constraintMatchPolicy.isEnabled()) { return undoScoreImpact; } return impactWithConstraintMatch(undoScoreImpact, HardMediumSoftScore.ofHard(hardImpact), constraintMatchSupplier); } public UndoScoreImpacter changeScoreBy(int matchWeight, ConstraintMatchSupplier<HardMediumSoftScore> constraintMatchSupplier) { int hardImpact = constraintWeight.hardScore() * matchWeight; int mediumImpact = constraintWeight.mediumScore() * matchWeight; int softImpact = constraintWeight.softScore() * matchWeight; parent.hardScore += hardImpact; parent.mediumScore += mediumImpact; parent.softScore += softImpact; UndoScoreImpacter undoScoreImpact = () -> { parent.hardScore -= hardImpact; parent.mediumScore -= mediumImpact; parent.softScore -= softImpact; }; if (!constraintMatchPolicy.isEnabled()) { return undoScoreImpact; } return impactWithConstraintMatch(undoScoreImpact, HardMediumSoftScore.of(hardImpact, mediumImpact, softImpact), constraintMatchSupplier); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/HardMediumSoftScoreInliner.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import java.util.Map; import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore; import ai.timefold.solver.core.api.score.stream.Constraint; import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint; final class HardMediumSoftScoreInliner extends AbstractScoreInliner<HardMediumSoftScore> { int hardScore; int mediumScore; int softScore; HardMediumSoftScoreInliner(Map<Constraint, HardMediumSoftScore> constraintWeightMap, ConstraintMatchPolicy constraintMatchPolicy) { super(constraintWeightMap, constraintMatchPolicy); } @Override public WeightedScoreImpacter<HardMediumSoftScore, ?> buildWeightedScoreImpacter(AbstractConstraint<?, ?, ?> constraint) { HardMediumSoftScore constraintWeight = constraintWeightMap.get(constraint); int hardConstraintWeight = constraintWeight.hardScore(); int mediumConstraintWeight = constraintWeight.mediumScore(); int softConstraintWeight = constraintWeight.softScore(); HardMediumSoftScoreContext context = new HardMediumSoftScoreContext(this, constraint, constraintWeight); if (mediumConstraintWeight == 0 && softConstraintWeight == 0) { return WeightedScoreImpacter.of(context, HardMediumSoftScoreContext::changeHardScoreBy); } else if (hardConstraintWeight == 0 && softConstraintWeight == 0) { return WeightedScoreImpacter.of(context, HardMediumSoftScoreContext::changeMediumScoreBy); } else if (hardConstraintWeight == 0 && mediumConstraintWeight == 0) { return WeightedScoreImpacter.of(context, HardMediumSoftScoreContext::changeSoftScoreBy); } else { return WeightedScoreImpacter.of(context, HardMediumSoftScoreContext::changeScoreBy); } } @Override public HardMediumSoftScore extractScore() { return HardMediumSoftScore.of(hardScore, mediumScore, softScore); } @Override public String toString() { return HardMediumSoftScore.class.getSimpleName() + " inliner"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/HardSoftBigDecimalScoreContext.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import java.math.BigDecimal; import ai.timefold.solver.core.api.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScore; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint; final class HardSoftBigDecimalScoreContext extends ScoreContext<HardSoftBigDecimalScore, HardSoftBigDecimalScoreInliner> { public HardSoftBigDecimalScoreContext(HardSoftBigDecimalScoreInliner parent, AbstractConstraint<?, ?, ?> constraint, HardSoftBigDecimalScore constraintWeight) { super(parent, constraint, constraintWeight); } public UndoScoreImpacter changeSoftScoreBy(BigDecimal matchWeight, ConstraintMatchSupplier<HardSoftBigDecimalScore> constraintMatchSupplier) { BigDecimal softImpact = constraintWeight.softScore().multiply(matchWeight); parent.softScore = parent.softScore.add(softImpact); UndoScoreImpacter undoScoreImpact = () -> parent.softScore = parent.softScore.subtract(softImpact); if (!constraintMatchPolicy.isEnabled()) { return undoScoreImpact; } return impactWithConstraintMatch(undoScoreImpact, HardSoftBigDecimalScore.ofSoft(softImpact), constraintMatchSupplier); } public UndoScoreImpacter changeHardScoreBy(BigDecimal matchWeight, ConstraintMatchSupplier<HardSoftBigDecimalScore> constraintMatchSupplier) { BigDecimal hardImpact = constraintWeight.hardScore().multiply(matchWeight); parent.hardScore = parent.hardScore.add(hardImpact); UndoScoreImpacter undoScoreImpact = () -> parent.hardScore = parent.hardScore.subtract(hardImpact); if (!constraintMatchPolicy.isEnabled()) { return undoScoreImpact; } return impactWithConstraintMatch(undoScoreImpact, HardSoftBigDecimalScore.ofHard(hardImpact), constraintMatchSupplier); } public UndoScoreImpacter changeScoreBy(BigDecimal matchWeight, ConstraintMatchSupplier<HardSoftBigDecimalScore> constraintMatchSupplier) { BigDecimal hardImpact = constraintWeight.hardScore().multiply(matchWeight); BigDecimal softImpact = constraintWeight.softScore().multiply(matchWeight); parent.hardScore = parent.hardScore.add(hardImpact); parent.softScore = parent.softScore.add(softImpact); UndoScoreImpacter undoScoreImpact = () -> { parent.hardScore = parent.hardScore.subtract(hardImpact); parent.softScore = parent.softScore.subtract(softImpact); }; if (!constraintMatchPolicy.isEnabled()) { return undoScoreImpact; } return impactWithConstraintMatch(undoScoreImpact, HardSoftBigDecimalScore.of(hardImpact, softImpact), constraintMatchSupplier); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/HardSoftBigDecimalScoreInliner.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import java.math.BigDecimal; import java.util.Map; import ai.timefold.solver.core.api.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScore; import ai.timefold.solver.core.api.score.stream.Constraint; import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint; final class HardSoftBigDecimalScoreInliner extends AbstractScoreInliner<HardSoftBigDecimalScore> { BigDecimal hardScore = BigDecimal.ZERO; BigDecimal softScore = BigDecimal.ZERO; HardSoftBigDecimalScoreInliner(Map<Constraint, HardSoftBigDecimalScore> constraintWeightMap, ConstraintMatchPolicy constraintMatchPolicy) { super(constraintWeightMap, constraintMatchPolicy); } @Override public WeightedScoreImpacter<HardSoftBigDecimalScore, ?> buildWeightedScoreImpacter(AbstractConstraint<?, ?, ?> constraint) { HardSoftBigDecimalScore constraintWeight = constraintWeightMap.get(constraint); HardSoftBigDecimalScoreContext context = new HardSoftBigDecimalScoreContext(this, constraint, constraintWeight); if (constraintWeight.softScore().equals(BigDecimal.ZERO)) { return WeightedScoreImpacter.of(context, HardSoftBigDecimalScoreContext::changeHardScoreBy); } else if (constraintWeight.hardScore().equals(BigDecimal.ZERO)) { return WeightedScoreImpacter.of(context, HardSoftBigDecimalScoreContext::changeSoftScoreBy); } else { return WeightedScoreImpacter.of(context, HardSoftBigDecimalScoreContext::changeScoreBy); } } @Override public HardSoftBigDecimalScore extractScore() { return HardSoftBigDecimalScore.of(hardScore, softScore); } @Override public String toString() { return HardSoftBigDecimalScore.class.getSimpleName() + " inliner"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/HardSoftLongScoreContext.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint; final class HardSoftLongScoreContext extends ScoreContext<HardSoftLongScore, HardSoftLongScoreInliner> { public HardSoftLongScoreContext(HardSoftLongScoreInliner parent, AbstractConstraint<?, ?, ?> constraint, HardSoftLongScore constraintWeight) { super(parent, constraint, constraintWeight); } public UndoScoreImpacter changeSoftScoreBy(long matchWeight, ConstraintMatchSupplier<HardSoftLongScore> constraintMatchSupplier) { long softImpact = constraintWeight.softScore() * matchWeight; parent.softScore += softImpact; UndoScoreImpacter undoScoreImpact = () -> parent.softScore -= softImpact; if (!constraintMatchPolicy.isEnabled()) { return undoScoreImpact; } return impactWithConstraintMatch(undoScoreImpact, HardSoftLongScore.ofSoft(softImpact), constraintMatchSupplier); } public UndoScoreImpacter changeHardScoreBy(long matchWeight, ConstraintMatchSupplier<HardSoftLongScore> constraintMatchSupplier) { long hardImpact = constraintWeight.hardScore() * matchWeight; parent.hardScore += hardImpact; UndoScoreImpacter undoScoreImpact = () -> parent.hardScore -= hardImpact; if (!constraintMatchPolicy.isEnabled()) { return undoScoreImpact; } return impactWithConstraintMatch(undoScoreImpact, HardSoftLongScore.ofHard(hardImpact), constraintMatchSupplier); } public UndoScoreImpacter changeScoreBy(long matchWeight, ConstraintMatchSupplier<HardSoftLongScore> constraintMatchSupplier) { long hardImpact = constraintWeight.hardScore() * matchWeight; long softImpact = constraintWeight.softScore() * matchWeight; parent.hardScore += hardImpact; parent.softScore += softImpact; UndoScoreImpacter undoScoreImpact = () -> { parent.hardScore -= hardImpact; parent.softScore -= softImpact; }; if (!constraintMatchPolicy.isEnabled()) { return undoScoreImpact; } return impactWithConstraintMatch(undoScoreImpact, HardSoftLongScore.of(hardImpact, softImpact), constraintMatchSupplier); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/HardSoftLongScoreInliner.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import java.util.Map; import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore; import ai.timefold.solver.core.api.score.stream.Constraint; import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint; final class HardSoftLongScoreInliner extends AbstractScoreInliner<HardSoftLongScore> { long hardScore; long softScore; HardSoftLongScoreInliner(Map<Constraint, HardSoftLongScore> constraintWeightMap, ConstraintMatchPolicy constraintMatchPolicy) { super(constraintWeightMap, constraintMatchPolicy); } @Override public WeightedScoreImpacter<HardSoftLongScore, ?> buildWeightedScoreImpacter(AbstractConstraint<?, ?, ?> constraint) { HardSoftLongScore constraintWeight = constraintWeightMap.get(constraint); HardSoftLongScoreContext context = new HardSoftLongScoreContext(this, constraint, constraintWeight); if (constraintWeight.softScore() == 0L) { return WeightedScoreImpacter.of(context, (HardSoftLongScoreContext ctx, long matchWeight, ConstraintMatchSupplier<HardSoftLongScore> constraintMatchSupplier) -> ctx .changeHardScoreBy(matchWeight, constraintMatchSupplier)); } else if (constraintWeight.hardScore() == 0L) { return WeightedScoreImpacter.of(context, (HardSoftLongScoreContext ctx, long matchWeight, ConstraintMatchSupplier<HardSoftLongScore> constraintMatchSupplier) -> ctx .changeSoftScoreBy(matchWeight, constraintMatchSupplier)); } else { return WeightedScoreImpacter.of(context, (HardSoftLongScoreContext ctx, long matchWeight, ConstraintMatchSupplier<HardSoftLongScore> constraintMatchSupplier) -> ctx .changeScoreBy(matchWeight, constraintMatchSupplier)); } } @Override public HardSoftLongScore extractScore() { return HardSoftLongScore.of(hardScore, softScore); } @Override public String toString() { return HardSoftLongScore.class.getSimpleName() + " inliner"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/HardSoftScoreContext.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint; final class HardSoftScoreContext extends ScoreContext<HardSoftScore, HardSoftScoreInliner> { public HardSoftScoreContext(HardSoftScoreInliner parent, AbstractConstraint<?, ?, ?> constraint, HardSoftScore constraintWeight) { super(parent, constraint, constraintWeight); } public UndoScoreImpacter changeSoftScoreBy(int matchWeight, ConstraintMatchSupplier<HardSoftScore> constraintMatchSupplier) { int softImpact = constraintWeight.softScore() * matchWeight; parent.softScore += softImpact; UndoScoreImpacter undoScoreImpact = () -> parent.softScore -= softImpact; if (!constraintMatchPolicy.isEnabled()) { return undoScoreImpact; } return impactWithConstraintMatch(undoScoreImpact, HardSoftScore.ofSoft(softImpact), constraintMatchSupplier); } public UndoScoreImpacter changeHardScoreBy(int matchWeight, ConstraintMatchSupplier<HardSoftScore> constraintMatchSupplier) { int hardImpact = constraintWeight.hardScore() * matchWeight; parent.hardScore += hardImpact; UndoScoreImpacter undoScoreImpact = () -> parent.hardScore -= hardImpact; if (!constraintMatchPolicy.isEnabled()) { return undoScoreImpact; } return impactWithConstraintMatch(undoScoreImpact, HardSoftScore.ofHard(hardImpact), constraintMatchSupplier); } public UndoScoreImpacter changeScoreBy(int matchWeight, ConstraintMatchSupplier<HardSoftScore> constraintMatchSupplier) { int hardImpact = constraintWeight.hardScore() * matchWeight; int softImpact = constraintWeight.softScore() * matchWeight; parent.hardScore += hardImpact; parent.softScore += softImpact; UndoScoreImpacter undoScoreImpact = () -> { parent.hardScore -= hardImpact; parent.softScore -= softImpact; }; if (!constraintMatchPolicy.isEnabled()) { return undoScoreImpact; } return impactWithConstraintMatch(undoScoreImpact, HardSoftScore.of(hardImpact, softImpact), constraintMatchSupplier); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/HardSoftScoreInliner.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import java.util.Map; import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; import ai.timefold.solver.core.api.score.stream.Constraint; import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint; final class HardSoftScoreInliner extends AbstractScoreInliner<HardSoftScore> { int hardScore; int softScore; HardSoftScoreInliner(Map<Constraint, HardSoftScore> constraintWeightMap, ConstraintMatchPolicy constraintMatchPolicy) { super(constraintWeightMap, constraintMatchPolicy); } @Override public WeightedScoreImpacter<HardSoftScore, ?> buildWeightedScoreImpacter( AbstractConstraint<?, ?, ?> constraint) { HardSoftScore constraintWeight = constraintWeightMap.get(constraint); HardSoftScoreContext context = new HardSoftScoreContext(this, constraint, constraintWeight); if (constraintWeight.softScore() == 0) { return WeightedScoreImpacter.of(context, HardSoftScoreContext::changeHardScoreBy); } else if (constraintWeight.hardScore() == 0) { return WeightedScoreImpacter.of(context, HardSoftScoreContext::changeSoftScoreBy); } else { return WeightedScoreImpacter.of(context, HardSoftScoreContext::changeScoreBy); } } @Override public HardSoftScore extractScore() { return HardSoftScore.of(hardScore, softScore); } @Override public String toString() { return HardSoftScore.class.getSimpleName() + " inliner"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/IntWeightedScoreImpacter.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import java.math.BigDecimal; import java.util.Objects; import ai.timefold.solver.core.api.score.Score; final class IntWeightedScoreImpacter<Score_ extends Score<Score_>, Context_ extends ScoreContext<Score_, ?>> implements WeightedScoreImpacter<Score_, Context_> { private final IntImpactFunction<Score_, Context_> impactFunction; private final Context_ context; public IntWeightedScoreImpacter(IntImpactFunction<Score_, Context_> impactFunction, Context_ context) { this.impactFunction = Objects.requireNonNull(impactFunction); this.context = context; } @Override public UndoScoreImpacter impactScore(int matchWeight, ConstraintMatchSupplier<Score_> constraintMatchSupplier) { context.getConstraint().assertCorrectImpact(matchWeight); return impactFunction.impact(context, matchWeight, constraintMatchSupplier); } @Override public UndoScoreImpacter impactScore(long matchWeight, ConstraintMatchSupplier<Score_> constraintMatchSupplier) { throw new UnsupportedOperationException("Impossible state: passing long into an int impacter."); } @Override public UndoScoreImpacter impactScore(BigDecimal matchWeight, ConstraintMatchSupplier<Score_> constraintMatchSupplier) { throw new UnsupportedOperationException("Impossible state: passing BigDecimal into an int impacter."); } @Override public Context_ getContext() { return context; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/LongWeightedScoreImpacter.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import java.math.BigDecimal; import java.util.Objects; import ai.timefold.solver.core.api.score.Score; final class LongWeightedScoreImpacter<Score_ extends Score<Score_>, Context_ extends ScoreContext<Score_, ?>> implements WeightedScoreImpacter<Score_, Context_> { private final LongImpactFunction<Score_, Context_> impactFunction; private final Context_ context; public LongWeightedScoreImpacter(LongImpactFunction<Score_, Context_> impactFunction, Context_ context) { this.impactFunction = Objects.requireNonNull(impactFunction); this.context = context; } @Override public UndoScoreImpacter impactScore(int matchWeight, ConstraintMatchSupplier<Score_> constraintMatchSupplier) { context.getConstraint().assertCorrectImpact(matchWeight); return impactFunction.impact(context, matchWeight, constraintMatchSupplier); // int can be cast to long } @Override public UndoScoreImpacter impactScore(long matchWeight, ConstraintMatchSupplier<Score_> constraintMatchSupplier) { context.getConstraint().assertCorrectImpact(matchWeight); return impactFunction.impact(context, matchWeight, constraintMatchSupplier); } @Override public UndoScoreImpacter impactScore(BigDecimal matchWeight, ConstraintMatchSupplier<Score_> constraintMatchSupplier) { throw new UnsupportedOperationException("Impossible state: passing BigDecimal into a long impacter."); } @Override public Context_ getContext() { return context; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/ScoreContext.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint; public abstract class ScoreContext<Score_ extends Score<Score_>, ScoreInliner_ extends AbstractScoreInliner<Score_>> { protected final ScoreInliner_ parent; protected final AbstractConstraint<?, ?, ?> constraint; protected final Score_ constraintWeight; protected final ConstraintMatchPolicy constraintMatchPolicy; protected ScoreContext(ScoreInliner_ parent, AbstractConstraint<?, ?, ?> constraint, Score_ constraintWeight) { this.parent = parent; this.constraint = constraint; this.constraintWeight = constraintWeight; this.constraintMatchPolicy = parent.constraintMatchPolicy; } public AbstractConstraint<?, ?, ?> getConstraint() { return constraint; } public Score_ getConstraintWeight() { return constraintWeight; } protected UndoScoreImpacter impactWithConstraintMatch(UndoScoreImpacter undoScoreImpact, Score_ score, ConstraintMatchSupplier<Score_> constraintMatchSupplier) { return parent.addConstraintMatch(constraint, score, constraintMatchSupplier, undoScoreImpact); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/SimpleBigDecimalScoreContext.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import java.math.BigDecimal; import ai.timefold.solver.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint; final class SimpleBigDecimalScoreContext extends ScoreContext<SimpleBigDecimalScore, SimpleBigDecimalScoreInliner> { public SimpleBigDecimalScoreContext(SimpleBigDecimalScoreInliner parent, AbstractConstraint<?, ?, ?> constraint, SimpleBigDecimalScore constraintWeight) { super(parent, constraint, constraintWeight); } public UndoScoreImpacter changeScoreBy(BigDecimal matchWeight, ConstraintMatchSupplier<SimpleBigDecimalScore> constraintMatchSupplier) { BigDecimal impact = constraintWeight.score().multiply(matchWeight); parent.score = parent.score.add(impact); UndoScoreImpacter undoScoreImpact = () -> parent.score = parent.score.subtract(impact); if (!constraintMatchPolicy.isEnabled()) { return undoScoreImpact; } return impactWithConstraintMatch(undoScoreImpact, SimpleBigDecimalScore.of(impact), constraintMatchSupplier); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/SimpleBigDecimalScoreInliner.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import java.math.BigDecimal; import java.util.Map; import ai.timefold.solver.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore; import ai.timefold.solver.core.api.score.stream.Constraint; import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint; final class SimpleBigDecimalScoreInliner extends AbstractScoreInliner<SimpleBigDecimalScore> { BigDecimal score = BigDecimal.ZERO; SimpleBigDecimalScoreInliner(Map<Constraint, SimpleBigDecimalScore> constraintWeightMap, ConstraintMatchPolicy constraintMatchPolicy) { super(constraintWeightMap, constraintMatchPolicy); } @Override public WeightedScoreImpacter<SimpleBigDecimalScore, ?> buildWeightedScoreImpacter(AbstractConstraint<?, ?, ?> constraint) { SimpleBigDecimalScore constraintWeight = constraintWeightMap.get(constraint); SimpleBigDecimalScoreContext context = new SimpleBigDecimalScoreContext(this, constraint, constraintWeight); return WeightedScoreImpacter.of(context, SimpleBigDecimalScoreContext::changeScoreBy); } @Override public SimpleBigDecimalScore extractScore() { return SimpleBigDecimalScore.of(score); } @Override public String toString() { return SimpleBigDecimalScore.class.getSimpleName() + " inliner"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/SimpleLongScoreContext.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import ai.timefold.solver.core.api.score.buildin.simplelong.SimpleLongScore; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint; final class SimpleLongScoreContext extends ScoreContext<SimpleLongScore, SimpleLongScoreInliner> { public SimpleLongScoreContext(SimpleLongScoreInliner parent, AbstractConstraint<?, ?, ?> constraint, SimpleLongScore constraintWeight) { super(parent, constraint, constraintWeight); } public UndoScoreImpacter changeScoreBy(long matchWeight, ConstraintMatchSupplier<SimpleLongScore> constraintMatchSupplier) { long impact = constraintWeight.score() * matchWeight; parent.score += impact; UndoScoreImpacter undoScoreImpact = () -> parent.score -= impact; if (!constraintMatchPolicy.isEnabled()) { return undoScoreImpact; } return impactWithConstraintMatch(undoScoreImpact, SimpleLongScore.of(impact), constraintMatchSupplier); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/SimpleLongScoreInliner.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import java.util.Map; import ai.timefold.solver.core.api.score.buildin.simplelong.SimpleLongScore; import ai.timefold.solver.core.api.score.stream.Constraint; import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint; final class SimpleLongScoreInliner extends AbstractScoreInliner<SimpleLongScore> { long score; SimpleLongScoreInliner(Map<Constraint, SimpleLongScore> constraintWeightMap, ConstraintMatchPolicy constraintMatchPolicy) { super(constraintWeightMap, constraintMatchPolicy); } @Override public WeightedScoreImpacter<SimpleLongScore, ?> buildWeightedScoreImpacter( AbstractConstraint<?, ?, ?> constraint) { SimpleLongScore constraintWeight = constraintWeightMap.get(constraint); SimpleLongScoreContext context = new SimpleLongScoreContext(this, constraint, constraintWeight); return WeightedScoreImpacter.of(context, (SimpleLongScoreContext ctx, long matchWeight, ConstraintMatchSupplier<SimpleLongScore> constraintMatchSupplier) -> ctx .changeScoreBy(matchWeight, constraintMatchSupplier)); } @Override public SimpleLongScore extractScore() { return SimpleLongScore.of(score); } @Override public String toString() { return SimpleLongScore.class.getSimpleName() + " inliner"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/SimpleScoreContext.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint; final class SimpleScoreContext extends ScoreContext<SimpleScore, SimpleScoreInliner> { public SimpleScoreContext(SimpleScoreInliner parent, AbstractConstraint<?, ?, ?> constraint, SimpleScore constraintWeight) { super(parent, constraint, constraintWeight); } public UndoScoreImpacter changeScoreBy(int matchWeight, ConstraintMatchSupplier<SimpleScore> constraintMatchSupplier) { int impact = constraintWeight.score() * matchWeight; parent.score += impact; UndoScoreImpacter undoScoreImpact = () -> parent.score -= impact; if (!constraintMatchPolicy.isEnabled()) { return undoScoreImpact; } return impactWithConstraintMatch(undoScoreImpact, SimpleScore.of(impact), constraintMatchSupplier); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/SimpleScoreInliner.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import java.util.Map; import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore; import ai.timefold.solver.core.api.score.stream.Constraint; import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraint; final class SimpleScoreInliner extends AbstractScoreInliner<SimpleScore> { int score; SimpleScoreInliner(Map<Constraint, SimpleScore> constraintWeightMap, ConstraintMatchPolicy constraintMatchPolicy) { super(constraintWeightMap, constraintMatchPolicy); } @Override public WeightedScoreImpacter<SimpleScore, ?> buildWeightedScoreImpacter( AbstractConstraint<?, ?, ?> constraint) { SimpleScore constraintWeight = constraintWeightMap.get(constraint); SimpleScoreContext context = new SimpleScoreContext(this, constraint, constraintWeight); return WeightedScoreImpacter.of(context, SimpleScoreContext::changeScoreBy); } @Override public SimpleScore extractScore() { return SimpleScore.of(score); } @Override public String toString() { return SimpleScore.class.getSimpleName() + " inliner"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/UndoScoreImpacter.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; @FunctionalInterface public interface UndoScoreImpacter extends Runnable { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/inliner/WeightedScoreImpacter.java
package ai.timefold.solver.core.impl.score.stream.common.inliner; import java.math.BigDecimal; import ai.timefold.solver.core.api.score.Score; /** * There are several valid ways how an impacter could be called from a constraint stream: * * <ul> * <li>{@code .penalize(..., (int) 1)}</li> * <li>{@code .penalizeLong(..., (int) 1)}</li> * <li>{@code .penalizeLong(..., (long) 1)}</li> * <li>{@code .penalizeBigDecimal(..., (int) 1)}</li> * <li>{@code .penalizeBigDecimal(..., (long) 1)}</li> * <li>{@code .penalizeBigDecimal(..., BigDecimal.ONE)}</li> * <li>Plus reward variants of the above.</li> * </ul> * * An implementation of this interface can throw an {@link UnsupportedOperationException} * for the method types it doesn't support. The CS API guarantees no types are mixed. For example, * a {@link BigDecimal} parameter method won't be called on an instance built with an {@link IntImpactFunction}. */ public interface WeightedScoreImpacter<Score_ extends Score<Score_>, Context_ extends ScoreContext<Score_, ?>> { static <Score_ extends Score<Score_>, Context_ extends ScoreContext<Score_, ?>> WeightedScoreImpacter<Score_, Context_> of(Context_ context, IntImpactFunction<Score_, Context_> impactFunction) { return new IntWeightedScoreImpacter<>(impactFunction, context); } static <Score_ extends Score<Score_>, Context_ extends ScoreContext<Score_, ?>> WeightedScoreImpacter<Score_, Context_> of(Context_ context, LongImpactFunction<Score_, Context_> impactFunction) { return new LongWeightedScoreImpacter<>(impactFunction, context); } static <Score_ extends Score<Score_>, Context_ extends ScoreContext<Score_, ?>> WeightedScoreImpacter<Score_, Context_> of(Context_ context, BigDecimalImpactFunction<Score_, Context_> impactFunction) { return new BigDecimalWeightedScoreImpacter<>(impactFunction, context); } /** * @param matchWeight never null * @param constraintMatchSupplier ignored unless constraint match enableds * @return never null */ UndoScoreImpacter impactScore(int matchWeight, ConstraintMatchSupplier<Score_> constraintMatchSupplier); /** * @param matchWeight never null * @param constraintMatchSupplier ignored unless constraint match enabled * @return never null */ UndoScoreImpacter impactScore(long matchWeight, ConstraintMatchSupplier<Score_> constraintMatchSupplier); /** * @param matchWeight never null * @param constraintMatchSupplier ignored unless constraint match enabled * @return never null */ UndoScoreImpacter impactScore(BigDecimal matchWeight, ConstraintMatchSupplier<Score_> constraintMatchSupplier); Context_ getContext(); @FunctionalInterface interface IntImpactFunction<Score_ extends Score<Score_>, Context_ extends ScoreContext<Score_, ?>> { UndoScoreImpacter impact(Context_ context, int matchWeight, ConstraintMatchSupplier<Score_> constraintMatchSupplier); } @FunctionalInterface interface LongImpactFunction<Score_ extends Score<Score_>, Context_ extends ScoreContext<Score_, ?>> { UndoScoreImpacter impact(Context_ context, long matchWeight, ConstraintMatchSupplier<Score_> constraintMatchSupplier); } @FunctionalInterface interface BigDecimalImpactFunction<Score_ extends Score<Score_>, Context_ extends ScoreContext<Score_, ?>> { UndoScoreImpacter impact(Context_ context, BigDecimal matchWeight, ConstraintMatchSupplier<Score_> constraintMatchSupplier); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/quad/InnerQuadConstraintStream.java
package ai.timefold.solver.core.impl.score.stream.common.quad; import java.math.BigDecimal; import java.util.Arrays; import java.util.Collection; import ai.timefold.solver.core.api.function.PentaFunction; import ai.timefold.solver.core.api.function.QuadFunction; import ai.timefold.solver.core.api.function.ToIntQuadFunction; import ai.timefold.solver.core.api.function.ToLongQuadFunction; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.stream.Constraint; import ai.timefold.solver.core.api.score.stream.DefaultConstraintJustification; import ai.timefold.solver.core.api.score.stream.penta.PentaJoiner; import ai.timefold.solver.core.api.score.stream.quad.QuadConstraintBuilder; import ai.timefold.solver.core.api.score.stream.quad.QuadConstraintStream; import ai.timefold.solver.core.impl.score.stream.common.RetrievalSemantics; import ai.timefold.solver.core.impl.score.stream.common.ScoreImpactType; import ai.timefold.solver.core.impl.util.ConstantLambdaUtils; import org.jspecify.annotations.NonNull; public interface InnerQuadConstraintStream<A, B, C, D> extends QuadConstraintStream<A, B, C, D> { static <A, B, C, D> PentaFunction<A, B, C, D, Score<?>, DefaultConstraintJustification> createDefaultJustificationMapping() { return (a, b, c, d, score) -> DefaultConstraintJustification.of(score, a, b, c, d); } static <A, B, C, D> QuadFunction<A, B, C, D, Collection<?>> createDefaultIndictedObjectsMapping() { return Arrays::asList; } RetrievalSemantics getRetrievalSemantics(); /** * This method will return true if the constraint stream is guaranteed to only produce distinct tuples. * See {@link #distinct()} for details. * * @return true if the guarantee of distinct tuples is provided */ boolean guaranteesDistinct(); @Override default @NonNull <E> QuadConstraintStream<A, B, C, D> ifExists(@NonNull Class<E> otherClass, @NonNull PentaJoiner<A, B, C, D, E> @NonNull... joiners) { if (getRetrievalSemantics() == RetrievalSemantics.STANDARD) { return ifExists(getConstraintFactory().forEach(otherClass), joiners); } else { // Calls fromUnfiltered() for backward compatibility only return ifExists(getConstraintFactory().fromUnfiltered(otherClass), joiners); } } @Override default @NonNull <E> QuadConstraintStream<A, B, C, D> ifExistsIncludingUnassigned(@NonNull Class<E> otherClass, @NonNull PentaJoiner<A, B, C, D, E> @NonNull... joiners) { if (getRetrievalSemantics() == RetrievalSemantics.STANDARD) { return ifExists(getConstraintFactory().forEachIncludingUnassigned(otherClass), joiners); } else { return ifExists(getConstraintFactory().fromUnfiltered(otherClass), joiners); } } @Override default @NonNull <E> QuadConstraintStream<A, B, C, D> ifNotExists(@NonNull Class<E> otherClass, @NonNull PentaJoiner<A, B, C, D, E> @NonNull... joiners) { if (getRetrievalSemantics() == RetrievalSemantics.STANDARD) { return ifNotExists(getConstraintFactory().forEach(otherClass), joiners); } else { // Calls fromUnfiltered() for backward compatibility only return ifNotExists(getConstraintFactory().fromUnfiltered(otherClass), joiners); } } @Override default @NonNull <E> QuadConstraintStream<A, B, C, D> ifNotExistsIncludingUnassigned(@NonNull Class<E> otherClass, @NonNull PentaJoiner<A, B, C, D, E> @NonNull... joiners) { if (getRetrievalSemantics() == RetrievalSemantics.STANDARD) { return ifNotExists(getConstraintFactory().forEachIncludingUnassigned(otherClass), joiners); } else { return ifNotExists(getConstraintFactory().fromUnfiltered(otherClass), joiners); } } @Override default @NonNull QuadConstraintStream<A, B, C, D> distinct() { if (guaranteesDistinct()) { return this; } else { return groupBy(ConstantLambdaUtils.quadPickFirst(), ConstantLambdaUtils.quadPickSecond(), ConstantLambdaUtils.quadPickThird(), ConstantLambdaUtils.quadPickFourth()); } } @Override default @NonNull <Score_ extends Score<Score_>> QuadConstraintBuilder<A, B, C, D, Score_> penalize( @NonNull Score_ constraintWeight, @NonNull ToIntQuadFunction<A, B, C, D> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.PENALTY); } @Override default @NonNull <Score_ extends Score<Score_>> QuadConstraintBuilder<A, B, C, D, Score_> penalizeLong( @NonNull Score_ constraintWeight, @NonNull ToLongQuadFunction<A, B, C, D> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.PENALTY); } @Override default @NonNull <Score_ extends Score<Score_>> QuadConstraintBuilder<A, B, C, D, Score_> penalizeBigDecimal( @NonNull Score_ constraintWeight, @NonNull QuadFunction<A, B, C, D, BigDecimal> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.PENALTY); } @Override default QuadConstraintBuilder<A, B, C, D, ?> penalizeConfigurable(ToIntQuadFunction<A, B, C, D> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.PENALTY); } @Override default QuadConstraintBuilder<A, B, C, D, ?> penalizeConfigurableLong(ToLongQuadFunction<A, B, C, D> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.PENALTY); } @Override default QuadConstraintBuilder<A, B, C, D, ?> penalizeConfigurableBigDecimal(QuadFunction<A, B, C, D, BigDecimal> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.PENALTY); } @Override default @NonNull <Score_ extends Score<Score_>> QuadConstraintBuilder<A, B, C, D, Score_> reward( @NonNull Score_ constraintWeight, @NonNull ToIntQuadFunction<A, B, C, D> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.REWARD); } @Override default @NonNull <Score_ extends Score<Score_>> QuadConstraintBuilder<A, B, C, D, Score_> rewardLong( @NonNull Score_ constraintWeight, @NonNull ToLongQuadFunction<A, B, C, D> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.REWARD); } @Override default @NonNull <Score_ extends Score<Score_>> QuadConstraintBuilder<A, B, C, D, Score_> rewardBigDecimal( @NonNull Score_ constraintWeight, @NonNull QuadFunction<A, B, C, D, BigDecimal> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.REWARD); } @Override default QuadConstraintBuilder<A, B, C, D, ?> rewardConfigurable(ToIntQuadFunction<A, B, C, D> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.REWARD); } @Override default QuadConstraintBuilder<A, B, C, D, ?> rewardConfigurableLong(ToLongQuadFunction<A, B, C, D> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.REWARD); } @Override default QuadConstraintBuilder<A, B, C, D, ?> rewardConfigurableBigDecimal(QuadFunction<A, B, C, D, BigDecimal> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.REWARD); } @Override default @NonNull <Score_ extends Score<Score_>> QuadConstraintBuilder<A, B, C, D, Score_> impact( @NonNull Score_ constraintWeight, @NonNull ToIntQuadFunction<A, B, C, D> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.MIXED); } @Override default @NonNull <Score_ extends Score<Score_>> QuadConstraintBuilder<A, B, C, D, Score_> impactLong( @NonNull Score_ constraintWeight, @NonNull ToLongQuadFunction<A, B, C, D> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.MIXED); } @Override default @NonNull <Score_ extends Score<Score_>> QuadConstraintBuilder<A, B, C, D, Score_> impactBigDecimal( @NonNull Score_ constraintWeight, @NonNull QuadFunction<A, B, C, D, BigDecimal> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.MIXED); } @Override default QuadConstraintBuilder<A, B, C, D, ?> impactConfigurable(ToIntQuadFunction<A, B, C, D> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.MIXED); } @Override default QuadConstraintBuilder<A, B, C, D, ?> impactConfigurableLong(ToLongQuadFunction<A, B, C, D> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.MIXED); } @Override default QuadConstraintBuilder<A, B, C, D, ?> impactConfigurableBigDecimal(QuadFunction<A, B, C, D, BigDecimal> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.MIXED); } <Score_ extends Score<Score_>> QuadConstraintBuilder<A, B, C, D, Score_> innerImpact(Score_ constraintWeight, ToIntQuadFunction<A, B, C, D> matchWeigher, ScoreImpactType scoreImpactType); <Score_ extends Score<Score_>> QuadConstraintBuilder<A, B, C, D, Score_> innerImpact(Score_ constraintWeight, ToLongQuadFunction<A, B, C, D> matchWeigher, ScoreImpactType scoreImpactType); <Score_ extends Score<Score_>> QuadConstraintBuilder<A, B, C, D, Score_> innerImpact(Score_ constraintWeight, QuadFunction<A, B, C, D, BigDecimal> matchWeigher, ScoreImpactType scoreImpactType); @Override default @NonNull Constraint penalize(@NonNull String constraintName, @NonNull Score<?> constraintWeight) { return penalize((Score) constraintWeight) .asConstraint(constraintName); } @Override default @NonNull Constraint penalize(@NonNull String constraintPackage, @NonNull String constraintName, @NonNull Score<?> constraintWeight) { return penalize((Score) constraintWeight) .asConstraint(constraintPackage, constraintName); } @Override default @NonNull Constraint penalizeConfigurable(@NonNull String constraintName) { return penalizeConfigurable() .asConstraint(constraintName); } @Override default @NonNull Constraint penalizeConfigurable(@NonNull String constraintPackage, @NonNull String constraintName) { return penalizeConfigurable() .asConstraint(constraintPackage, constraintName); } @Override default @NonNull Constraint reward(@NonNull String constraintName, @NonNull Score<?> constraintWeight) { return reward((Score) constraintWeight) .asConstraint(constraintName); } @Override default @NonNull Constraint reward(@NonNull String constraintPackage, @NonNull String constraintName, @NonNull Score<?> constraintWeight) { return reward((Score) constraintWeight) .asConstraint(constraintPackage, constraintName); } @Override default @NonNull Constraint rewardConfigurable(@NonNull String constraintName) { return rewardConfigurable() .asConstraint(constraintName); } @Override default @NonNull Constraint rewardConfigurable(@NonNull String constraintPackage, @NonNull String constraintName) { return penalizeConfigurable() .asConstraint(constraintPackage, constraintName); } @Override default @NonNull Constraint impact(@NonNull String constraintName, @NonNull Score<?> constraintWeight) { return impact((Score) constraintWeight) .asConstraint(constraintName); } @Override default @NonNull Constraint impact(@NonNull String constraintPackage, @NonNull String constraintName, @NonNull Score<?> constraintWeight) { return impact((Score) constraintWeight) .asConstraint(constraintPackage, constraintName); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/quad/QuadConstraintBuilderImpl.java
package ai.timefold.solver.core.impl.score.stream.common.quad; import java.util.Collection; import java.util.Objects; import ai.timefold.solver.core.api.function.PentaFunction; import ai.timefold.solver.core.api.function.QuadFunction; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.stream.ConstraintJustification; import ai.timefold.solver.core.api.score.stream.quad.QuadConstraintBuilder; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintBuilder; import ai.timefold.solver.core.impl.score.stream.common.ScoreImpactType; import org.jspecify.annotations.NonNull; public final class QuadConstraintBuilderImpl<A, B, C, D, Score_ extends Score<Score_>> extends AbstractConstraintBuilder<Score_> implements QuadConstraintBuilder<A, B, C, D, Score_> { private PentaFunction<A, B, C, D, Score_, ConstraintJustification> justificationMapping; private QuadFunction<A, B, C, D, Collection<Object>> indictedObjectsMapping; public QuadConstraintBuilderImpl(QuadConstraintConstructor<A, B, C, D, Score_> constraintConstructor, ScoreImpactType impactType, Score_ constraintWeight) { super(constraintConstructor, impactType, constraintWeight); } @Override protected PentaFunction<A, B, C, D, Score_, ConstraintJustification> getJustificationMapping() { return justificationMapping; } @Override public @NonNull <ConstraintJustification_ extends ConstraintJustification> QuadConstraintBuilder<A, B, C, D, Score_> justifyWith( @NonNull PentaFunction<A, B, C, D, Score_, ConstraintJustification_> justificationMapping) { if (this.justificationMapping != null) { throw new IllegalStateException(""" Justification mapping already set (%s). Maybe the constraint calls justifyWith() twice?""" .formatted(justificationMapping)); } this.justificationMapping = (PentaFunction<A, B, C, D, Score_, ConstraintJustification>) Objects.requireNonNull(justificationMapping); return this; } @Override protected QuadFunction<A, B, C, D, Collection<Object>> getIndictedObjectsMapping() { return indictedObjectsMapping; } @Override public @NonNull QuadConstraintBuilder<A, B, C, D, Score_> indictWith(@NonNull QuadFunction<A, B, C, D, Collection<Object>> indictedObjectsMapping) { if (this.indictedObjectsMapping != null) { throw new IllegalStateException(""" Indicted objects' mapping already set (%s). Maybe the constraint calls indictWith() twice?""" .formatted(indictedObjectsMapping)); } this.indictedObjectsMapping = Objects.requireNonNull(indictedObjectsMapping); return this; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/quad/QuadConstraintConstructor.java
package ai.timefold.solver.core.impl.score.stream.common.quad; import java.util.Collection; import ai.timefold.solver.core.api.function.PentaFunction; import ai.timefold.solver.core.api.function.QuadFunction; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.score.stream.common.ConstraintConstructor; @FunctionalInterface public interface QuadConstraintConstructor<A, B, C, D, Score_ extends Score<Score_>> extends ConstraintConstructor<Score_, PentaFunction<A, B, C, D, Score_, Object>, QuadFunction<A, B, C, D, Collection<?>>> { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/tri/InnerTriConstraintStream.java
package ai.timefold.solver.core.impl.score.stream.common.tri; import static ai.timefold.solver.core.impl.score.stream.common.RetrievalSemantics.STANDARD; import java.math.BigDecimal; import java.util.Arrays; import java.util.Collection; import ai.timefold.solver.core.api.function.QuadFunction; import ai.timefold.solver.core.api.function.ToIntTriFunction; import ai.timefold.solver.core.api.function.ToLongTriFunction; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.stream.Constraint; import ai.timefold.solver.core.api.score.stream.DefaultConstraintJustification; import ai.timefold.solver.core.api.score.stream.quad.QuadConstraintStream; import ai.timefold.solver.core.api.score.stream.quad.QuadJoiner; import ai.timefold.solver.core.api.score.stream.tri.TriConstraintBuilder; import ai.timefold.solver.core.api.score.stream.tri.TriConstraintStream; import ai.timefold.solver.core.impl.score.stream.common.RetrievalSemantics; import ai.timefold.solver.core.impl.score.stream.common.ScoreImpactType; import ai.timefold.solver.core.impl.util.ConstantLambdaUtils; import org.jspecify.annotations.NonNull; public interface InnerTriConstraintStream<A, B, C> extends TriConstraintStream<A, B, C> { static <A, B, C> QuadFunction<A, B, C, Score<?>, DefaultConstraintJustification> createDefaultJustificationMapping() { return (a, b, c, score) -> DefaultConstraintJustification.of(score, a, b, c); } static <A, B, C> TriFunction<A, B, C, Collection<?>> createDefaultIndictedObjectsMapping() { return Arrays::asList; } RetrievalSemantics getRetrievalSemantics(); /** * This method will return true if the constraint stream is guaranteed to only produce distinct tuples. * See {@link #distinct()} for details. * * @return true if the guarantee of distinct tuples is provided */ boolean guaranteesDistinct(); @Override default @NonNull <D> QuadConstraintStream<A, B, C, D> join(@NonNull Class<D> otherClass, @NonNull QuadJoiner<A, B, C, D> @NonNull... joiners) { if (getRetrievalSemantics() == STANDARD) { return join(getConstraintFactory().forEach(otherClass), joiners); } else { return join(getConstraintFactory().from(otherClass), joiners); } } @Override default @NonNull <D> TriConstraintStream<A, B, C> ifExists(@NonNull Class<D> otherClass, @NonNull QuadJoiner<A, B, C, D> @NonNull... joiners) { if (getRetrievalSemantics() == STANDARD) { return ifExists(getConstraintFactory().forEach(otherClass), joiners); } else { // Calls fromUnfiltered() for backward compatibility only return ifExists(getConstraintFactory().fromUnfiltered(otherClass), joiners); } } @Override default @NonNull <D> TriConstraintStream<A, B, C> ifExistsIncludingUnassigned(@NonNull Class<D> otherClass, @NonNull QuadJoiner<A, B, C, D> @NonNull... joiners) { if (getRetrievalSemantics() == STANDARD) { return ifExists(getConstraintFactory().forEachIncludingUnassigned(otherClass), joiners); } else { return ifExists(getConstraintFactory().fromUnfiltered(otherClass), joiners); } } @Override default @NonNull <D> TriConstraintStream<A, B, C> ifNotExists(@NonNull Class<D> otherClass, @NonNull QuadJoiner<A, B, C, D> @NonNull... joiners) { if (getRetrievalSemantics() == STANDARD) { return ifNotExists(getConstraintFactory().forEach(otherClass), joiners); } else { // Calls fromUnfiltered() for backward compatibility only return ifNotExists(getConstraintFactory().fromUnfiltered(otherClass), joiners); } } @Override default @NonNull <D> TriConstraintStream<A, B, C> ifNotExistsIncludingUnassigned(@NonNull Class<D> otherClass, @NonNull QuadJoiner<A, B, C, D> @NonNull... joiners) { if (getRetrievalSemantics() == STANDARD) { return ifNotExists(getConstraintFactory().forEachIncludingUnassigned(otherClass), joiners); } else { return ifNotExists(getConstraintFactory().fromUnfiltered(otherClass), joiners); } } @Override default @NonNull TriConstraintStream<A, B, C> distinct() { if (guaranteesDistinct()) { return this; } else { return groupBy(ConstantLambdaUtils.triPickFirst(), ConstantLambdaUtils.triPickSecond(), ConstantLambdaUtils.triPickThird()); } } @Override default @NonNull <Score_ extends Score<Score_>> TriConstraintBuilder<A, B, C, Score_> penalize( @NonNull Score_ constraintWeight, @NonNull ToIntTriFunction<A, B, C> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.PENALTY); } @Override default @NonNull <Score_ extends Score<Score_>> TriConstraintBuilder<A, B, C, Score_> penalizeLong( @NonNull Score_ constraintWeight, @NonNull ToLongTriFunction<A, B, C> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.PENALTY); } @Override default @NonNull <Score_ extends Score<Score_>> TriConstraintBuilder<A, B, C, Score_> penalizeBigDecimal( @NonNull Score_ constraintWeight, @NonNull TriFunction<A, B, C, BigDecimal> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.PENALTY); } @Override default TriConstraintBuilder<A, B, C, ?> penalizeConfigurable(ToIntTriFunction<A, B, C> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.PENALTY); } @Override default TriConstraintBuilder<A, B, C, ?> penalizeConfigurableLong(ToLongTriFunction<A, B, C> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.PENALTY); } @Override default TriConstraintBuilder<A, B, C, ?> penalizeConfigurableBigDecimal(TriFunction<A, B, C, BigDecimal> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.PENALTY); } @Override default @NonNull <Score_ extends Score<Score_>> TriConstraintBuilder<A, B, C, Score_> reward( @NonNull Score_ constraintWeight, @NonNull ToIntTriFunction<A, B, C> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.REWARD); } @Override default @NonNull <Score_ extends Score<Score_>> TriConstraintBuilder<A, B, C, Score_> rewardLong( @NonNull Score_ constraintWeight, @NonNull ToLongTriFunction<A, B, C> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.REWARD); } @Override default @NonNull <Score_ extends Score<Score_>> TriConstraintBuilder<A, B, C, Score_> rewardBigDecimal( @NonNull Score_ constraintWeight, @NonNull TriFunction<A, B, C, BigDecimal> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.REWARD); } @Override default TriConstraintBuilder<A, B, C, ?> rewardConfigurable(ToIntTriFunction<A, B, C> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.REWARD); } @Override default TriConstraintBuilder<A, B, C, ?> rewardConfigurableLong(ToLongTriFunction<A, B, C> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.REWARD); } @Override default TriConstraintBuilder<A, B, C, ?> rewardConfigurableBigDecimal(TriFunction<A, B, C, BigDecimal> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.REWARD); } @Override default @NonNull <Score_ extends Score<Score_>> TriConstraintBuilder<A, B, C, Score_> impact( @NonNull Score_ constraintWeight, @NonNull ToIntTriFunction<A, B, C> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.MIXED); } @Override default @NonNull <Score_ extends Score<Score_>> TriConstraintBuilder<A, B, C, Score_> impactLong( @NonNull Score_ constraintWeight, @NonNull ToLongTriFunction<A, B, C> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.MIXED); } @Override default @NonNull <Score_ extends Score<Score_>> TriConstraintBuilder<A, B, C, Score_> impactBigDecimal( @NonNull Score_ constraintWeight, @NonNull TriFunction<A, B, C, BigDecimal> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.MIXED); } @Override default TriConstraintBuilder<A, B, C, ?> impactConfigurable(ToIntTriFunction<A, B, C> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.MIXED); } @Override default TriConstraintBuilder<A, B, C, ?> impactConfigurableLong(ToLongTriFunction<A, B, C> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.MIXED); } @Override default TriConstraintBuilder<A, B, C, ?> impactConfigurableBigDecimal(TriFunction<A, B, C, BigDecimal> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.MIXED); } <Score_ extends Score<Score_>> TriConstraintBuilder<A, B, C, Score_> innerImpact(Score_ constraintWeight, ToIntTriFunction<A, B, C> matchWeigher, ScoreImpactType scoreImpactType); <Score_ extends Score<Score_>> TriConstraintBuilder<A, B, C, Score_> innerImpact(Score_ constraintWeight, ToLongTriFunction<A, B, C> matchWeigher, ScoreImpactType scoreImpactType); <Score_ extends Score<Score_>> TriConstraintBuilder<A, B, C, Score_> innerImpact(Score_ constraintWeight, TriFunction<A, B, C, BigDecimal> matchWeigher, ScoreImpactType scoreImpactType); @Override default @NonNull Constraint penalize(@NonNull String constraintName, @NonNull Score<?> constraintWeight) { return penalize((Score) constraintWeight) .asConstraint(constraintName); } @Override default @NonNull Constraint penalize(@NonNull String constraintPackage, @NonNull String constraintName, @NonNull Score<?> constraintWeight) { return penalize((Score) constraintWeight) .asConstraint(constraintPackage, constraintName); } @Override default @NonNull Constraint penalizeConfigurable(@NonNull String constraintName) { return penalizeConfigurable() .asConstraint(constraintName); } @Override default @NonNull Constraint penalizeConfigurable(@NonNull String constraintPackage, @NonNull String constraintName) { return penalizeConfigurable() .asConstraint(constraintPackage, constraintName); } @Override default @NonNull Constraint reward(@NonNull String constraintName, @NonNull Score<?> constraintWeight) { return reward((Score) constraintWeight) .asConstraint(constraintName); } @Override default @NonNull Constraint reward(@NonNull String constraintPackage, @NonNull String constraintName, @NonNull Score<?> constraintWeight) { return reward((Score) constraintWeight) .asConstraint(constraintPackage, constraintName); } @Override default @NonNull Constraint rewardConfigurable(@NonNull String constraintName) { return rewardConfigurable() .asConstraint(constraintName); } @Override default @NonNull Constraint rewardConfigurable(@NonNull String constraintPackage, @NonNull String constraintName) { return penalizeConfigurable() .asConstraint(constraintPackage, constraintName); } @Override default @NonNull Constraint impact(@NonNull String constraintName, @NonNull Score<?> constraintWeight) { return impact((Score) constraintWeight) .asConstraint(constraintName); } @Override default @NonNull Constraint impact(@NonNull String constraintPackage, @NonNull String constraintName, @NonNull Score<?> constraintWeight) { return impact((Score) constraintWeight) .asConstraint(constraintPackage, constraintName); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/tri/TriConstraintBuilderImpl.java
package ai.timefold.solver.core.impl.score.stream.common.tri; import java.util.Collection; import java.util.Objects; import ai.timefold.solver.core.api.function.QuadFunction; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.stream.ConstraintJustification; import ai.timefold.solver.core.api.score.stream.tri.TriConstraintBuilder; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintBuilder; import ai.timefold.solver.core.impl.score.stream.common.ScoreImpactType; import org.jspecify.annotations.NonNull; public final class TriConstraintBuilderImpl<A, B, C, Score_ extends Score<Score_>> extends AbstractConstraintBuilder<Score_> implements TriConstraintBuilder<A, B, C, Score_> { private QuadFunction<A, B, C, Score_, ConstraintJustification> justificationMapping; private TriFunction<A, B, C, Collection<Object>> indictedObjectsMapping; public TriConstraintBuilderImpl(TriConstraintConstructor<A, B, C, Score_> constraintConstructor, ScoreImpactType impactType, Score_ constraintWeight) { super(constraintConstructor, impactType, constraintWeight); } @Override protected QuadFunction<A, B, C, Score_, ConstraintJustification> getJustificationMapping() { return justificationMapping; } @Override public @NonNull <ConstraintJustification_ extends ConstraintJustification> TriConstraintBuilder<A, B, C, Score_> justifyWith( @NonNull QuadFunction<A, B, C, Score_, ConstraintJustification_> justificationMapping) { if (this.justificationMapping != null) { throw new IllegalStateException(""" Justification mapping already set (%s). Maybe the constraint calls justifyWith() twice?""" .formatted(justificationMapping)); } this.justificationMapping = (QuadFunction<A, B, C, Score_, ConstraintJustification>) Objects.requireNonNull(justificationMapping); return this; } @Override protected TriFunction<A, B, C, Collection<Object>> getIndictedObjectsMapping() { return indictedObjectsMapping; } @Override public @NonNull TriConstraintBuilder<A, B, C, Score_> indictWith(@NonNull TriFunction<A, B, C, Collection<Object>> indictedObjectsMapping) { if (this.indictedObjectsMapping != null) { throw new IllegalStateException(""" Indicted objects' mapping already set (%s). Maybe the constraint calls indictWith() twice?""" .formatted(indictedObjectsMapping)); } this.indictedObjectsMapping = Objects.requireNonNull(indictedObjectsMapping); return this; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/tri/TriConstraintConstructor.java
package ai.timefold.solver.core.impl.score.stream.common.tri; import java.util.Collection; import ai.timefold.solver.core.api.function.QuadFunction; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.score.stream.common.ConstraintConstructor; @FunctionalInterface public interface TriConstraintConstructor<A, B, C, Score_ extends Score<Score_>> extends ConstraintConstructor<Score_, QuadFunction<A, B, C, Score_, Object>, TriFunction<A, B, C, Collection<?>>> { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/uni/InnerUniConstraintStream.java
package ai.timefold.solver.core.impl.score.stream.common.uni; import static ai.timefold.solver.core.impl.score.stream.common.RetrievalSemantics.STANDARD; import java.math.BigDecimal; import java.util.Collection; import java.util.Collections; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.ToIntFunction; import java.util.function.ToLongFunction; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.stream.Constraint; import ai.timefold.solver.core.api.score.stream.ConstraintFactory; import ai.timefold.solver.core.api.score.stream.DefaultConstraintJustification; import ai.timefold.solver.core.api.score.stream.bi.BiConstraintStream; import ai.timefold.solver.core.api.score.stream.bi.BiJoiner; import ai.timefold.solver.core.api.score.stream.uni.UniConstraintBuilder; import ai.timefold.solver.core.api.score.stream.uni.UniConstraintStream; import ai.timefold.solver.core.impl.bavet.bi.joiner.BiJoinerComber; import ai.timefold.solver.core.impl.score.stream.common.RetrievalSemantics; import ai.timefold.solver.core.impl.score.stream.common.ScoreImpactType; import ai.timefold.solver.core.impl.util.ConstantLambdaUtils; import org.jspecify.annotations.NonNull; public interface InnerUniConstraintStream<A> extends UniConstraintStream<A> { static <A> BiFunction<A, Score<?>, DefaultConstraintJustification> createDefaultJustificationMapping() { return (a, score) -> DefaultConstraintJustification.of(score, a); } static <A> Function<A, Collection<?>> createDefaultIndictedObjectsMapping() { return Collections::singletonList; } RetrievalSemantics getRetrievalSemantics(); /** * This method returns true if the constraint stream is guaranteed to only produce distinct tuples. * See {@link #distinct()} for details. * * @return true if the guarantee of distinct tuples is provided */ boolean guaranteesDistinct(); @Override default @NonNull <B> BiConstraintStream<A, B> join(@NonNull Class<B> otherClass, @NonNull BiJoiner<A, B>... joiners) { if (getRetrievalSemantics() == STANDARD) { return join(getConstraintFactory().forEach(otherClass), joiners); } else { return join(getConstraintFactory().from(otherClass), joiners); } } /** * Allows {@link ConstraintFactory#forEachUniquePair(Class)} to reuse the joiner combing logic. * * @param otherStream never null * @param joinerComber never null * @param <B> * @return never null */ <B> BiConstraintStream<A, B> join(UniConstraintStream<B> otherStream, BiJoinerComber<A, B> joinerComber); @Override default @NonNull <B> UniConstraintStream<A> ifExists(@NonNull Class<B> otherClass, @NonNull BiJoiner<A, B>... joiners) { if (getRetrievalSemantics() == STANDARD) { return ifExists(getConstraintFactory().forEach(otherClass), joiners); } else { // Calls fromUnfiltered() for backward compatibility only return ifExists(getConstraintFactory().fromUnfiltered(otherClass), joiners); } } @Override default @NonNull <B> UniConstraintStream<A> ifExistsIncludingUnassigned(@NonNull Class<B> otherClass, @NonNull BiJoiner<A, B>... joiners) { if (getRetrievalSemantics() == STANDARD) { return ifExists(getConstraintFactory().forEachIncludingUnassigned(otherClass), joiners); } else { return ifExists(getConstraintFactory().fromUnfiltered(otherClass), joiners); } } @Override default @NonNull <B> UniConstraintStream<A> ifNotExists(@NonNull Class<B> otherClass, @NonNull BiJoiner<A, B>... joiners) { if (getRetrievalSemantics() == STANDARD) { return ifNotExists(getConstraintFactory().forEach(otherClass), joiners); } else { // Calls fromUnfiltered() for backward compatibility only return ifNotExists(getConstraintFactory().fromUnfiltered(otherClass), joiners); } } @Override default @NonNull <B> UniConstraintStream<A> ifNotExistsIncludingUnassigned(@NonNull Class<B> otherClass, @NonNull BiJoiner<A, B>... joiners) { if (getRetrievalSemantics() == STANDARD) { return ifNotExists(getConstraintFactory().forEachIncludingUnassigned(otherClass), joiners); } else { return ifNotExists(getConstraintFactory().fromUnfiltered(otherClass), joiners); } } @Override default @NonNull UniConstraintStream<A> distinct() { if (guaranteesDistinct()) { return this; } else { return groupBy(ConstantLambdaUtils.identity()); } } @Override default @NonNull <Score_ extends Score<Score_>> UniConstraintBuilder<A, Score_> penalize(@NonNull Score_ constraintWeight, @NonNull ToIntFunction<A> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.PENALTY); } @Override default @NonNull <Score_ extends Score<Score_>> UniConstraintBuilder<A, Score_> penalizeLong( @NonNull Score_ constraintWeight, @NonNull ToLongFunction<A> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.PENALTY); } @Override default @NonNull <Score_ extends Score<Score_>> UniConstraintBuilder<A, Score_> penalizeBigDecimal( @NonNull Score_ constraintWeight, @NonNull Function<A, BigDecimal> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.PENALTY); } @Override default UniConstraintBuilder<A, ?> penalizeConfigurable(ToIntFunction<A> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.PENALTY); } @Override default UniConstraintBuilder<A, ?> penalizeConfigurableLong(ToLongFunction<A> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.PENALTY); } @Override default UniConstraintBuilder<A, ?> penalizeConfigurableBigDecimal(Function<A, BigDecimal> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.PENALTY); } @Override default @NonNull <Score_ extends Score<Score_>> UniConstraintBuilder<A, Score_> reward(@NonNull Score_ constraintWeight, @NonNull ToIntFunction<A> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.REWARD); } @Override default @NonNull <Score_ extends Score<Score_>> UniConstraintBuilder<A, Score_> rewardLong(@NonNull Score_ constraintWeight, @NonNull ToLongFunction<A> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.REWARD); } @Override default @NonNull <Score_ extends Score<Score_>> UniConstraintBuilder<A, Score_> rewardBigDecimal( @NonNull Score_ constraintWeight, @NonNull Function<A, BigDecimal> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.REWARD); } @Override default UniConstraintBuilder<A, ?> rewardConfigurable(ToIntFunction<A> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.REWARD); } @Override default UniConstraintBuilder<A, ?> rewardConfigurableLong(ToLongFunction<A> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.REWARD); } @Override default UniConstraintBuilder<A, ?> rewardConfigurableBigDecimal(Function<A, BigDecimal> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.REWARD); } @Override default @NonNull <Score_ extends Score<Score_>> UniConstraintBuilder<A, Score_> impact(@NonNull Score_ constraintWeight, @NonNull ToIntFunction<A> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.MIXED); } @Override default @NonNull <Score_ extends Score<Score_>> UniConstraintBuilder<A, Score_> impactLong(@NonNull Score_ constraintWeight, @NonNull ToLongFunction<A> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.MIXED); } @Override default @NonNull <Score_ extends Score<Score_>> UniConstraintBuilder<A, Score_> impactBigDecimal( @NonNull Score_ constraintWeight, @NonNull Function<A, BigDecimal> matchWeigher) { return innerImpact(constraintWeight, matchWeigher, ScoreImpactType.MIXED); } @Override default UniConstraintBuilder<A, ?> impactConfigurable(ToIntFunction<A> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.MIXED); } @Override default UniConstraintBuilder<A, ?> impactConfigurableLong(ToLongFunction<A> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.MIXED); } @Override default UniConstraintBuilder<A, ?> impactConfigurableBigDecimal(Function<A, BigDecimal> matchWeigher) { return innerImpact(null, matchWeigher, ScoreImpactType.MIXED); } <Score_ extends Score<Score_>> UniConstraintBuilder<A, Score_> innerImpact(Score_ constraintWeight, ToIntFunction<A> matchWeigher, ScoreImpactType scoreImpactType); <Score_ extends Score<Score_>> UniConstraintBuilder<A, Score_> innerImpact(Score_ constraintWeight, ToLongFunction<A> matchWeigher, ScoreImpactType scoreImpactType); <Score_ extends Score<Score_>> UniConstraintBuilder<A, Score_> innerImpact(Score_ constraintWeight, Function<A, BigDecimal> matchWeigher, ScoreImpactType scoreImpactType); @Override default @NonNull Constraint penalize(@NonNull String constraintName, @NonNull Score<?> constraintWeight) { return penalize((Score) constraintWeight) .asConstraint(constraintName); } @Override default @NonNull Constraint penalize(@NonNull String constraintPackage, @NonNull String constraintName, @NonNull Score<?> constraintWeight) { return penalize((Score) constraintWeight) .asConstraint(constraintPackage, constraintName); } @Override default @NonNull Constraint penalizeConfigurable(@NonNull String constraintName) { return penalizeConfigurable() .asConstraint(constraintName); } @Override default @NonNull Constraint penalizeConfigurable(@NonNull String constraintPackage, @NonNull String constraintName) { return penalizeConfigurable() .asConstraint(constraintPackage, constraintName); } @Override default @NonNull Constraint reward(@NonNull String constraintName, @NonNull Score<?> constraintWeight) { return reward((Score) constraintWeight) .asConstraint(constraintName); } @Override default @NonNull Constraint reward(@NonNull String constraintPackage, @NonNull String constraintName, @NonNull Score<?> constraintWeight) { return reward((Score) constraintWeight) .asConstraint(constraintPackage, constraintName); } @Override default @NonNull Constraint rewardConfigurable(@NonNull String constraintName) { return rewardConfigurable() .asConstraint(constraintName); } @Override default @NonNull Constraint rewardConfigurable(@NonNull String constraintPackage, @NonNull String constraintName) { return penalizeConfigurable() .asConstraint(constraintPackage, constraintName); } @Override default @NonNull Constraint impact(@NonNull String constraintName, @NonNull Score<?> constraintWeight) { return impact((Score) constraintWeight) .asConstraint(constraintName); } @Override default @NonNull Constraint impact(@NonNull String constraintPackage, @NonNull String constraintName, @NonNull Score<?> constraintWeight) { return impact((Score) constraintWeight) .asConstraint(constraintPackage, constraintName); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/uni/UniConstraintBuilderImpl.java
package ai.timefold.solver.core.impl.score.stream.common.uni; import java.util.Collection; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Function; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.stream.ConstraintJustification; import ai.timefold.solver.core.api.score.stream.uni.UniConstraintBuilder; import ai.timefold.solver.core.impl.score.stream.common.AbstractConstraintBuilder; import ai.timefold.solver.core.impl.score.stream.common.ScoreImpactType; import org.jspecify.annotations.NonNull; public final class UniConstraintBuilderImpl<A, Score_ extends Score<Score_>> extends AbstractConstraintBuilder<Score_> implements UniConstraintBuilder<A, Score_> { private BiFunction<A, Score_, ConstraintJustification> justificationMapping; private Function<A, Collection<Object>> indictedObjectsMapping; public UniConstraintBuilderImpl(UniConstraintConstructor<A, Score_> constraintConstructor, ScoreImpactType impactType, Score_ constraintWeight) { super(constraintConstructor, impactType, constraintWeight); } @Override protected BiFunction<A, Score_, ConstraintJustification> getJustificationMapping() { return justificationMapping; } @Override public @NonNull <ConstraintJustification_ extends ConstraintJustification> UniConstraintBuilder<A, Score_> justifyWith( @NonNull BiFunction<A, Score_, ConstraintJustification_> justificationMapping) { if (this.justificationMapping != null) { throw new IllegalStateException(""" Justification mapping already set (%s). Maybe the constraint calls justifyWith() twice?""" .formatted(justificationMapping)); } this.justificationMapping = (BiFunction<A, Score_, ConstraintJustification>) Objects.requireNonNull(justificationMapping); return this; } @Override protected Function<A, Collection<Object>> getIndictedObjectsMapping() { return indictedObjectsMapping; } @Override public @NonNull UniConstraintBuilder<A, Score_> indictWith(@NonNull Function<A, Collection<Object>> indictedObjectsMapping) { if (this.indictedObjectsMapping != null) { throw new IllegalStateException(""" Indicted objects' mapping already set (%s). Maybe the constraint calls indictWith() twice?""" .formatted(indictedObjectsMapping)); } this.indictedObjectsMapping = Objects.requireNonNull(indictedObjectsMapping); return this; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/stream/common/uni/UniConstraintConstructor.java
package ai.timefold.solver.core.impl.score.stream.common.uni; import java.util.Collection; import java.util.function.BiFunction; import java.util.function.Function; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.score.stream.common.ConstraintConstructor; @FunctionalInterface public interface UniConstraintConstructor<A, Score_ extends Score<Score_>> extends ConstraintConstructor<Score_, BiFunction<A, Score_, Object>, Function<A, Collection<?>>> { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/trend/InitializingScoreTrend.java
package ai.timefold.solver.core.impl.score.trend; import java.util.Arrays; import java.util.stream.Collectors; import java.util.stream.Stream; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel; /** * Bounds the possible {@link Score}s for a {@link PlanningSolution} as more and more variables are initialized * (while the already initialized variables don't change). * * @see InitializingScoreTrendLevel */ public record InitializingScoreTrend(InitializingScoreTrendLevel[] trendLevels) { public static InitializingScoreTrend parseTrend(String initializingScoreTrendString, int levelsSize) { var trendTokens = initializingScoreTrendString.split("/"); var tokenIsSingle = trendTokens.length == 1; if (!tokenIsSingle && trendTokens.length != levelsSize) { throw new IllegalArgumentException(""" The initializingScoreTrendString (%s) doesn't follow the correct pattern (%s): \ the trendTokens length (%d) differs from the levelsSize (%d).""" .formatted(initializingScoreTrendString, buildTrendPattern(levelsSize), trendTokens.length, levelsSize)); } var trendLevels = new InitializingScoreTrendLevel[levelsSize]; for (var i = 0; i < levelsSize; i++) { trendLevels[i] = InitializingScoreTrendLevel.valueOf(trendTokens[tokenIsSingle ? 0 : i]); } return new InitializingScoreTrend(trendLevels); } public static InitializingScoreTrend buildUniformTrend(InitializingScoreTrendLevel trendLevel, int levelsSize) { var trendLevels = new InitializingScoreTrendLevel[levelsSize]; Arrays.fill(trendLevels, trendLevel); return new InitializingScoreTrend(trendLevels); } private static String buildTrendPattern(int levelsSize) { return Stream.generate(InitializingScoreTrendLevel.ANY::name) .limit(levelsSize) .collect(Collectors.joining("/")); } // ************************************************************************ // Complex methods // ************************************************************************ public int getLevelsSize() { return trendLevels.length; } public boolean isOnlyUp() { for (var trendLevel : trendLevels) { if (trendLevel != InitializingScoreTrendLevel.ONLY_UP) { return false; } } return true; } public boolean isOnlyDown() { for (var trendLevel : trendLevels) { if (trendLevel != InitializingScoreTrendLevel.ONLY_DOWN) { return false; } } return true; } @Override public boolean equals(Object o) { return o instanceof InitializingScoreTrend that && Arrays.equals(trendLevels, that.trendLevels); } @Override public int hashCode() { return Arrays.hashCode(trendLevels); } @Override public String toString() { return "InitializingScoreTrend(%s)".formatted(Arrays.toString(trendLevels)); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/AbstractSolver.java
package ai.timefold.solver.core.impl.solver; import java.util.Iterator; import java.util.List; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.solver.Solver; import ai.timefold.solver.core.api.solver.event.SolverEventListener; import ai.timefold.solver.core.impl.phase.Phase; import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleListener; import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleSupport; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope; import ai.timefold.solver.core.impl.solver.event.SolverEventSupport; import ai.timefold.solver.core.impl.solver.recaller.BestSolutionRecaller; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import ai.timefold.solver.core.impl.solver.termination.PhaseTermination; import ai.timefold.solver.core.impl.solver.termination.UniversalTermination; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Common code between {@link DefaultSolver} and child solvers. * <p> * Do not create a new child {@link Solver} to implement a new heuristic or metaheuristic, * just use a new {@link Phase} for that. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @see Solver * @see DefaultSolver */ public abstract class AbstractSolver<Solution_> implements Solver<Solution_> { protected final transient Logger logger = LoggerFactory.getLogger(getClass()); private final SolverEventSupport<Solution_> solverEventSupport = new SolverEventSupport<>(this); private final PhaseLifecycleSupport<Solution_> phaseLifecycleSupport = new PhaseLifecycleSupport<>(); protected final BestSolutionRecaller<Solution_> bestSolutionRecaller; // Note that the DefaultSolver.basicPlumbingTermination is a component of this termination. // Called "globalTermination" to clearly distinguish from "phaseTermination" inside AbstractPhase. protected final UniversalTermination<Solution_> globalTermination; protected final List<Phase<Solution_>> phaseList; // ************************************************************************ // Constructors and simple getters/setters // ************************************************************************ protected AbstractSolver(BestSolutionRecaller<Solution_> bestSolutionRecaller, UniversalTermination<Solution_> globalTermination, List<Phase<Solution_>> phaseList) { this.bestSolutionRecaller = bestSolutionRecaller; this.globalTermination = globalTermination; bestSolutionRecaller.setSolverEventSupport(solverEventSupport); this.phaseList = List.copyOf(phaseList); } public void solvingStarted(SolverScope<Solution_> solverScope) { solverScope.setWorkingSolutionFromBestSolution(); bestSolutionRecaller.solvingStarted(solverScope); globalTermination.solvingStarted(solverScope); phaseLifecycleSupport.fireSolvingStarted(solverScope); // Using value range manager from the same score director as the working solution; this is a correct use. var problemSizeStatistics = solverScope.getScoreDirector() .getValueRangeManager() .getProblemSizeStatistics(); solverScope.setProblemSizeStatistics(problemSizeStatistics); for (Phase<Solution_> phase : phaseList) { phase.solvingStarted(solverScope); } } protected void runPhases(SolverScope<Solution_> solverScope) { if (!solverScope.getSolutionDescriptor().hasMovableEntities(solverScope.getScoreDirector())) { logger.info("Skipped all phases ({}): out of {} planning entities, none are movable (non-pinned).", phaseList.size(), solverScope.getWorkingEntityCount()); return; } Iterator<Phase<Solution_>> it = phaseList.iterator(); while (!globalTermination.isSolverTerminated(solverScope) && it.hasNext()) { Phase<Solution_> phase = it.next(); phase.solve(solverScope); // If there is a next phase, it starts from the best solution, which might differ from the working solution. // If there isn't, no need to planning clone the best solution to the working solution. if (it.hasNext()) { solverScope.setWorkingSolutionFromBestSolution(); } } } public void solvingEnded(SolverScope<Solution_> solverScope) { for (Phase<Solution_> phase : phaseList) { phase.solvingEnded(solverScope); } bestSolutionRecaller.solvingEnded(solverScope); globalTermination.solvingEnded(solverScope); phaseLifecycleSupport.fireSolvingEnded(solverScope); } public void solvingError(SolverScope<Solution_> solverScope, Exception exception) { phaseLifecycleSupport.fireSolvingError(solverScope, exception); for (Phase<Solution_> phase : phaseList) { phase.solvingError(solverScope, exception); } } public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { bestSolutionRecaller.phaseStarted(phaseScope); phaseLifecycleSupport.firePhaseStarted(phaseScope); globalTermination.phaseStarted(phaseScope); // Do not propagate to phases; the active phase does that for itself and they should not propagate further. } public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { bestSolutionRecaller.phaseEnded(phaseScope); phaseLifecycleSupport.firePhaseEnded(phaseScope); globalTermination.phaseEnded(phaseScope); // Do not propagate to phases; the active phase does that for itself and they should not propagate further. } public void stepStarted(AbstractStepScope<Solution_> stepScope) { bestSolutionRecaller.stepStarted(stepScope); phaseLifecycleSupport.fireStepStarted(stepScope); globalTermination.stepStarted(stepScope); // Do not propagate to phases; the active phase does that for itself and they should not propagate further. } public void stepEnded(AbstractStepScope<Solution_> stepScope) { bestSolutionRecaller.stepEnded(stepScope); phaseLifecycleSupport.fireStepEnded(stepScope); globalTermination.stepEnded(stepScope); // Do not propagate to phases; the active phase does that for itself and they should not propagate further. } @Override public void addEventListener(SolverEventListener<Solution_> eventListener) { solverEventSupport.addEventListener(eventListener); } @Override public void removeEventListener(SolverEventListener<Solution_> eventListener) { solverEventSupport.removeEventListener(eventListener); } /** * Add a {@link PhaseLifecycleListener} that is notified * of {@link PhaseLifecycleListener#solvingStarted(SolverScope) solving} events * and also of the {@link PhaseLifecycleListener#phaseStarted(AbstractPhaseScope) phase} * and the {@link PhaseLifecycleListener#stepStarted(AbstractStepScope) step} starting/ending events of all phases. * <p> * To get notified for only 1 phase, use {@link Phase#addPhaseLifecycleListener(PhaseLifecycleListener)} instead. * * @param phaseLifecycleListener never null */ public void addPhaseLifecycleListener(PhaseLifecycleListener<Solution_> phaseLifecycleListener) { phaseLifecycleSupport.addEventListener(phaseLifecycleListener); } /** * @param phaseLifecycleListener never null * @see #addPhaseLifecycleListener(PhaseLifecycleListener) */ public void removePhaseLifecycleListener(PhaseLifecycleListener<Solution_> phaseLifecycleListener) { phaseLifecycleSupport.removeEventListener(phaseLifecycleListener); } public boolean isTerminationSameAsSolverTermination(PhaseTermination<Solution_> phaseTermination) { return phaseTermination == globalTermination; } public BestSolutionRecaller<Solution_> getBestSolutionRecaller() { return bestSolutionRecaller; } public List<Phase<Solution_>> getPhaseList() { return phaseList; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/Assigner.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.ScoreAnalysisFetchPolicy; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked final class Assigner<Solution_, Score_ extends Score<Score_>, Recommendation_, In_, Out_> implements Function<InnerScoreDirector<Solution_, Score_>, List<Recommendation_>> { private final DefaultSolverFactory<Solution_> solverFactory; private final Function<In_, Out_> propositionFunction; private final RecommendationConstructor<Score_, Recommendation_, Out_> recommendationConstructor; private final ScoreAnalysisFetchPolicy fetchPolicy; private final Solution_ originalSolution; private final In_ originalElement; public Assigner(DefaultSolverFactory<Solution_> solverFactory, Function<In_, @Nullable Out_> propositionFunction, RecommendationConstructor<Score_, Recommendation_, Out_> recommendationConstructor, ScoreAnalysisFetchPolicy fetchPolicy, Solution_ originalSolution, In_ originalElement) { this.solverFactory = Objects.requireNonNull(solverFactory); this.propositionFunction = Objects.requireNonNull(propositionFunction); this.recommendationConstructor = Objects.requireNonNull(recommendationConstructor); this.fetchPolicy = Objects.requireNonNull(fetchPolicy); this.originalSolution = Objects.requireNonNull(originalSolution); this.originalElement = Objects.requireNonNull(originalElement); } @Override public List<Recommendation_> apply(InnerScoreDirector<Solution_, Score_> scoreDirector) { var initializationStatistics = scoreDirector.getValueRangeManager().getInitializationStatistics(); var uninitializedCount = initializationStatistics.uninitializedEntityCount() + initializationStatistics.unassignedValueCount(); if (uninitializedCount > 1) { throw new IllegalStateException(""" Solution (%s) has (%d) uninitialized elements. Assignment Recommendation API requires at most one uninitialized element in the solution.""" .formatted(originalSolution, uninitializedCount)); } var originalScoreAnalysis = scoreDirector.buildScoreAnalysis(fetchPolicy); var clonedElement = Objects.requireNonNull(scoreDirector.lookUpWorkingObject(originalElement)); var processor = new AssignmentProcessor<>(solverFactory, propositionFunction, recommendationConstructor, fetchPolicy, clonedElement, originalScoreAnalysis); return processor.apply(scoreDirector); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/AssignmentProcessor.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.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.domain.variable.descriptor.BasicVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableDemand; import ai.timefold.solver.core.impl.heuristic.move.LegacyMoveAdapter; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.ChangeMove; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained.ChainedChangeMove; import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListUnassignMove; import ai.timefold.solver.core.impl.move.director.MoveDirector; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import ai.timefold.solver.core.preview.api.domain.metamodel.PositionInList; import ai.timefold.solver.core.preview.api.move.Move; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked final class AssignmentProcessor<Solution_, Score_ extends Score<Score_>, Recommendation_, In_, Out_> implements Function<InnerScoreDirector<Solution_, Score_>, List<Recommendation_>> { private final DefaultSolverFactory<Solution_> solverFactory; private final Function<In_, @Nullable Out_> propositionFunction; private final RecommendationConstructor<Score_, Recommendation_, Out_> recommendationConstructor; private final ScoreAnalysisFetchPolicy fetchPolicy; private final ScoreAnalysis<Score_> originalScoreAnalysis; private final In_ clonedElement; public AssignmentProcessor(DefaultSolverFactory<Solution_> solverFactory, Function<In_, @Nullable Out_> propositionFunction, RecommendationConstructor<Score_, Recommendation_, Out_> recommendationConstructor, ScoreAnalysisFetchPolicy fetchPolicy, In_ clonedElement, ScoreAnalysis<Score_> originalScoreAnalysis) { this.solverFactory = Objects.requireNonNull(solverFactory); this.propositionFunction = Objects.requireNonNull(propositionFunction); this.recommendationConstructor = Objects.requireNonNull(recommendationConstructor); this.fetchPolicy = Objects.requireNonNull(fetchPolicy); this.originalScoreAnalysis = Objects.requireNonNull(originalScoreAnalysis); this.clonedElement = clonedElement; } @Override public List<Recommendation_> apply(InnerScoreDirector<Solution_, Score_> scoreDirector) { // The cloned element may already be assigned. // If it is, we need to unassign it before we can run the construction heuristic. var moveDirector = scoreDirector.getMoveDirector(); var supplyManager = scoreDirector.getSupplyManager(); var solutionDescriptor = solverFactory.getSolutionDescriptor(); var listVariableDescriptor = solutionDescriptor.getListVariableDescriptor(); if (listVariableDescriptor != null) { var demand = listVariableDescriptor.getStateDemand(); try (var listVariableStateSupply = supplyManager.demand(demand)) { var elementPosition = listVariableStateSupply.getElementPosition(clonedElement); if (elementPosition instanceof PositionInList positionInList) { // Unassign the cloned element. var entity = positionInList.entity(); var index = positionInList.index(); wrapAndExecute(moveDirector, new ListUnassignMove<>(listVariableDescriptor, entity, index)); } } } else { var entityDescriptor = solutionDescriptor.findEntityDescriptorOrFail(clonedElement.getClass()); for (var variableDescriptor : entityDescriptor.getGenuineVariableDescriptorList()) { var basicVariableDescriptor = (BasicVariableDescriptor<Solution_>) variableDescriptor; if (basicVariableDescriptor.getValue(clonedElement) == null) { // The variable is already unassigned. continue; } // Uninitialize the basic variable. if (basicVariableDescriptor.isChained()) { var demand = new SingletonInverseVariableDemand<>(basicVariableDescriptor); var supply = supplyManager.demand(demand); wrapAndExecute(moveDirector, new ChainedChangeMove<>(basicVariableDescriptor, clonedElement, null, supply)); supplyManager.cancel(demand); } else { wrapAndExecute(moveDirector, new ChangeMove<>(basicVariableDescriptor, clonedElement, null)); } } } scoreDirector.triggerVariableListeners(); // 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_>(solverFactory.getClock()); solverScope.setWorkingRandom(new Random(0)); // We will evaluate every option; random does not matter. solverScope.setScoreDirector(scoreDirector); var phaseScope = new ConstructionHeuristicPhaseScope<>(solverScope, -1); 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 recommendedAssignmentList = new ArrayList<Recommendation_>(); var moveIndex = 0L; for (var move : placement) { recommendedAssignmentList.add(execute(scoreDirector, move, moveIndex, clonedElement, propositionFunction)); moveIndex++; } recommendedAssignmentList.sort(null); return recommendedAssignmentList; } finally { entityPlacer.stepEnded(stepScope); entityPlacer.phaseEnded(phaseScope); entityPlacer.solvingEnded(solverScope); } } private void wrapAndExecute(MoveDirector<Solution_, Score_> moveDirector, ai.timefold.solver.core.impl.heuristic.move.Move<Solution_> move) { // No need to call moveDirector.execute(), // as legacy moves were guaranteed to trigger shadow vars as part of their contract. new LegacyMoveAdapter<>(move).execute(moveDirector); } private EntityPlacer<Solution_> buildEntityPlacer() { var solver = (DefaultSolver<Solution_>) solverFactory.buildSolver(); var phaseList = solver.getPhaseList(); var constructionHeuristicCount = phaseList.stream() .filter(DefaultConstructionHeuristicPhase.class::isInstance) .count(); if (constructionHeuristicCount != 1) { throw new IllegalStateException( "Assignment 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( "Assignment Recommendation API requires the first solver phase (%s) in the solver config to be a construction heuristic." .formatted(phase)); } } private Recommendation_ execute(InnerScoreDirector<Solution_, Score_> scoreDirector, Move<Solution_> move, long moveIndex, In_ clonedElement, Function<In_, @Nullable Out_> propositionFunction) { return scoreDirector.getMoveDirector().executeTemporary(move, (moveDirector, score) -> { var newScoreAnalysis = scoreDirector.buildScoreAnalysis(fetchPolicy); var newScoreDifference = newScoreAnalysis.diff(originalScoreAnalysis); return recommendationConstructor.apply(moveIndex, propositionFunction.apply(clonedElement), newScoreDifference); }); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/BestSolutionContainingProblemChanges.java
package ai.timefold.solver.core.impl.solver; import java.util.List; import java.util.concurrent.CompletableFuture; final class BestSolutionContainingProblemChanges<Solution_> { private final Solution_ bestSolution; private final List<CompletableFuture<Void>> containedProblemChanges; public BestSolutionContainingProblemChanges(Solution_ bestSolution, List<CompletableFuture<Void>> containedProblemChanges) { this.bestSolution = bestSolution; this.containedProblemChanges = containedProblemChanges; } public Solution_ getBestSolution() { return bestSolution; } public void completeProblemChanges() { containedProblemChanges.forEach(futureProblemChange -> futureProblemChange.complete(null)); } public void completeProblemChangesExceptionally(Throwable exception) { containedProblemChanges.forEach(futureProblemChange -> futureProblemChange.completeExceptionally(exception)); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/BestSolutionHolder.java
package ai.timefold.solver.core.impl.solver; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BooleanSupplier; import java.util.function.UnaryOperator; import ai.timefold.solver.core.api.solver.Solver; import ai.timefold.solver.core.api.solver.change.ProblemChange; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; /** * The goal of this class is to register problem changes and best solutions in a thread-safe way. * Problem changes are {@link #addProblemChange(Solver, List) put in a queue} * and later associated with the best solution which contains them. * The best solution is associated with a version number * that is incremented each time a {@link #set new best solution is set}. * The best solution is {@link #take() taken} together with all problem changes * that were registered before the best solution was set. * * <p> * This class needs to be thread-safe. * * @param <Solution_> */ @NullMarked final class BestSolutionHolder<Solution_> { private final AtomicReference<BigInteger> lastProcessedVersion = new AtomicReference<>(BigInteger.valueOf(-1)); // These references are non-final and being accessed from multiple threads, // therefore they need to be volatile and all access synchronized. // Both the map and the best solution are based on the current version, // and therefore access to both needs to be guarded by the same lock. // The version is BigInteger to avoid long overflow. // The solver can run potentially forever, so long overflow is a (remote) possibility. private volatile SortedMap<BigInteger, List<CompletableFuture<Void>>> problemChangesPerVersionMap = createNewProblemChangesMap(); private volatile @Nullable VersionedBestSolution<Solution_> versionedBestSolution = null; private volatile BigInteger currentVersion = BigInteger.ZERO; private static SortedMap<BigInteger, List<CompletableFuture<Void>>> createNewProblemChangesMap() { return createNewProblemChangesMap(Collections.emptySortedMap()); } private static SortedMap<BigInteger, List<CompletableFuture<Void>>> createNewProblemChangesMap(SortedMap<BigInteger, List<CompletableFuture<Void>>> map) { return new TreeMap<>(map); } synchronized boolean isEmpty() { return this.versionedBestSolution == null; } /** * @return the last best solution together with problem changes the solution contains. * If there is no new best solution, returns null. */ @Nullable BestSolutionContainingProblemChanges<Solution_> take() { var latestVersionedBestSolution = resetVersionedBestSolution(); if (latestVersionedBestSolution == null) { return null; } var bestSolutionVersion = latestVersionedBestSolution.version(); var latestProcessedVersion = this.lastProcessedVersion.getAndUpdate(bestSolutionVersion::max); if (latestProcessedVersion.compareTo(bestSolutionVersion) > 0) { // Corner case: The best solution has already been taken, // because a later take() was scheduled to run before an earlier take(). // This causes the later take() to return the latest best solution and all the problem changes, // and the earlier best solution to be skipped entirely. return null; } // The map is replaced by a map containing only the problem changes that are not contained in the best solution. // This is fully synchronized, so no other thread can access the old map anymore. // The old map can then be processed by the current thread without synchronization. // The copying of maps is possibly expensive, but due to the nature of problem changes, // we do not expect the map to ever get too big. // It is not practical to submit a problem change every second, as that gives the solver no time to react. // This limits the size of the map on input. // The solver also finds new best solutions, which regularly trims the size of the map as well. var boundaryVersion = bestSolutionVersion.add(BigInteger.ONE); var oldProblemChangesPerVersion = replaceMapSynchronized(map -> createNewProblemChangesMap(map.tailMap(boundaryVersion))); // At this point, the old map is not accessible to any other thread. // We also do not need to clear it, because this being the only reference, // garbage collector will do it for us. var containedProblemChanges = oldProblemChangesPerVersion.headMap(boundaryVersion) .values() .stream() .flatMap(Collection::stream) .toList(); return new BestSolutionContainingProblemChanges<>(latestVersionedBestSolution.bestSolution(), containedProblemChanges); } private synchronized @Nullable VersionedBestSolution<Solution_> resetVersionedBestSolution() { var oldVersionedBestSolution = this.versionedBestSolution; this.versionedBestSolution = null; return oldVersionedBestSolution; } private synchronized SortedMap<BigInteger, List<CompletableFuture<Void>>> replaceMapSynchronized( UnaryOperator<SortedMap<BigInteger, List<CompletableFuture<Void>>>> replaceFunction) { var oldMap = problemChangesPerVersionMap; problemChangesPerVersionMap = replaceFunction.apply(oldMap); return oldMap; } /** * Sets the new best solution if all known problem changes have been processed * and thus are contained in this best solution. * * @param bestSolution the new best solution that replaces the previous one if there is any * @param isEveryProblemChangeProcessed a supplier that tells if all problem changes have been processed */ void set(Solution_ bestSolution, BooleanSupplier isEveryProblemChangeProcessed) { // The new best solution can be accepted only if there are no pending problem changes // nor any additional changes may come during this operation. // Otherwise, a race condition might occur // that leads to associating problem changes with a solution that was created later, // but does not contain them yet. // As a result, CompletableFutures representing these changes would be completed too early. if (isEveryProblemChangeProcessed.getAsBoolean()) { synchronized (this) { versionedBestSolution = new VersionedBestSolution<>(bestSolution, currentVersion); currentVersion = currentVersion.add(BigInteger.ONE); } } } /** * Adds a batch of problem changes to a solver and registers them * to be later retrieved together with a relevant best solution by the {@link #take()} method. * * @return CompletableFuture that will be completed after the best solution containing this change is passed to * a user-defined Consumer. */ @NonNull CompletableFuture<Void> addProblemChange(Solver<Solution_> solver, List<ProblemChange<Solution_>> problemChangeList) { var futureProblemChange = new CompletableFuture<Void>(); synchronized (this) { var futureProblemChangeList = problemChangesPerVersionMap.computeIfAbsent(currentVersion, version -> new ArrayList<>()); futureProblemChangeList.add(futureProblemChange); solver.addProblemChanges(problemChangeList); } return futureProblemChange; } void cancelPendingChanges() { // We first replace the reference with a new map, fully synchronized. // Then we process the old map unsynchronized, which is safe because no one can access it anymore. // We do not need to clear it, because this being the only reference, // the garbage collector will do it for us. replaceMapSynchronized(map -> createNewProblemChangesMap()) .values() .stream() .flatMap(Collection::stream) .forEach(pendingProblemChange -> pendingProblemChange.cancel(false)); } private record VersionedBestSolution<Solution_>(Solution_ bestSolution, BigInteger version) { } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/ClassInstanceCache.java
package ai.timefold.solver.core.impl.solver; import java.util.IdentityHashMap; import java.util.Map; import ai.timefold.solver.core.config.solver.SolverConfig; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.heuristic.selector.common.nearby.NearbyDistanceMeter; /** * Exists so that particular user-provided classes, * which are instantiated by Timefold from {@link SolverConfig}, * only ever have one instance. * Each solver instance needs to get a fresh instance of this class, * so that solvers can not share state between them. * <p> * Case in point, {@link NearbyDistanceMeter}. * If two places in the config reference the same implementation of this interface, * we can be sure that they represent the same logic. * And since it is us who instantiate them and they require no-arg constructors, * we can be reasonably certain that they will not contain any context-specific state. * Therefore it is safe to have all of these references served by a single instance, * allowing for all sorts of beneficial caching. * (Such as, in this case, nearby distance matrix caching across the solver.) * * @see ConfigUtils#newInstance(Object, String, Class) */ public final class ClassInstanceCache { public static ClassInstanceCache create() { return new ClassInstanceCache(); } private final Map<Class, Object> singletonMap = new IdentityHashMap<>(); private ClassInstanceCache() { } public <T> T newInstance(Object configBean, String propertyName, Class<T> clazz) { return (T) singletonMap.computeIfAbsent(clazz, key -> ConfigUtils.newInstance(configBean, propertyName, key)); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/ConsumerSupport.java
package ai.timefold.solver.core.impl.solver; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.function.BiConsumer; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import ai.timefold.solver.core.api.solver.SolverJobBuilder.FirstInitializedSolutionConsumer; final class ConsumerSupport<Solution_, ProblemId_> implements AutoCloseable { private final ProblemId_ problemId; private final Consumer<? super Solution_> bestSolutionConsumer; private final Consumer<? super Solution_> finalBestSolutionConsumer; private final FirstInitializedSolutionConsumer<? super Solution_> firstInitializedSolutionConsumer; private final Consumer<? super Solution_> solverJobStartedConsumer; private final BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler; private final Semaphore activeConsumption = new Semaphore(1); private final Semaphore firstSolutionConsumption = new Semaphore(1); private final Semaphore startSolverJobConsumption = new Semaphore(1); private final BestSolutionHolder<Solution_> bestSolutionHolder; private final ExecutorService consumerExecutor = Executors.newSingleThreadExecutor(); private Solution_ firstInitializedSolution; private Solution_ initialSolution; public ConsumerSupport(ProblemId_ problemId, Consumer<? super Solution_> bestSolutionConsumer, Consumer<? super Solution_> finalBestSolutionConsumer, FirstInitializedSolutionConsumer<? super Solution_> firstInitializedSolutionConsumer, Consumer<? super Solution_> solverJobStartedConsumer, BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler, BestSolutionHolder<Solution_> bestSolutionHolder) { this.problemId = problemId; this.bestSolutionConsumer = bestSolutionConsumer; this.finalBestSolutionConsumer = finalBestSolutionConsumer == null ? finalBestSolution -> { } : finalBestSolutionConsumer; this.firstInitializedSolutionConsumer = firstInitializedSolutionConsumer == null ? (solution, isTerminatedEarly) -> { } : firstInitializedSolutionConsumer; this.solverJobStartedConsumer = solverJobStartedConsumer; this.exceptionHandler = exceptionHandler; this.bestSolutionHolder = bestSolutionHolder; this.firstInitializedSolution = null; this.initialSolution = null; } // Called on the Solver thread. void consumeIntermediateBestSolution(Solution_ bestSolution, BooleanSupplier isEveryProblemChangeProcessed) { /* * If the bestSolutionConsumer is not provided, the best solution is still set for the purpose of recording * problem changes. */ bestSolutionHolder.set(bestSolution, isEveryProblemChangeProcessed); if (bestSolutionConsumer != null) { tryConsumeWaitingIntermediateBestSolution(); } } // Called on the Solver thread. void consumeFirstInitializedSolution(Solution_ firstInitializedSolution, boolean isTerminatedEarly) { try { // Called on the solver thread // During the solving process, this lock is called once, and it won't block the Solver thread firstSolutionConsumption.acquire(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Interrupted when waiting for the first initialized solution consumption."); } // called on the Consumer thread this.firstInitializedSolution = firstInitializedSolution; scheduleFirstInitializedSolutionConsumption( solution -> firstInitializedSolutionConsumer.accept(solution, isTerminatedEarly)); } // Called on the consumer thread void consumeStartSolverJob(Solution_ initialSolution) { try { // Called on the solver thread // During the solving process, this lock is called once, and it won't block the Solver thread startSolverJobConsumption.acquire(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Interrupted when waiting for the start solver job consumption."); } // called on the Consumer thread this.initialSolution = initialSolution; scheduleStartJobConsumption(); } // Called on the Solver thread after Solver#solve() returns. void consumeFinalBestSolution(Solution_ finalBestSolution) { try { acquireAll(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Interrupted when waiting for the final best solution consumption."); } // Make sure the final best solution is consumed by the intermediate best solution consumer first. // Situation: // The consumer is consuming the last but one best solution. The final best solution is waiting for the consumer. if (bestSolutionConsumer != null) { scheduleIntermediateBestSolutionConsumption(); } consumerExecutor.submit(() -> { try { finalBestSolutionConsumer.accept(finalBestSolution); } catch (Throwable throwable) { exceptionHandler.accept(problemId, throwable); } finally { // If there is no intermediate best solution consumer, complete the problem changes now. if (bestSolutionConsumer == null) { var solutionHolder = bestSolutionHolder.take(); if (solutionHolder != null) { solutionHolder.completeProblemChanges(); } } // Cancel problem changes that arrived after the solver terminated. bestSolutionHolder.cancelPendingChanges(); releaseAll(); disposeConsumerThread(); } }); } // Called both on the Solver thread and the Consumer thread. private void tryConsumeWaitingIntermediateBestSolution() { if (bestSolutionHolder.isEmpty()) { return; // There is no best solution to consume. } if (activeConsumption.tryAcquire()) { scheduleIntermediateBestSolutionConsumption().thenRunAsync(this::tryConsumeWaitingIntermediateBestSolution, consumerExecutor); } } /** * Called both on the Solver thread and the Consumer thread. * Don't call without locking, otherwise multiple consumptions may be scheduled. */ private CompletableFuture<Void> scheduleIntermediateBestSolutionConsumption() { return CompletableFuture.runAsync(() -> { BestSolutionContainingProblemChanges<Solution_> bestSolutionContainingProblemChanges = bestSolutionHolder.take(); if (bestSolutionContainingProblemChanges != null) { try { bestSolutionConsumer.accept(bestSolutionContainingProblemChanges.getBestSolution()); bestSolutionContainingProblemChanges.completeProblemChanges(); } catch (Throwable throwable) { if (exceptionHandler != null) { exceptionHandler.accept(problemId, throwable); } bestSolutionContainingProblemChanges.completeProblemChangesExceptionally(throwable); } finally { activeConsumption.release(); } } }, consumerExecutor); } /** * Called on the Consumer thread. * Don't call without locking firstSolutionConsumption, * because the consumption may not be executed before the final best solution is executed. */ private void scheduleFirstInitializedSolutionConsumption(Consumer<? super Solution_> firstInitializedSolutionConsumer) { scheduleConsumption(firstSolutionConsumption, firstInitializedSolutionConsumer, firstInitializedSolution); } /** * Called on the Consumer thread. * Don't call without locking startSolverJobConsumption, * because the consumption may not be executed before the final best solution is executed. */ private void scheduleStartJobConsumption() { scheduleConsumption(startSolverJobConsumption, solverJobStartedConsumer, initialSolution); } private void scheduleConsumption(Semaphore semaphore, Consumer<? super Solution_> consumer, Solution_ solution) { CompletableFuture.runAsync(() -> { try { if (consumer != null && solution != null) { consumer.accept(solution); } } catch (Throwable throwable) { if (exceptionHandler != null) { exceptionHandler.accept(problemId, throwable); } } finally { semaphore.release(); } }, consumerExecutor); } private void acquireAll() throws InterruptedException { // Wait for the previous consumption to complete. // As the solver has already finished, holding the solver thread is not an issue. activeConsumption.acquire(); // Wait for the start job event to complete startSolverJobConsumption.acquire(); // Wait for the first solution consumption to complete firstSolutionConsumption.acquire(); } private void releaseAll() { activeConsumption.release(); startSolverJobConsumption.release(); firstSolutionConsumption.release(); } @Override public void close() { try { acquireAll(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Interrupted when waiting for closing the consumer."); } finally { disposeConsumerThread(); bestSolutionHolder.cancelPendingChanges(); releaseAll(); } } private void disposeConsumerThread() { consumerExecutor.shutdownNow(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/DefaultRecommendedAssignment.java
package ai.timefold.solver.core.impl.solver; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.analysis.ScoreAnalysis; import ai.timefold.solver.core.api.solver.RecommendedAssignment; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked public record DefaultRecommendedAssignment<Proposition_, Score_ extends Score<Score_>>(long index, @Nullable Proposition_ proposition, ScoreAnalysis<Score_> scoreAnalysisDiff) implements RecommendedAssignment<Proposition_, Score_>, Comparable<DefaultRecommendedAssignment<Proposition_, Score_>> { @Override public int compareTo(DefaultRecommendedAssignment<Proposition_, Score_> other) { int scoreComparison = scoreAnalysisDiff.score().compareTo(other.scoreAnalysisDiff.score()); if (scoreComparison != 0) { return -scoreComparison; // Better scores first. } // Otherwise maintain insertion order. return Long.compareUnsigned(index, other.index); // Unsigned == many more positive values. } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/DefaultRecommendedFit.java
package ai.timefold.solver.core.impl.solver; 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 org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; /** * @deprecated Prefer {@link DefaultRecommendedAssignment} instead. */ @Deprecated(forRemoval = true, since = "1.15.0") @NullMarked public record DefaultRecommendedFit<Proposition_, Score_ extends Score<Score_>>(long index, @Nullable Proposition_ proposition, ScoreAnalysis<Score_> scoreAnalysisDiff) implements RecommendedFit<Proposition_, Score_>, Comparable<DefaultRecommendedFit<Proposition_, Score_>> { @Override public int compareTo(DefaultRecommendedFit<Proposition_, Score_> other) { int scoreComparison = scoreAnalysisDiff.score().compareTo(other.scoreAnalysisDiff.score()); if (scoreComparison != 0) { return -scoreComparison; // Better scores first. } // Otherwise maintain insertion order. return Long.compareUnsigned(index, other.index); // Unsigned == many more positive values. } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/DefaultSolutionManager.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.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.ScoreExplanation; import ai.timefold.solver.core.api.score.analysis.ScoreAnalysis; import ai.timefold.solver.core.api.solver.RecommendedAssignment; import ai.timefold.solver.core.api.solver.RecommendedFit; import ai.timefold.solver.core.api.solver.ScoreAnalysisFetchPolicy; import ai.timefold.solver.core.api.solver.SolutionManager; import ai.timefold.solver.core.api.solver.SolutionUpdatePolicy; import ai.timefold.solver.core.api.solver.SolverFactory; import ai.timefold.solver.core.api.solver.SolverManager; import ai.timefold.solver.core.config.solver.EnvironmentMode; import ai.timefold.solver.core.config.solver.PreviewFeature; import ai.timefold.solver.core.impl.domain.variable.declarative.ConsistencyTracker; import ai.timefold.solver.core.impl.score.DefaultScoreExplanation; import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; import ai.timefold.solver.core.impl.score.director.ScoreDirectorFactory; import ai.timefold.solver.core.impl.score.director.stream.BavetConstraintStreamScoreDirectorFactory; import ai.timefold.solver.core.impl.util.MutableReference; import ai.timefold.solver.core.preview.api.domain.solution.diff.PlanningSolutionDiff; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ @NullMarked public final class DefaultSolutionManager<Solution_, Score_ extends Score<Score_>> implements SolutionManager<Solution_, Score_> { private final DefaultSolverFactory<Solution_> solverFactory; private final ScoreDirectorFactory<Solution_, Score_> scoreDirectorFactory; public <ProblemId_> DefaultSolutionManager(SolverManager<Solution_, ProblemId_> solverManager) { this(((DefaultSolverManager<Solution_, ProblemId_>) solverManager).getSolverFactory()); } public DefaultSolutionManager(SolverFactory<Solution_> solverFactory) { this.solverFactory = ((DefaultSolverFactory<Solution_>) solverFactory); this.scoreDirectorFactory = this.solverFactory.getScoreDirectorFactory(); } public ScoreDirectorFactory<Solution_, Score_> getScoreDirectorFactory() { return scoreDirectorFactory; } @Override public Score_ update(Solution_ solution, SolutionUpdatePolicy solutionUpdatePolicy) { if (solutionUpdatePolicy == SolutionUpdatePolicy.NO_UPDATE) { throw new IllegalArgumentException("Can not call " + this.getClass().getSimpleName() + ".update() with this solutionUpdatePolicy (" + solutionUpdatePolicy + ")."); } return callScoreDirector(solution, solutionUpdatePolicy, s -> s.getSolutionDescriptor().getScore(s.getWorkingSolution()), ConstraintMatchPolicy.DISABLED, false); } private <Result_> Result_ callScoreDirector(Solution_ solution, SolutionUpdatePolicy solutionUpdatePolicy, Function<InnerScoreDirector<Solution_, Score_>, Result_> function, ConstraintMatchPolicy constraintMatchPolicy, boolean cloneSolution) { var isShadowVariableUpdateEnabled = solutionUpdatePolicy.isShadowVariableUpdateEnabled(); var nonNullSolution = Objects.requireNonNull(solution); try (var scoreDirector = getScoreDirectorFactory().createScoreDirectorBuilder() .withLookUpEnabled(cloneSolution) .withConstraintMatchPolicy(constraintMatchPolicy) .withExpectShadowVariablesInCorrectState(!isShadowVariableUpdateEnabled) .build()) { nonNullSolution = cloneSolution ? scoreDirector.cloneSolution(nonNullSolution) : nonNullSolution; if (isShadowVariableUpdateEnabled) { scoreDirector.setWorkingSolution(nonNullSolution); } else { scoreDirector.setWorkingSolutionWithoutUpdatingShadows(nonNullSolution); } if (constraintMatchPolicy.isEnabled() && !scoreDirector.getConstraintMatchPolicy().isEnabled()) { throw new IllegalStateException(""" Requested constraint matching but score director doesn't support it. Maybe use Constraint Streams instead of Easy or Incremental score calculator?"""); } if (solutionUpdatePolicy.isScoreUpdateEnabled()) { scoreDirector.calculateScore(); } return function.apply(scoreDirector); } } @SuppressWarnings("unchecked") @Override public ScoreExplanation<Solution_, Score_> explain(Solution_ solution, SolutionUpdatePolicy solutionUpdatePolicy) { var currentScore = (Score_) scoreDirectorFactory.getSolutionDescriptor().getScore(solution); var explanation = callScoreDirector(solution, solutionUpdatePolicy, DefaultScoreExplanation::new, ConstraintMatchPolicy.ENABLED, false); assertFreshScore(solution, currentScore, explanation.getScore(), solutionUpdatePolicy); return explanation; } private void assertFreshScore(Solution_ solution, Score_ currentScore, Score_ calculatedScore, SolutionUpdatePolicy solutionUpdatePolicy) { if (!solutionUpdatePolicy.isScoreUpdateEnabled()) { // Score update is not enabled; this means the score is supposed to be valid. // Yet it is different from a freshly calculated score, suggesting previous score corruption. if (!Objects.equals(currentScore, calculatedScore)) { throw new IllegalStateException(""" Current score (%s) and freshly calculated score (%s) for solution (%s) do not match. Maybe run %s environment mode to check for score corruptions. Otherwise enable %s.%s to update the stale score. """ .formatted(currentScore, calculatedScore, solution, EnvironmentMode.TRACKED_FULL_ASSERT, SolutionUpdatePolicy.class.getSimpleName(), SolutionUpdatePolicy.UPDATE_ALL)); } } } @SuppressWarnings("unchecked") @Override public ScoreAnalysis<Score_> analyze(Solution_ solution, ScoreAnalysisFetchPolicy fetchPolicy, SolutionUpdatePolicy solutionUpdatePolicy) { Objects.requireNonNull(fetchPolicy, "fetchPolicy"); var currentScore = (Score_) scoreDirectorFactory.getSolutionDescriptor().getScore(solution); var analysis = callScoreDirector(solution, solutionUpdatePolicy, scoreDirector -> scoreDirector.buildScoreAnalysis(fetchPolicy), ConstraintMatchPolicy.match(fetchPolicy), false); assertFreshScore(solution, currentScore, analysis.score(), solutionUpdatePolicy); return analysis; } @Override public PlanningSolutionDiff<Solution_> diff(Solution_ oldSolution, Solution_ newSolution) { solverFactory.ensurePreviewFeature(PreviewFeature.PLANNING_SOLUTION_DIFF); return solverFactory.getSolutionDescriptor() .diff(oldSolution, newSolution); } @Override public <In_, Out_> List<RecommendedAssignment<Out_, Score_>> recommendAssignment(Solution_ solution, In_ evaluatedEntityOrElement, Function<In_, @Nullable Out_> propositionFunction, ScoreAnalysisFetchPolicy fetchPolicy) { var assigner = new Assigner<Solution_, Score_, RecommendedAssignment<Out_, Score_>, In_, Out_>(solverFactory, propositionFunction, DefaultRecommendedAssignment::new, fetchPolicy, solution, evaluatedEntityOrElement); return callScoreDirector(solution, SolutionUpdatePolicy.UPDATE_ALL, assigner, ConstraintMatchPolicy.match(fetchPolicy), true); } @Override public <In_, Out_> List<RecommendedFit<Out_, Score_>> recommendFit(Solution_ solution, In_ fittedEntityOrElement, Function<In_, @Nullable Out_> propositionFunction, ScoreAnalysisFetchPolicy fetchPolicy) { var assigner = new Assigner<Solution_, Score_, RecommendedFit<Out_, Score_>, In_, Out_>(solverFactory, propositionFunction, DefaultRecommendedFit::new, fetchPolicy, solution, fittedEntityOrElement); return callScoreDirector(solution, SolutionUpdatePolicy.UPDATE_ALL, assigner, ConstraintMatchPolicy.match(fetchPolicy), true); } /** * Generates a Bavet node network visualization for the given solution. * It uses a Graphviz DOT language representation. * The string returned by this method can be converted to an image using {@code dot}: * * <pre> * $ dot -Tsvg input.dot > output.svg * </pre> * * This assumes the string returned by this method is saved to a file named {@code input.dot}. * * <p> * The node network itself is an internal implementation detail of Constraint Streams. * Do not rely on any particular node network structure in production code, * and do not micro-optimize your constraints to match the node network. * Such optimizations are destined to become obsolete and possibly harmful as the node network evolves. * * <p> * This method is only provided for debugging purposes * and is deliberately not part of the public API. * Its signature or behavior may change without notice, * and it may be removed in future versions. * * @see <a href="https://graphviz.org/doc/info/lang.html">Graphviz DOT language</a> * * @param solution Will be used to read constraint weights, which determine the final node network. * @return A string representing the node network in Graphviz DOT language. */ public @Nullable String visualizeNodeNetwork(Solution_ solution) { if (scoreDirectorFactory instanceof BavetConstraintStreamScoreDirectorFactory<Solution_, ?> bavetScoreDirectorFactory) { var result = new MutableReference<String>(null); bavetScoreDirectorFactory.newSession(solution, new ConsistencyTracker<>(), ConstraintMatchPolicy.ENABLED, false, result::setValue); return result.getValue(); } throw new UnsupportedOperationException("Node network visualization is only supported when using Constraint Streams."); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/DefaultSolver.java
package ai.timefold.solver.core.impl.solver; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import ai.timefold.solver.core.api.domain.lookup.PlanningId; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.solver.ProblemFactChange; import ai.timefold.solver.core.api.solver.Solver; import ai.timefold.solver.core.api.solver.change.ProblemChange; import ai.timefold.solver.core.config.solver.EnvironmentMode; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; import ai.timefold.solver.core.impl.phase.Phase; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; import ai.timefold.solver.core.impl.score.director.ScoreDirectorFactory; import ai.timefold.solver.core.impl.solver.change.ProblemChangeAdapter; import ai.timefold.solver.core.impl.solver.random.RandomFactory; import ai.timefold.solver.core.impl.solver.recaller.BestSolutionRecaller; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import ai.timefold.solver.core.impl.solver.termination.BasicPlumbingTermination; import ai.timefold.solver.core.impl.solver.termination.UniversalTermination; import org.jspecify.annotations.NonNull; import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.Tags; /** * Default implementation for {@link Solver}. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @see Solver * @see AbstractSolver */ public class DefaultSolver<Solution_> extends AbstractSolver<Solution_> { protected EnvironmentMode environmentMode; protected RandomFactory randomFactory; protected BasicPlumbingTermination<Solution_> basicPlumbingTermination; protected final AtomicBoolean solving = new AtomicBoolean(false); protected final SolverScope<Solution_> solverScope; private final String moveThreadCountDescription; // ************************************************************************ // Constructors and simple getters/setters // ************************************************************************ public DefaultSolver(EnvironmentMode environmentMode, RandomFactory randomFactory, BestSolutionRecaller<Solution_> bestSolutionRecaller, BasicPlumbingTermination<Solution_> basicPlumbingTermination, UniversalTermination<Solution_> termination, List<Phase<Solution_>> phaseList, SolverScope<Solution_> solverScope, String moveThreadCountDescription) { super(bestSolutionRecaller, termination, phaseList); this.environmentMode = environmentMode; this.randomFactory = randomFactory; this.basicPlumbingTermination = basicPlumbingTermination; this.solverScope = solverScope; solverScope.setSolver(this); this.moveThreadCountDescription = moveThreadCountDescription; } public EnvironmentMode getEnvironmentMode() { return environmentMode; } public RandomFactory getRandomFactory() { return randomFactory; } public ScoreDirectorFactory<Solution_, ?> getScoreDirectorFactory() { return solverScope.getScoreDirector().getScoreDirectorFactory(); } public SolverScope<Solution_> getSolverScope() { return solverScope; } // ************************************************************************ // Complex getters // ************************************************************************ public long getTimeMillisSpent() { return solverScope.getTimeMillisSpent(); } public long getScoreCalculationCount() { return solverScope.getScoreCalculationCount(); } public long getMoveEvaluationCount() { return solverScope.getMoveEvaluationCount(); } public long getScoreCalculationSpeed() { return solverScope.getScoreCalculationSpeed(); } public long getMoveEvaluationSpeed() { return solverScope.getMoveEvaluationSpeed(); } @Override public boolean isSolving() { return solving.get(); } @Override public boolean terminateEarly() { var terminationEarlySuccessful = basicPlumbingTermination.terminateEarly(); if (terminationEarlySuccessful) { logger.info("Terminating solver early."); } return terminationEarlySuccessful; } @Override public boolean isTerminateEarly() { return basicPlumbingTermination.isTerminateEarly(); } @Override public boolean addProblemFactChange(@NonNull ProblemFactChange<Solution_> problemFactChange) { return addProblemFactChanges(Collections.singletonList(problemFactChange)); } @Override public boolean addProblemFactChanges(@NonNull List<ProblemFactChange<Solution_>> problemFactChangeList) { Objects.requireNonNull(problemFactChangeList, () -> "The list of problem fact changes (" + problemFactChangeList + ") cannot be null."); return basicPlumbingTermination.addProblemChanges(problemFactChangeList.stream() .map(ProblemChangeAdapter::create) .collect(Collectors.toList())); } @Override public void addProblemChange(@NonNull ProblemChange<Solution_> problemChange) { addProblemChanges(Collections.singletonList(problemChange)); } @Override public void addProblemChanges(@NonNull List<ProblemChange<Solution_>> problemChangeList) { Objects.requireNonNull(problemChangeList, () -> "The list of problem changes (" + problemChangeList + ") cannot be null."); basicPlumbingTermination.addProblemChanges(problemChangeList.stream() .map(ProblemChangeAdapter::create) .toList()); } @Override public boolean isEveryProblemChangeProcessed() { return basicPlumbingTermination.isEveryProblemChangeProcessed(); } @Override public boolean isEveryProblemFactChangeProcessed() { return isEveryProblemChangeProcessed(); } public void setMonitorTagMap(Map<String, String> monitorTagMap) { var monitoringTags = Objects.requireNonNullElse(monitorTagMap, Collections.<String, String> emptyMap()) .entrySet().stream().map(entry -> Tags.of(entry.getKey(), entry.getValue())) .reduce(Tags.empty(), Tags::and); solverScope.setMonitoringTags(monitoringTags); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public final @NonNull Solution_ solve(@NonNull Solution_ problem) { // No tags for these metrics; they are global var solveLengthTimer = Metrics.more().longTaskTimer(SolverMetric.SOLVE_DURATION.getMeterId()); var errorCounter = Metrics.counter(SolverMetric.ERROR_COUNT.getMeterId()); solverScope.setInitialSolution(Objects.requireNonNull(problem, "The problem must not be null.")); solverScope.setSolver(this); outerSolvingStarted(solverScope); var restartSolver = true; while (restartSolver) { var sample = solveLengthTimer.start(); try { // solvingStarted will call registerSolverSpecificMetrics(), since // the solverScope need to be fully initialized to calculate the // problem's scale metrics solvingStarted(solverScope); runPhases(solverScope); solvingEnded(solverScope); } catch (Exception e) { errorCounter.increment(); solvingError(solverScope, e); throw e; } finally { sample.stop(); unregisterSolverSpecificMetrics(); } restartSolver = checkProblemFactChanges(); } outerSolvingEnded(solverScope); return solverScope.getBestSolution(); } public void outerSolvingStarted(SolverScope<Solution_> solverScope) { solving.set(true); basicPlumbingTermination.resetTerminateEarly(); solverScope.setStartingSolverCount(0); solverScope.setWorkingRandom(randomFactory.createRandom()); } @Override public void solvingStarted(SolverScope<Solution_> solverScope) { assertCorrectSolutionState(); solverScope.startingNow(); solverScope.getScoreDirector().resetCalculationCount(); super.solvingStarted(solverScope); var startingSolverCount = solverScope.getStartingSolverCount() + 1; solverScope.setStartingSolverCount(startingSolverCount); registerSolverSpecificMetrics(); // Update the best solution, since problem's shadows and score were updated bestSolutionRecaller.updateBestSolutionAndFireIfInitialized(solverScope); logger.info("Solving {}: time spent ({}), best score ({}), " + "environment mode ({}), move thread count ({}), random ({}).", (startingSolverCount == 1 ? "started" : "restarted"), solverScope.calculateTimeMillisSpentUpToNow(), solverScope.getBestScore().raw(), environmentMode.name(), moveThreadCountDescription, (randomFactory != null ? randomFactory : "not fixed")); if (logger.isInfoEnabled()) { // Formatting is expensive here. var problemSizeStatistics = solverScope.getProblemSizeStatistics(); logger.info( "Problem scale: entity count ({}), variable count ({}), approximate value count ({}), approximate problem scale ({}).", problemSizeStatistics.entityCount(), problemSizeStatistics.variableCount(), problemSizeStatistics.approximateValueCount(), problemSizeStatistics.approximateProblemScaleAsFormattedString()); } } private void registerSolverSpecificMetrics() { solverScope.getSolverMetricSet().forEach(solverMetric -> solverMetric.register(this)); } private void unregisterSolverSpecificMetrics() { solverScope.getSolverMetricSet().forEach(solverMetric -> solverMetric.unregister(this)); } private void assertCorrectSolutionState() { var bestSolution = solverScope.getBestSolution(); solverScope.getSolutionDescriptor().visitAllProblemFacts(bestSolution, this::assertNonNullPlanningId); solverScope.getSolutionDescriptor().visitAllEntities(bestSolution, entity -> { assertNonNullPlanningId(entity); // Ensure correct state of pinning properties. var entityDescriptor = solverScope.getSolutionDescriptor().findEntityDescriptorOrFail(entity.getClass()); if (!entityDescriptor.supportsPinning() || !entityDescriptor.hasAnyGenuineListVariables()) { return; } var listVariableDescriptor = entityDescriptor.getGenuineListVariableDescriptor(); var pinIndex = listVariableDescriptor.getFirstUnpinnedIndex(entity); if (entityDescriptor.isMovable(solverScope.getScoreDirector().getWorkingSolution(), entity)) { if (pinIndex < 0) { throw new IllegalStateException("The movable planning entity (%s) has a pin index (%s) which is negative." .formatted(entity, pinIndex)); } var listSize = listVariableDescriptor.getListSize(entity); if (pinIndex > listSize) { // pinIndex == listSize is allowed, as that says the pin is at the end of the list, // allowing additions to the list. throw new IllegalStateException( "The movable planning entity (%s) has a pin index (%s) which is greater than the list size (%s)." .formatted(entity, pinIndex, listSize)); } } else { if (pinIndex != 0) { throw new IllegalStateException("The immovable planning entity (%s) has a pin index (%s) which is not 0." .formatted(entity, pinIndex)); } } }); } private void assertNonNullPlanningId(Object fact) { var factClass = fact.getClass(); var planningIdAccessor = solverScope.getSolutionDescriptor().getPlanningIdAccessor(factClass); if (planningIdAccessor == null) { // There is no planning ID annotation. return; } var id = planningIdAccessor.executeGetter(fact); if (id == null) { // Fail fast as planning ID is null. throw new IllegalStateException("The planningId (" + id + ") of the member (" + planningIdAccessor + ") of the class (" + factClass + ") on object (" + fact + ") must not be null.\n" + "Maybe initialize the planningId of the class (" + planningIdAccessor.getDeclaringClass() + ") instance (" + fact + ") before solving.\n" + "Maybe remove the @" + PlanningId.class.getSimpleName() + " annotation."); } } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { super.solvingEnded(solverScope); solverScope.endingNow(); } public void outerSolvingEnded(SolverScope<Solution_> solverScope) { logger.info("Solving ended: time spent ({}), best score ({}), move evaluation speed ({}/sec), " + "phase total ({}), environment mode ({}), move thread count ({}).", solverScope.getTimeMillisSpent(), solverScope.getBestScore().raw(), solverScope.getMoveEvaluationSpeed(), phaseList.size(), environmentMode.name(), moveThreadCountDescription); // Must be kept open for doProblemFactChange solverScope.getScoreDirector().close(); solving.set(false); } private boolean checkProblemFactChanges() { var restartSolver = basicPlumbingTermination.waitForRestartSolverDecision(); if (!restartSolver) { return false; } else { var problemFactChangeQueue = basicPlumbingTermination .startProblemChangesProcessing(); solverScope.setWorkingSolutionFromBestSolution(); var stepIndex = 0; var problemChangeAdapter = problemFactChangeQueue.poll(); while (problemChangeAdapter != null) { problemChangeAdapter.doProblemChange(solverScope); logger.debug(" Real-time problem change applied; step index ({}).", stepIndex); stepIndex++; problemChangeAdapter = problemFactChangeQueue.poll(); } // All PFCs are processed, fail fast if any of the new facts have null planning IDs. InnerScoreDirector<Solution_, ?> scoreDirector = solverScope.getScoreDirector(); assertCorrectSolutionState(); // Everything is fine, proceed. var score = scoreDirector.calculateScore(); basicPlumbingTermination.endProblemChangesProcessing(); bestSolutionRecaller.updateBestSolutionAndFireIfInitialized(solverScope); logger.info("Real-time problem fact changes done: step total ({}), new best score ({}).", stepIndex, score); return true; } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/DefaultSolverFactory.java
package ai.timefold.solver.core.impl.solver; import java.time.Clock; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Objects; import java.util.OptionalInt; 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.SolverConfigOverride; import ai.timefold.solver.core.api.solver.SolverFactory; import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig; import ai.timefold.solver.core.config.constructionheuristic.placer.QueuedEntityPlacerConfig; import ai.timefold.solver.core.config.localsearch.LocalSearchPhaseConfig; import ai.timefold.solver.core.config.score.director.ScoreDirectorFactoryConfig; import ai.timefold.solver.core.config.solver.EnvironmentMode; import ai.timefold.solver.core.config.solver.PreviewFeature; import ai.timefold.solver.core.config.solver.SolverConfig; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; import ai.timefold.solver.core.config.solver.random.RandomType; import ai.timefold.solver.core.config.solver.termination.TerminationConfig; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.AbstractFromConfigFactory; import ai.timefold.solver.core.impl.constructionheuristic.DefaultConstructionHeuristicPhaseFactory; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; import ai.timefold.solver.core.impl.phase.Phase; import ai.timefold.solver.core.impl.phase.PhaseFactory; import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy; import ai.timefold.solver.core.impl.score.director.ScoreDirectorFactory; import ai.timefold.solver.core.impl.score.director.ScoreDirectorFactoryFactory; import ai.timefold.solver.core.impl.solver.change.DefaultProblemChangeDirector; import ai.timefold.solver.core.impl.solver.random.DefaultRandomFactory; import ai.timefold.solver.core.impl.solver.random.RandomFactory; import ai.timefold.solver.core.impl.solver.recaller.BestSolutionRecaller; import ai.timefold.solver.core.impl.solver.recaller.BestSolutionRecallerFactory; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import ai.timefold.solver.core.impl.solver.termination.BasicPlumbingTermination; import ai.timefold.solver.core.impl.solver.termination.SolverTermination; import ai.timefold.solver.core.impl.solver.termination.TerminationFactory; import ai.timefold.solver.core.impl.solver.termination.UniversalTermination; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.micrometer.core.instrument.Tags; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @see SolverFactory */ public final class DefaultSolverFactory<Solution_> implements SolverFactory<Solution_> { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultSolverFactory.class); private static final long DEFAULT_RANDOM_SEED = 0L; private final Clock clock; private final SolverConfig solverConfig; private final SolutionDescriptor<Solution_> solutionDescriptor; private final ScoreDirectorFactory<Solution_, ?> scoreDirectorFactory; public DefaultSolverFactory(SolverConfig solverConfig) { this.clock = Objects.requireNonNullElse(solverConfig.getClock(), Clock.systemDefaultZone()); this.solverConfig = Objects.requireNonNull(solverConfig, "The solverConfig (" + solverConfig + ") cannot be null."); this.solutionDescriptor = buildSolutionDescriptor(); // Caching score director factory as it potentially does expensive things. this.scoreDirectorFactory = buildScoreDirectorFactory(); } public Clock getClock() { return clock; } public SolutionDescriptor<Solution_> getSolutionDescriptor() { return solutionDescriptor; } @SuppressWarnings("unchecked") public <Score_ extends Score<Score_>> ScoreDirectorFactory<Solution_, Score_> getScoreDirectorFactory() { return (ScoreDirectorFactory<Solution_, Score_>) scoreDirectorFactory; } @Override public @NonNull Solver<Solution_> buildSolver(@NonNull SolverConfigOverride<Solution_> configOverride) { Objects.requireNonNull(configOverride, "Invalid configOverride (null) given to SolverFactory."); var isDaemon = Objects.requireNonNullElse(solverConfig.getDaemon(), false); var solverScope = new SolverScope<Solution_>(clock); var monitoringConfig = solverConfig.determineMetricConfig(); solverScope.setMonitoringTags(Tags.empty()); var solverMetricList = Objects.requireNonNull(monitoringConfig.getSolverMetricList()); var metricsRequiringConstraintMatchSet = Collections.<SolverMetric> emptyList(); if (!solverMetricList.isEmpty()) { solverScope.setSolverMetricSet(EnumSet.copyOf(solverMetricList)); metricsRequiringConstraintMatchSet = solverScope.getSolverMetricSet().stream() .filter(SolverMetric::isMetricConstraintMatchBased) .filter(solverScope::isMetricEnabled) .toList(); } else { solverScope.setSolverMetricSet(EnumSet.noneOf(SolverMetric.class)); } var environmentMode = solverConfig.determineEnvironmentMode(); var isStepAssertOrMore = environmentMode.isStepAssertOrMore(); var constraintMatchEnabled = !metricsRequiringConstraintMatchSet.isEmpty() || isStepAssertOrMore; if (constraintMatchEnabled && !isStepAssertOrMore) { LOGGER.info( "Enabling constraint matching as required by the enabled metrics ({}). This will impact solver performance.", metricsRequiringConstraintMatchSet); } var castScoreDirector = scoreDirectorFactory.createScoreDirectorBuilder() .withLookUpEnabled(true) .withConstraintMatchPolicy( constraintMatchEnabled ? ConstraintMatchPolicy.ENABLED : ConstraintMatchPolicy.DISABLED) .build(); solverScope.setScoreDirector(castScoreDirector); solverScope.setProblemChangeDirector(new DefaultProblemChangeDirector<>(castScoreDirector)); var moveThreadCount = resolveMoveThreadCount(true); var bestSolutionRecaller = BestSolutionRecallerFactory.create().<Solution_> buildBestSolutionRecaller(environmentMode); var randomFactory = buildRandomFactory(environmentMode); var previewFeaturesEnabled = solverConfig.getEnablePreviewFeatureSet(); var configPolicy = new HeuristicConfigPolicy.Builder<Solution_>() .withPreviewFeatureSet(previewFeaturesEnabled) .withEnvironmentMode(environmentMode) .withMoveThreadCount(moveThreadCount) .withMoveThreadBufferSize(solverConfig.getMoveThreadBufferSize()) .withThreadFactoryClass(solverConfig.getThreadFactoryClass()) .withNearbyDistanceMeterClass(solverConfig.getNearbyDistanceMeterClass()) .withRandom(randomFactory.createRandom()) .withInitializingScoreTrend(scoreDirectorFactory.getInitializingScoreTrend()) .withSolutionDescriptor(solutionDescriptor) .withClassInstanceCache(ClassInstanceCache.create()) .build(); var basicPlumbingTermination = new BasicPlumbingTermination<Solution_>(isDaemon); var termination = buildTermination(basicPlumbingTermination, configPolicy, configOverride); var phaseList = buildPhaseList(configPolicy, bestSolutionRecaller, termination); return new DefaultSolver<>(environmentMode, randomFactory, bestSolutionRecaller, basicPlumbingTermination, (UniversalTermination<Solution_>) termination, phaseList, solverScope, moveThreadCount == null ? SolverConfig.MOVE_THREAD_COUNT_NONE : Integer.toString(moveThreadCount)); } public @Nullable Integer resolveMoveThreadCount(boolean enforceMaximum) { var maybeCount = new MoveThreadCountResolver().resolveMoveThreadCount(solverConfig.getMoveThreadCount(), enforceMaximum); if (maybeCount.isPresent()) { return maybeCount.getAsInt(); } else { return null; } } private SolverTermination<Solution_> buildTermination(BasicPlumbingTermination<Solution_> basicPlumbingTermination, HeuristicConfigPolicy<Solution_> configPolicy, SolverConfigOverride<Solution_> solverConfigOverride) { var terminationConfig = Objects.requireNonNullElseGet(solverConfigOverride.getTerminationConfig(), () -> Objects.requireNonNullElseGet(solverConfig.getTerminationConfig(), TerminationConfig::new)); return TerminationFactory.<Solution_> create(terminationConfig) .buildTermination(configPolicy, basicPlumbingTermination); } private SolutionDescriptor<Solution_> buildSolutionDescriptor() { if (solverConfig.getSolutionClass() == null) { throw new IllegalArgumentException( "The solver configuration must have a solutionClass (%s). If you're using the Quarkus extension or Spring Boot starter, it should have been filled in already." .formatted(solverConfig.getSolutionClass())); } if (ConfigUtils.isEmptyCollection(solverConfig.getEntityClassList())) { throw new IllegalArgumentException( "The solver configuration must have at least 1 entityClass (%s). If you're using the Quarkus extension or Spring Boot starter, it should have been filled in already." .formatted(solverConfig.getEntityClassList())); } return SolutionDescriptor.buildSolutionDescriptor(solverConfig.getEnablePreviewFeatureSet(), solverConfig.determineDomainAccessType(), (Class<Solution_>) solverConfig.getSolutionClass(), solverConfig.getGizmoMemberAccessorMap(), solverConfig.getGizmoSolutionClonerMap(), solverConfig.getEntityClassList()); } private <Score_ extends Score<Score_>> ScoreDirectorFactory<Solution_, Score_> buildScoreDirectorFactory() { var environmentMode = solverConfig.determineEnvironmentMode(); var scoreDirectorFactoryConfig_ = Objects.requireNonNullElseGet(solverConfig.getScoreDirectorFactoryConfig(), ScoreDirectorFactoryConfig::new); var scoreDirectorFactoryFactory = new ScoreDirectorFactoryFactory<Solution_, Score_>(scoreDirectorFactoryConfig_); return scoreDirectorFactoryFactory.buildScoreDirectorFactory(environmentMode, solutionDescriptor); } public RandomFactory buildRandomFactory(EnvironmentMode environmentMode_) { var randomFactoryClass = solverConfig.getRandomFactoryClass(); if (randomFactoryClass != null) { var randomType = solverConfig.getRandomType(); var randomSeed = solverConfig.getRandomSeed(); if (randomType != null || randomSeed != null) { throw new IllegalArgumentException( "The solverConfig with randomFactoryClass (%s) has a non-null randomType (%s) or a non-null randomSeed (%s)." .formatted(randomFactoryClass, randomType, randomSeed)); } return ConfigUtils.newInstance(solverConfig, "randomFactoryClass", randomFactoryClass); } else { var randomType_ = Objects.requireNonNullElse(solverConfig.getRandomType(), RandomType.JDK); var randomSeed_ = solverConfig.getRandomSeed(); if (solverConfig.getRandomSeed() == null && environmentMode_ != EnvironmentMode.NON_REPRODUCIBLE) { randomSeed_ = DEFAULT_RANDOM_SEED; } return new DefaultRandomFactory(randomType_, randomSeed_); } } public List<Phase<Solution_>> buildPhaseList(HeuristicConfigPolicy<Solution_> configPolicy, BestSolutionRecaller<Solution_> bestSolutionRecaller, SolverTermination<Solution_> termination) { var phaseConfigList = solverConfig.getPhaseConfigList(); if (ConfigUtils.isEmptyCollection(phaseConfigList)) { var genuineEntityDescriptorCollection = configPolicy.getSolutionDescriptor().getGenuineEntityDescriptors(); phaseConfigList = new ArrayList<>(genuineEntityDescriptorCollection.size() + 2); for (var entityDescriptor : genuineEntityDescriptorCollection) { if (entityDescriptor.hasBothGenuineListAndBasicVariables()) { // We add a separate step for each variable type phaseConfigList.add(buildConstructionHeuristicPhaseConfigForBasicVariable(configPolicy, entityDescriptor)); phaseConfigList.add(buildConstructionHeuristicPhaseConfigForListVariable(configPolicy, entityDescriptor)); } else if (entityDescriptor.hasAnyGenuineListVariables()) { // There is no need to revalidate the number of list variables, // as it has already been validated in SolutionDescriptor // TODO: Do multiple Construction Heuristics for each list variable descriptor? phaseConfigList.add(buildConstructionHeuristicPhaseConfigForListVariable(configPolicy, entityDescriptor)); } else { phaseConfigList.add(buildConstructionHeuristicPhaseConfigForBasicVariable(configPolicy, entityDescriptor)); } } phaseConfigList.add(new LocalSearchPhaseConfig()); } return PhaseFactory.buildPhases(phaseConfigList, configPolicy, bestSolutionRecaller, termination); } private ConstructionHeuristicPhaseConfig buildConstructionHeuristicPhaseConfigForBasicVariable(HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor) { var constructionHeuristicPhaseConfig = new ConstructionHeuristicPhaseConfig(); constructionHeuristicPhaseConfig .setEntityPlacerConfig(new QueuedEntityPlacerConfig().withEntitySelectorConfig(AbstractFromConfigFactory .getDefaultEntitySelectorConfigForEntity(configPolicy, entityDescriptor))); return constructionHeuristicPhaseConfig; } private ConstructionHeuristicPhaseConfig buildConstructionHeuristicPhaseConfigForListVariable(HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor) { var constructionHeuristicPhaseConfig = new ConstructionHeuristicPhaseConfig(); var listVariableDescriptor = entityDescriptor.getGenuineListVariableDescriptor(); constructionHeuristicPhaseConfig .setEntityPlacerConfig(DefaultConstructionHeuristicPhaseFactory .buildListVariableQueuedValuePlacerConfig(configPolicy, listVariableDescriptor)); return constructionHeuristicPhaseConfig; } public void ensurePreviewFeature(PreviewFeature previewFeature) { HeuristicConfigPolicy.ensurePreviewFeature(previewFeature, solverConfig.getEnablePreviewFeatureSet()); } // Required for testability as final classes cannot be mocked. static class MoveThreadCountResolver { protected OptionalInt resolveMoveThreadCount(String moveThreadCount) { return resolveMoveThreadCount(moveThreadCount, true); } protected OptionalInt resolveMoveThreadCount(String moveThreadCount, boolean enforceMaximum) { var availableProcessorCount = getAvailableProcessors(); int resolvedMoveThreadCount; if (moveThreadCount == null || moveThreadCount.equals(SolverConfig.MOVE_THREAD_COUNT_NONE)) { return OptionalInt.empty(); } else if (moveThreadCount.equals(SolverConfig.MOVE_THREAD_COUNT_AUTO)) { // Leave one for the Operating System and 1 for the solver thread, take the rest resolvedMoveThreadCount = (availableProcessorCount - 2); if (enforceMaximum && resolvedMoveThreadCount > 4) { // A moveThreadCount beyond 4 is currently typically slower // TODO remove limitation after fixing https://issues.redhat.com/browse/PLANNER-2449 resolvedMoveThreadCount = 4; } if (resolvedMoveThreadCount <= 1) { // Fall back to single threaded solving with no move threads. // To deliberately enforce 1 moveThread, set the moveThreadCount explicitly to 1. return OptionalInt.empty(); } } else { resolvedMoveThreadCount = ConfigUtils.resolvePoolSize("moveThreadCount", moveThreadCount, SolverConfig.MOVE_THREAD_COUNT_NONE, SolverConfig.MOVE_THREAD_COUNT_AUTO); } if (resolvedMoveThreadCount < 1) { throw new IllegalArgumentException( "The moveThreadCount (%s) resulted in a resolvedMoveThreadCount (%d) that is lower than 1." .formatted(moveThreadCount, resolvedMoveThreadCount)); } if (resolvedMoveThreadCount > availableProcessorCount) { LOGGER.warn( "The resolvedMoveThreadCount ({}) is higher than the availableProcessorCount ({}), which is counter-efficient.", resolvedMoveThreadCount, availableProcessorCount); // Still allow it, to reproduce issues of a high-end server machine on a low-end developer machine } return OptionalInt.of(resolvedMoveThreadCount); } protected int getAvailableProcessors() { return Runtime.getRuntime().availableProcessors(); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/DefaultSolverJob.java
package ai.timefold.solver.core.impl.solver; import java.time.Duration; import java.util.List; 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.atomic.AtomicReference; 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.SolverJobBuilder.FirstInitializedSolutionConsumer; 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.AbstractPhase; import ai.timefold.solver.core.impl.phase.PossiblyInitializingPhase; import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleListenerAdapter; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; import ai.timefold.solver.core.impl.score.director.ValueRangeManager; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import ai.timefold.solver.core.impl.solver.termination.SolverTermination; import org.jspecify.annotations.NonNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @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 FirstInitializedSolutionConsumer<? super Solution_> firstInitializedSolutionConsumer; private final Consumer<? super Solution_> solverJobStartedConsumer; 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<>(); private final AtomicReference<ProblemSizeStatistics> temporaryProblemSizeStatistics = new AtomicReference<>(); 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, FirstInitializedSolutionConsumer<? super Solution_> firstInitializedSolutionConsumer, Consumer<? super Solution_> solverJobStartedConsumer, 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 %s.".formatted(DefaultSolver.class.getSimpleName())); } this.solver = (DefaultSolver<Solution_>) solver; this.problemFinder = problemFinder; this.bestSolutionConsumer = bestSolutionConsumer; this.finalBestSolutionConsumer = finalBestSolutionConsumer; this.firstInitializedSolutionConsumer = firstInitializedSolutionConsumer; this.solverJobStartedConsumer = solverJobStartedConsumer; 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 @NonNull ProblemId_ getProblemId() { return problemId; } @Override public @NonNull 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, firstInitializedSolutionConsumer, solverJobStartedConsumer, 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()); // add a phase lifecycle listener that consumes the first initialized solution solver.addPhaseLifecycleListener(new FirstInitializedSolutionPhaseLifecycleListener(consumerSupport)); // add a phase lifecycle listener once when the solver starts its execution solver.addPhaseLifecycleListener(new StartSolverJobPhaseLifecycleListener(consumerSupport)); 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 (%s).".formatted(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(); close(); } @Override public @NonNull CompletableFuture<Void> addProblemChanges(@NonNull List<ProblemChange<Solution_>> problemChangeList) { Objects.requireNonNull(problemChangeList, () -> "A problem change list for problem (%s) must not be null." .formatted(problemId)); if (problemChangeList.isEmpty()) { throw new IllegalArgumentException("The problem change list for problem (%s) must not be empty." .formatted(problemId)); } else if (solverStatus == SolverStatus.NOT_SOLVING) { throw new IllegalStateException("Cannot add the problem changes (%s) because the solver job (%s) is not solving." .formatted(problemChangeList, solverStatus)); } return bestSolutionHolder.addProblemChange(solver, problemChangeList); } @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 (%s).".formatted(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 @NonNull 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 @NonNull Duration getSolvingDuration() { return Duration.ofMillis(solver.getTimeMillisSpent()); } @Override public long getScoreCalculationCount() { return solver.getScoreCalculationCount(); } @Override public long getMoveEvaluationCount() { return solver.getMoveEvaluationCount(); } @Override public long getScoreCalculationSpeed() { return solver.getScoreCalculationSpeed(); } @Override public long getMoveEvaluationSpeed() { return solver.getMoveEvaluationSpeed(); } @Override public @NonNull ProblemSizeStatistics getProblemSizeStatistics() { var solverScope = solver.getSolverScope(); var problemSizeStatistics = solverScope.getProblemSizeStatistics(); if (problemSizeStatistics != null) { temporaryProblemSizeStatistics.set(null); return problemSizeStatistics; } // Solving has not started yet; we do not have a working solution. // Therefore we cannot rely on ScoreDirector's ValueRangeManager // and we need to use a new cold instance. // This will be inefficient on account of recomputing all the value ranges, // but it only exists to solve a corner case of accessing the problem size statistics // before the solving has started. // Once the solving has started, the problem size statistics will be computed // using the ScoreDirector's hot ValueRangeManager. return temporaryProblemSizeStatistics.updateAndGet(oldStatistics -> { if (oldStatistics != null) { // If the problem size statistics were already computed, return them. // This can happen if the problem size statistics were computed before the solving started. return oldStatistics; } var solutionDescriptor = solverScope.getSolutionDescriptor(); var valueManager = ValueRangeManager.of(solutionDescriptor, problemFinder.apply(problemId)); return valueManager.getProblemSizeStatistics(); }); } public SolverTermination<Solution_> getSolverTermination() { return solver.globalTermination; } 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(); } } } /** * A listener that consumes the solution from a phase only if the phase first initializes the solution. */ private final class FirstInitializedSolutionPhaseLifecycleListener extends PhaseLifecycleListenerAdapter<Solution_> { private final ConsumerSupport<Solution_, ProblemId_> consumerSupport; public FirstInitializedSolutionPhaseLifecycleListener(ConsumerSupport<Solution_, ProblemId_> consumerSupport) { this.consumerSupport = consumerSupport; } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { var eventPhase = solver.getPhaseList().stream() .filter(phase -> ((AbstractPhase<Solution_>) phase).getPhaseIndex() == phaseScope.getPhaseIndex()) .findFirst() .orElseThrow(() -> new IllegalStateException( "Impossible state: Solving failed for problemId (%s) because the phase id %d was not found." .formatted(problemId, phaseScope.getPhaseIndex()))); if (eventPhase instanceof PossiblyInitializingPhase<Solution_> possiblyInitializingPhase && possiblyInitializingPhase.isLastInitializingPhase()) { // The Solver thread calls the method, // but the consumption is done asynchronously by the Consumer thread. // Only happens if the phase initializes the solution. consumerSupport.consumeFirstInitializedSolution(phaseScope.getWorkingSolution(), possiblyInitializingPhase.getTerminationStatus().early()); } } } /** * A listener that is triggered once when the solver starts the solving process. */ private final class StartSolverJobPhaseLifecycleListener extends PhaseLifecycleListenerAdapter<Solution_> { private final ConsumerSupport<Solution_, ProblemId_> consumerSupport; public StartSolverJobPhaseLifecycleListener(ConsumerSupport<Solution_, ProblemId_> consumerSupport) { this.consumerSupport = consumerSupport; } @Override public void solvingStarted(SolverScope<Solution_> solverScope) { consumerSupport.consumeStartSolverJob(solverScope.getWorkingSolution()); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/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; import org.jspecify.annotations.NonNull; /** * @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 FirstInitializedSolutionConsumer<? super Solution_> initializedSolutionConsumer; private Consumer<? super Solution_> solverJobStartedConsumer; 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 @NonNull SolverJobBuilder<Solution_, ProblemId_> withProblemId(@NonNull ProblemId_ problemId) { this.problemId = Objects.requireNonNull(problemId, "Invalid problemId (null) given to SolverJobBuilder."); return this; } @Override public @NonNull SolverJobBuilder<Solution_, ProblemId_> withProblemFinder(@NonNull Function<? super ProblemId_, ? extends Solution_> problemFinder) { this.problemFinder = Objects.requireNonNull(problemFinder, "Invalid problemFinder (null) given to SolverJobBuilder."); return this; } @Override public @NonNull SolverJobBuilder<Solution_, ProblemId_> withBestSolutionConsumer(@NonNull Consumer<? super Solution_> bestSolutionConsumer) { this.bestSolutionConsumer = Objects.requireNonNull(bestSolutionConsumer, "Invalid bestSolutionConsumer (null) given to SolverJobBuilder."); return this; } @Override public @NonNull SolverJobBuilder<Solution_, ProblemId_> withFinalBestSolutionConsumer(@NonNull Consumer<? super Solution_> finalBestSolutionConsumer) { this.finalBestSolutionConsumer = Objects.requireNonNull(finalBestSolutionConsumer, "Invalid finalBestSolutionConsumer (null) given to SolverJobBuilder."); return this; } @Override public @NonNull SolverJobBuilder<Solution_, ProblemId_> withFirstInitializedSolutionConsumer( @NonNull FirstInitializedSolutionConsumer<? super Solution_> firstInitializedSolutionConsumer) { this.initializedSolutionConsumer = Objects.requireNonNull(firstInitializedSolutionConsumer, "Invalid initializedSolutionConsumer (null) given to SolverJobBuilder."); return this; } @Override public SolverJobBuilder<Solution_, ProblemId_> withSolverJobStartedConsumer(Consumer<? super Solution_> solverJobStartedConsumer) { this.solverJobStartedConsumer = Objects.requireNonNull(solverJobStartedConsumer, "Invalid startSolverJobHandler (null) given to SolverJobBuilder."); return this; } @Override public @NonNull SolverJobBuilder<Solution_, ProblemId_> withExceptionHandler(@NonNull BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler) { this.exceptionHandler = Objects.requireNonNull(exceptionHandler, "Invalid exceptionHandler (null) given to SolverJobBuilder."); return this; } @Override public @NonNull SolverJobBuilder<Solution_, ProblemId_> withConfigOverride(@NonNull SolverConfigOverride<Solution_> solverConfigOverride) { this.solverConfigOverride = Objects.requireNonNull(solverConfigOverride, "Invalid solverConfigOverride (null) given to SolverJobBuilder."); return this; } @Override public @NonNull 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, initializedSolutionConsumer, solverJobStartedConsumer, exceptionHandler, solverConfigOverride); } else { return solverManager.solveAndListen(problemId, problemFinder, bestSolutionConsumer, finalBestSolutionConsumer, initializedSolutionConsumer, solverJobStartedConsumer, exceptionHandler, solverConfigOverride); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/DefaultSolverManager.java
package ai.timefold.solver.core.impl.solver; import java.util.List; 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.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.SolverFactory; import ai.timefold.solver.core.api.solver.SolverJob; import ai.timefold.solver.core.api.solver.SolverJobBuilder; import ai.timefold.solver.core.api.solver.SolverJobBuilder.FirstInitializedSolutionConsumer; 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 ai.timefold.solver.core.config.util.ConfigUtils; import org.jspecify.annotations.NonNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @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) { this.defaultExceptionHandler = (problemId, throwable) -> LOGGER.error("Solving failed for problemId ({}).", problemId, throwable); this.solverFactory = solverFactory; validateSolverFactory(); var parallelSolverCount = solverManagerConfig.resolveParallelSolverCount(); var threadFactoryClass = solverManagerConfig.getThreadFactoryClass(); var threadFactory = threadFactoryClass == null ? Executors.defaultThreadFactory() : ConfigUtils.newInstance(solverManagerConfig, "threadFactoryClass", threadFactoryClass); solverThreadPool = Executors.newFixedThreadPool(parallelSolverCount, threadFactory); 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 @NonNull SolverJobBuilder<Solution_, ProblemId_> solveBuilder() { return new DefaultSolverJobBuilder<>(this); } SolverJob<Solution_, ProblemId_> solveAndListen(ProblemId_ problemId, Function<? super ProblemId_, ? extends Solution_> problemFinder, Consumer<? super Solution_> bestSolutionConsumer, Consumer<? super Solution_> finalBestSolutionConsumer, FirstInitializedSolutionConsumer<? super Solution_> initializedSolutionConsumer, Consumer<? super Solution_> solverJobStartedConsumer, 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, initializedSolutionConsumer, solverJobStartedConsumer, exceptionHandler, solverConfigOverride); } SolverJob<Solution_, ProblemId_> solve(ProblemId_ problemId, Function<? super ProblemId_, ? extends Solution_> problemFinder, Consumer<? super Solution_> bestSolutionConsumer, Consumer<? super Solution_> finalBestSolutionConsumer, FirstInitializedSolutionConsumer<? super Solution_> initializedSolutionConsumer, Consumer<? super Solution_> solverJobStartedConsumer, BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler, SolverConfigOverride<Solution_> configOverride) { var solver = solverFactory.buildSolver(configOverride); ((DefaultSolver<Solution_>) solver).setMonitorTagMap(Map.of("problem.id", problemId.toString())); BiConsumer<? super ProblemId_, ? super Throwable> finalExceptionHandler = (exceptionHandler != null) ? exceptionHandler : defaultExceptionHandler; var 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, initializedSolutionConsumer, solverJobStartedConsumer, finalExceptionHandler); } }); var future = solverThreadPool.submit(solverJob); solverJob.setFinalBestSolutionFuture(future); return solverJob; } @Override public @NonNull SolverStatus getSolverStatus(@NonNull ProblemId_ problemId) { var solverJob = getSolverJob(problemId); if (solverJob == null) { return SolverStatus.NOT_SOLVING; } return solverJob.getSolverStatus(); } @Override public @NonNull CompletableFuture<Void> addProblemChanges(@NonNull ProblemId_ problemId, @NonNull List<ProblemChange<Solution_>> problemChangeList) { var 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 changes (%s) because there is no solver solving the problemId (%s)." .formatted(problemChangeList, problemId)); } return solverJob.addProblemChanges(problemChangeList); } @Override public void terminateEarly(@NonNull ProblemId_ problemId) { var 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/1.26.1/ai/timefold/solver/core/impl
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/RecommendationConstructor.java
package ai.timefold.solver.core.impl.solver; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.analysis.ScoreAnalysis; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked interface RecommendationConstructor<Score_ extends Score<Score_>, Recommendation_, Out_> { Recommendation_ apply(long moveIndex, @Nullable Out_ result, ScoreAnalysis<Score_> scoreDifference); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/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.solver.change.ProblemChangeDirector; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; 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(@NonNull Entity entity, @NonNull 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(@NonNull Entity entity, @NonNull Consumer<Entity> entityConsumer) { Objects.requireNonNull(entity, () -> "Entity (" + entity + ") cannot be null."); Objects.requireNonNull(entityConsumer, () -> "Entity consumer (" + entityConsumer + ") cannot be null."); var workingEntity = lookUpWorkingObjectOrFail(entity); scoreDirector.beforeEntityRemoved(workingEntity); entityConsumer.accept(workingEntity); scoreDirector.afterEntityRemoved(workingEntity); } @Override public <Entity> void changeVariable(@NonNull Entity entity, @NonNull String variableName, @NonNull 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."); var workingEntity = lookUpWorkingObjectOrFail(entity); scoreDirector.beforeVariableChanged(workingEntity, variableName); entityConsumer.accept(workingEntity); scoreDirector.afterVariableChanged(workingEntity, variableName); } @Override public <ProblemFact> void addProblemFact(@NonNull ProblemFact problemFact, @NonNull 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(@NonNull ProblemFact problemFact, @NonNull Consumer<ProblemFact> problemFactConsumer) { Objects.requireNonNull(problemFact, () -> "Problem fact (" + problemFact + ") cannot be null."); Objects.requireNonNull(problemFactConsumer, () -> "Problem fact consumer (" + problemFactConsumer + ") cannot be null."); var workingProblemFact = lookUpWorkingObjectOrFail(problemFact); scoreDirector.beforeProblemFactRemoved(workingProblemFact); problemFactConsumer.accept(workingProblemFact); scoreDirector.afterProblemFactRemoved(workingProblemFact); } @Override public <EntityOrProblemFact> void changeProblemProperty(@NonNull EntityOrProblemFact problemFactOrEntity, @NonNull 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."); var workingEntityOrProblemFact = lookUpWorkingObjectOrFail(problemFactOrEntity); scoreDirector.beforeProblemPropertyChanged(workingEntityOrProblemFact); problemFactOrEntityConsumer.accept(workingEntityOrProblemFact); scoreDirector.afterProblemPropertyChanged(workingEntityOrProblemFact); } @Override public <EntityOrProblemFact> @Nullable EntityOrProblemFact lookUpWorkingObjectOrFail(@Nullable 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(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/change/ProblemChangeAdapter.java
package ai.timefold.solver.core.impl.solver.change; import ai.timefold.solver.core.api.solver.ProblemFactChange; import ai.timefold.solver.core.api.solver.change.ProblemChange; import ai.timefold.solver.core.impl.solver.scope.SolverScope; /** * Provides a layer of abstraction over {@link ai.timefold.solver.core.api.solver.change.ProblemChange} and the * deprecated {@link ai.timefold.solver.core.api.solver.ProblemFactChange} to preserve backward compatibility. */ public interface ProblemChangeAdapter<Solution_> { void doProblemChange(SolverScope<Solution_> solverScope); static <Solution_> ProblemChangeAdapter<Solution_> create(ProblemFactChange<Solution_> problemFactChange) { return (solverScope) -> problemFactChange.doChange(solverScope.getScoreDirector()); } static <Solution_> ProblemChangeAdapter<Solution_> create(ProblemChange<Solution_> problemChange) { return (solverScope) -> { problemChange.doChange(solverScope.getWorkingSolution(), solverScope.getProblemChangeDirector()); solverScope.getScoreDirector().triggerVariableListeners(); }; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/event/AbstractEventSupport.java
package ai.timefold.solver.core.impl.solver.event; import java.util.ArrayList; import java.util.Collection; import java.util.EventListener; import java.util.IdentityHashMap; import java.util.List; import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector; public abstract class AbstractEventSupport<E extends EventListener> { /** * {@link EntitySelector} instances may end up here. * Each instance added via {@link #addEventListener(EventListener)} must appear here, * regardless of whether it is equal to any other instance already present. * Likewise {@link #removeEventListener(EventListener)} must remove elements by identity, not equality. * <p> * This list-based implementation could be called an "identity set", similar to {@link IdentityHashMap}. * We can not use {@link IdentityHashMap}, because we require iteration in insertion order. */ private final List<E> eventListenerList = new ArrayList<>(); public void addEventListener(E eventListener) { for (E addedEventListener : eventListenerList) { if (addedEventListener == eventListener) { throw new IllegalArgumentException( "Event listener (" + eventListener + ") already found in list (" + eventListenerList + ")."); } } eventListenerList.add(eventListener); } public void removeEventListener(E eventListener) { if (!eventListenerList.removeIf(e -> e == eventListener)) { throw new IllegalArgumentException( "Event listener (" + eventListener + ") not found in list (" + eventListenerList + ")."); } } protected Collection<E> getEventListeners() { return eventListenerList; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/event/DefaultBestSolutionChangedEvent.java
package ai.timefold.solver.core.impl.solver.event; import ai.timefold.solver.core.api.solver.Solver; import ai.timefold.solver.core.api.solver.event.BestSolutionChangedEvent; import ai.timefold.solver.core.impl.score.director.InnerScore; import org.jspecify.annotations.NonNull; public final class DefaultBestSolutionChangedEvent<Solution_> extends BestSolutionChangedEvent<Solution_> { private final int unassignedCount; public DefaultBestSolutionChangedEvent(@NonNull Solver<Solution_> solver, long timeMillisSpent, @NonNull Solution_ newBestSolution, @NonNull InnerScore newBestScore) { super(solver, timeMillisSpent, newBestSolution, newBestScore.raw(), newBestScore.isFullyAssigned()); this.unassignedCount = newBestScore.unassignedCount(); } public int getUnassignedCount() { return unassignedCount; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/event/SolverEventSupport.java
package ai.timefold.solver.core.impl.solver.event; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.solver.Solver; 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) { var it = getEventListeners().iterator(); var timeMillisSpent = solverScope.getBestSolutionTimeMillisSpent(); var bestScore = solverScope.getBestScore(); if (it.hasNext()) { var event = new DefaultBestSolutionChangedEvent<>(solver, timeMillisSpent, newBestSolution, bestScore); do { it.next().bestSolutionChanged(event); } while (it.hasNext()); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/event/SolverLifecycleListener.java
package ai.timefold.solver.core.impl.solver.event; import java.util.EventListener; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.impl.solver.scope.SolverScope; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @see SolverLifecycleListenerAdapter */ public interface SolverLifecycleListener<Solution_> extends EventListener { void solvingStarted(SolverScope<Solution_> solverScope); void solvingEnded(SolverScope<Solution_> solverScope); /** * Invoked in case of an exception in the {@link ai.timefold.solver.core.api.solver.Solver} run. In that case, * the {@link #solvingEnded(SolverScope)} is never called. * For internal purposes only. */ default void solvingError(SolverScope<Solution_> solverScope, Exception exception) { // no-op } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/event/SolverLifecycleListenerAdapter.java
package ai.timefold.solver.core.impl.solver.event; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.impl.solver.scope.SolverScope; /** * An adapter for {@link SolverLifecycleListener}. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public abstract class SolverLifecycleListenerAdapter<Solution_> implements SolverLifecycleListener<Solution_> { @Override public void solvingStarted(SolverScope<Solution_> solverScope) { // Hook method } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { // Hook method } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/exception/CloningCorruptionException.java
package ai.timefold.solver.core.impl.solver.exception; public final class CloningCorruptionException extends IllegalStateException { public CloningCorruptionException(String message) { super(message); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/exception/ScoreCorruptionException.java
package ai.timefold.solver.core.impl.solver.exception; public class ScoreCorruptionException extends IllegalStateException { public ScoreCorruptionException(String message) { super(message); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/exception/UndoScoreCorruptionException.java
package ai.timefold.solver.core.impl.solver.exception; import ai.timefold.solver.core.config.solver.EnvironmentMode; /** * An exception that is thrown in {@link 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 final class UndoScoreCorruptionException extends ScoreCorruptionException { 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/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/exception/VariableCorruptionException.java
package ai.timefold.solver.core.impl.solver.exception; public final class VariableCorruptionException extends IllegalStateException { public VariableCorruptionException(String message) { super(message); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/exception/package-info.java
/** * Contains various exceptions thrown by the solver. * Their API is currently unstable, including their FQN. * Catch these exceptions at your own risk. */ package ai.timefold.solver.core.impl.solver.exception;
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/monitoring/ScoreLevels.java
package ai.timefold.solver.core.impl.solver.monitoring; import java.util.Arrays; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; public final class ScoreLevels { final AtomicReference<Number>[] levelValues; final AtomicInteger unassignedCount; @SuppressWarnings("unchecked") ScoreLevels(int unassignedCount, Number[] levelValues) { // We store the values inside a constant reference, // so that the metric can always load the latest value. // If we stored the value directly and just overwrote it, // the metric would always hold a reference to the old value, // effectively ignoring the update. this.unassignedCount = new AtomicInteger(unassignedCount); this.levelValues = Arrays.stream(levelValues) .map(AtomicReference::new) .toArray(AtomicReference[]::new); } void setLevelValue(int level, Number value) { levelValues[level].set(value); } void setUnassignedCount(int unassignedCount) { this.unassignedCount.set(unassignedCount); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/monitoring/SolverMetricUtil.java
package ai.timefold.solver.core.impl.solver.monitoring; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import ai.timefold.solver.core.impl.score.director.InnerScore; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.Tags; @NullMarked public final class SolverMetricUtil { // Necessary for benchmarker, but otherwise undocumented and not considered public. private static final String UNASSIGNED_COUNT_LABEL = "unassigned.count"; public static <Score_ extends Score<Score_>> void registerScore(SolverMetric metric, Tags tags, ScoreDefinition<Score_> scoreDefinition, Map<Tags, ScoreLevels> tagToScoreLevels, InnerScore<Score_> innerScore) { var levelValues = innerScore.raw().toLevelNumbers(); if (tagToScoreLevels.containsKey(tags)) { // Set new score levels for the previously registered gauges to read. var scoreLevels = tagToScoreLevels.get(tags); scoreLevels.setUnassignedCount(innerScore.unassignedCount()); for (var i = 0; i < levelValues.length; i++) { scoreLevels.setLevelValue(i, levelValues[i]); } } else { var levelLabels = getLevelLabels(scoreDefinition); var scoreLevels = new Number[levelLabels.length]; System.arraycopy(levelValues, 0, scoreLevels, 0, levelValues.length); var result = new ScoreLevels(innerScore.unassignedCount(), scoreLevels); tagToScoreLevels.put(tags, result); // Register the gauges to read the score levels. Metrics.gauge(getGaugeName(metric, UNASSIGNED_COUNT_LABEL), tags, result.unassignedCount, AtomicInteger::doubleValue); for (var i = 0; i < levelValues.length; i++) { Metrics.gauge(getGaugeName(metric, levelLabels[i]), tags, result.levelValues[i], ref -> ref.get().doubleValue()); } } } private static String[] getLevelLabels(ScoreDefinition<?> scoreDefinition) { var labelNames = scoreDefinition.getLevelLabels(); for (var i = 0; i < labelNames.length; i++) { labelNames[i] = labelNames[i].replace(' ', '.'); } return labelNames; } public static String getGaugeName(SolverMetric metric, String label) { return metric.getMeterId() + "." + label; } public static @Nullable Double getGaugeValue(MeterRegistry registry, SolverMetric metric, Tags runId) { return getGaugeValue(registry, metric.getMeterId(), runId); } public static @Nullable Double getGaugeValue(MeterRegistry registry, String meterId, Tags runId) { var gauge = registry.find(meterId).tags(runId).gauge(); if (gauge != null && Double.isFinite(gauge.value())) { return gauge.value(); } else { return null; } } public static <Score_ extends Score<Score_>> @Nullable InnerScore<Score_> extractScore(SolverMetric metric, ScoreDefinition<Score_> scoreDefinition, Function<String, @Nullable Number> scoreLevelFunction) { var levelLabels = getLevelLabels(scoreDefinition); var levelNumbers = new Number[levelLabels.length]; for (var i = 0; i < levelLabels.length; i++) { var levelNumber = scoreLevelFunction.apply(getGaugeName(metric, levelLabels[i])); if (levelNumber == null) { return null; } levelNumbers[i] = levelNumber; } var score = scoreDefinition.fromLevelNumbers(levelNumbers); var unassignedCount = scoreLevelFunction.apply(getGaugeName(metric, UNASSIGNED_COUNT_LABEL)); if (unassignedCount == null) { return null; } return InnerScore.withUnassignedCount(score, unassignedCount.intValue()); } private SolverMetricUtil() { // No external instances. } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/monitoring
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/monitoring/statistic/BestScoreStatistic.java
package ai.timefold.solver.core.impl.solver.monitoring.statistic; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; 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.director.InnerScore; import ai.timefold.solver.core.impl.solver.DefaultSolver; import ai.timefold.solver.core.impl.solver.event.DefaultBestSolutionChangedEvent; import ai.timefold.solver.core.impl.solver.monitoring.ScoreLevels; import ai.timefold.solver.core.impl.solver.monitoring.SolverMetricUtil; import io.micrometer.core.instrument.Tags; public class BestScoreStatistic<Solution_> implements SolverStatistic<Solution_> { private final Map<Tags, ScoreLevels> 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); } tagsToBestScoreMap.remove(extractTags(solver)); } private static Tags extractTags(Solver<?> solver) { var defaultSolver = (DefaultSolver<?>) solver; return defaultSolver.getSolverScope().getMonitoringTags(); } @Override public void register(Solver<Solution_> solver) { var defaultSolver = (DefaultSolver<Solution_>) solver; var scoreDefinition = defaultSolver.getSolverScope().getScoreDefinition(); var tags = extractTags(solver); SolverEventListener<Solution_> listener = event -> { var castEvent = (DefaultBestSolutionChangedEvent<Solution_>) event; SolverMetricUtil.registerScore(SolverMetric.BEST_SCORE, tags, scoreDefinition, tagsToBestScoreMap, InnerScore.withUnassignedCount(event.getNewBestScore(), castEvent.getUnassignedCount())); }; solverToEventListenerMap.put(defaultSolver, listener); defaultSolver.addEventListener(listener); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/monitoring
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/monitoring/statistic/BestSolutionMutationCountStatistic.java
package ai.timefold.solver.core.impl.solver.monitoring.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.ScoreDirectorFactory; import ai.timefold.solver.core.impl.solver.DefaultSolver; import org.jspecify.annotations.NonNull; 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; ScoreDirectorFactory<Solution_, ?> scoreDirectorFactory = defaultSolver.getScoreDirectorFactory(); SolutionDescriptor<Solution_> solutionDescriptor = scoreDirectorFactory.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(@NonNull 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/1.26.1/ai/timefold/solver/core/impl/solver/monitoring
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/monitoring/statistic/MemoryUseStatistic.java
package ai.timefold.solver.core.impl.solver.monitoring.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/1.26.1/ai/timefold/solver/core/impl/solver/monitoring
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/monitoring/statistic/MoveCountPerTypeStatistic.java
package ai.timefold.solver.core.impl.solver.monitoring.statistic; import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import ai.timefold.solver.core.api.solver.Solver; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleListenerAdapter; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; 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; import io.micrometer.core.instrument.Tags; public class MoveCountPerTypeStatistic<Solution_> implements SolverStatistic<Solution_> { private final Map<Solver<Solution_>, PhaseLifecycleListenerAdapter<Solution_>> solverToPhaseLifecycleListenerMap = new WeakHashMap<>(); @Override public void unregister(Solver<Solution_> solver) { var listener = solverToPhaseLifecycleListenerMap.remove(solver); if (listener != null) { ((DefaultSolver<Solution_>) solver).removePhaseLifecycleListener(listener); ((MoveCountPerTypeStatisticListener<Solution_>) listener).unregister(solver); } } @Override public void register(Solver<Solution_> solver) { var defaultSolver = (DefaultSolver<Solution_>) solver; var listener = new MoveCountPerTypeStatistic.MoveCountPerTypeStatisticListener<Solution_>(); solverToPhaseLifecycleListenerMap.put(solver, listener); defaultSolver.addPhaseLifecycleListener(listener); } private static class MoveCountPerTypeStatisticListener<Solution_> extends PhaseLifecycleListenerAdapter<Solution_> { private final Map<Tags, Map<String, AtomicLong>> tagsToMoveCountMap = new ConcurrentHashMap<>(); @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { // The metric must be collected when the phase ends instead of when the solver ends // because there is no guarantee this listener will run the phase event before the StatisticRegistry listener var moveCountPerType = phaseScope.getSolverScope().getMoveEvaluationCountPerType(); var tags = phaseScope.getSolverScope().getMonitoringTags(); moveCountPerType.forEach((type, count) -> { var key = SolverMetric.MOVE_COUNT_PER_TYPE.getMeterId() + "." + type; var counter = Metrics.gauge(key, tags, new AtomicLong(0L)); if (counter != null) { counter.set(count); } registerMoveCountPerType(tags, key, counter); }); } private void registerMoveCountPerType(Tags tag, String key, AtomicLong count) { tagsToMoveCountMap.compute(tag, (tags, countMap) -> { if (countMap == null) { countMap = new HashMap<>(); } countMap.put(key, count); return countMap; }); } void unregister(Solver<Solution_> solver) { SolverScope<Solution_> solverScope = ((DefaultSolver<Solution_>) solver).getSolverScope(); tagsToMoveCountMap.values().stream().flatMap(v -> v.keySet().stream()) .forEach(meter -> Metrics.globalRegistry.remove(new Meter.Id(meter, solverScope.getMonitoringTags(), null, null, Meter.Type.GAUGE))); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/monitoring
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/monitoring/statistic/PickedMoveBestScoreDiffStatistic.java
package ai.timefold.solver.core.impl.solver.monitoring.statistic; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; 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.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.InnerScore; import ai.timefold.solver.core.impl.solver.DefaultSolver; import ai.timefold.solver.core.impl.solver.monitoring.ScoreLevels; import ai.timefold.solver.core.impl.solver.monitoring.SolverMetricUtil; 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) { var listener = solverToPhaseLifecycleListenerMap.remove(solver); if (listener != null) { ((DefaultSolver<Solution_>) solver).removePhaseLifecycleListener(listener); } } @Override public void register(Solver<Solution_> solver) { var defaultSolver = (DefaultSolver<Solution_>) solver; var scoreDirectorFactory = defaultSolver.getScoreDirectorFactory(); var solutionDescriptor = scoreDirectorFactory.getSolutionDescriptor(); var 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; // Guaranteed local search; no need for InnerScore. private final ScoreDefinition<Score_> scoreDefinition; private final Map<Tags, ScoreLevels> tagsToMoveScoreMap = new ConcurrentHashMap<>(); public PickedMoveBestScoreDiffStatisticListener(ScoreDefinition<Score_> scoreDefinition) { this.scoreDefinition = scoreDefinition; } @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { if (phaseScope instanceof LocalSearchPhaseScope) { oldBestScore = phaseScope.<Score_> getBestScore().raw(); } } @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); } } private void localSearchStepEnded(LocalSearchStepScope<Solution_> stepScope) { if (stepScope.getBestScoreImproved()) { var moveType = stepScope.getStep().describe(); var newBestScore = stepScope.<Score_> getScore().raw(); var bestScoreDiff = newBestScore.subtract(oldBestScore); oldBestScore = newBestScore; var tags = stepScope.getPhaseScope().getSolverScope().getMonitoringTags() .and("move.type", moveType); SolverMetricUtil.registerScore(SolverMetric.PICKED_MOVE_TYPE_BEST_SCORE_DIFF, tags, scoreDefinition, tagsToMoveScoreMap, InnerScore.fullyAssigned(bestScoreDiff)); } } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/monitoring
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/monitoring/statistic/PickedMoveStepScoreDiffStatistic.java
package ai.timefold.solver.core.impl.solver.monitoring.statistic; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; 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.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.InnerScore; import ai.timefold.solver.core.impl.solver.DefaultSolver; import ai.timefold.solver.core.impl.solver.monitoring.ScoreLevels; import ai.timefold.solver.core.impl.solver.monitoring.SolverMetricUtil; 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) { var listener = solverToPhaseLifecycleListenerMap.remove(solver); if (listener != null) { ((DefaultSolver<Solution_>) solver).removePhaseLifecycleListener(listener); } } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void register(Solver<Solution_> solver) { var defaultSolver = (DefaultSolver<Solution_>) solver; var scoreDirectorFactory = defaultSolver.getScoreDirectorFactory(); var solutionDescriptor = scoreDirectorFactory.getSolutionDescriptor(); var listener = new PickedMoveStepScoreDiffStatisticListener(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; // Guaranteed local search; no need for InnerScore. private final ScoreDefinition<Score_> scoreDefinition; private final Map<Tags, ScoreLevels> tagsToMoveScoreMap = new ConcurrentHashMap<>(); public PickedMoveStepScoreDiffStatisticListener(ScoreDefinition<Score_> scoreDefinition) { this.scoreDefinition = scoreDefinition; } @SuppressWarnings("unchecked") @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { if (phaseScope instanceof LocalSearchPhaseScope) { oldStepScore = (Score_) phaseScope.getStartingScore().raw(); } } @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); } } private void localSearchStepEnded(LocalSearchStepScope<Solution_> stepScope) { var moveType = stepScope.getStep().describe(); var newStepScore = stepScope.<Score_> getScore().raw(); var stepScoreDiff = newStepScore.subtract(oldStepScore); oldStepScore = newStepScore; var tags = stepScope.getPhaseScope().getSolverScope().getMonitoringTags() .and("move.type", moveType); SolverMetricUtil.registerScore(SolverMetric.PICKED_MOVE_TYPE_STEP_SCORE_DIFF, tags, scoreDefinition, tagsToMoveScoreMap, InnerScore.fullyAssigned(stepScoreDiff)); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/monitoring
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/monitoring/statistic/SolverScopeStatistic.java
package ai.timefold.solver.core.impl.solver.monitoring.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/1.26.1/ai/timefold/solver/core/impl/solver/monitoring
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/monitoring/statistic/SolverStatistic.java
package ai.timefold.solver.core.impl.solver.monitoring.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/1.26.1/ai/timefold/solver/core/impl/solver/monitoring
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/monitoring/statistic/StatelessSolverStatistic.java
package ai.timefold.solver.core.impl.solver.monitoring.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/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/random/DefaultRandomFactory.java
package ai.timefold.solver.core.impl.solver.random; import java.util.Random; import ai.timefold.solver.core.config.solver.random.RandomType; import org.apache.commons.math3.random.MersenneTwister; import org.apache.commons.math3.random.RandomAdaptor; import org.apache.commons.math3.random.Well1024a; import org.apache.commons.math3.random.Well19937a; import org.apache.commons.math3.random.Well19937c; import org.apache.commons.math3.random.Well44497a; import org.apache.commons.math3.random.Well44497b; import org.apache.commons.math3.random.Well512a; public class DefaultRandomFactory implements RandomFactory { protected final RandomType randomType; protected final Long randomSeed; /** * @param randomType never null * @param randomSeed null if no seed */ public DefaultRandomFactory(RandomType randomType, Long randomSeed) { this.randomType = randomType; this.randomSeed = randomSeed; } @Override public Random createRandom() { switch (randomType) { case JDK: return randomSeed == null ? new Random() : new Random(randomSeed); case MERSENNE_TWISTER: return new RandomAdaptor(randomSeed == null ? new MersenneTwister() : new MersenneTwister(randomSeed)); case WELL512A: return new RandomAdaptor(randomSeed == null ? new Well512a() : new Well512a(randomSeed)); case WELL1024A: return new RandomAdaptor(randomSeed == null ? new Well1024a() : new Well1024a(randomSeed)); case WELL19937A: return new RandomAdaptor(randomSeed == null ? new Well19937a() : new Well19937a(randomSeed)); case WELL19937C: return new RandomAdaptor(randomSeed == null ? new Well19937c() : new Well19937c(randomSeed)); case WELL44497A: return new RandomAdaptor(randomSeed == null ? new Well44497a() : new Well44497a(randomSeed)); case WELL44497B: return new RandomAdaptor(randomSeed == null ? new Well44497b() : new Well44497b(randomSeed)); default: throw new IllegalStateException("The randomType (" + randomType + ") is not implemented."); } } @Override public String toString() { return randomType.name() + (randomSeed == null ? "" : " with seed " + randomSeed); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/random/RandomFactory.java
package ai.timefold.solver.core.impl.solver.random; import java.util.Random; /** * @see DefaultRandomFactory */ public interface RandomFactory { /** * @return never null */ Random createRandom(); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/random/RandomUtils.java
package ai.timefold.solver.core.impl.solver.random; import java.util.Random; public class RandomUtils { /** * Mimics {@link Random#nextInt(int)} for longs. * * @param random never null * @param n {@code > 0L} * @return like {@link Random#nextInt(int)} but for a long * @see Random#nextInt(int) */ public static long nextLong(Random random, long n) { // This code is based on java.util.Random#nextInt(int)'s javadoc. if (n <= 0L) { throw new IllegalArgumentException("n must be positive"); } if (n < Integer.MAX_VALUE) { return random.nextInt((int) n); } long bits; long val; do { bits = (random.nextLong() << 1) >>> 1; val = bits % n; } while (bits - val + (n - 1L) < 0L); return val; } /** * Mimics {@link Random#nextInt(int)} for doubles. * * @param random never null * @param n {@code > 0.0} * @return like {@link Random#nextInt(int)} but for a double * @see Random#nextInt(int) */ public static double nextDouble(Random random, double n) { // This code is based on java.util.Random#nextInt(int)'s javadoc. if (n <= 0.0) { throw new IllegalArgumentException("n must be positive"); } return random.nextDouble() * n; } private RandomUtils() { } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/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.InnerScore; 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 // ************************************************************************ @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void solvingStarted(SolverScope<Solution_> solverScope) { // Starting bestSolution is already set by Solver.solve(Solution) var scoreDirector = solverScope.getScoreDirector(); InnerScore innerScore = scoreDirector.calculateScore(); var score = innerScore.raw(); solverScope.setBestScore(innerScore); solverScope.setBestSolutionTimeMillis(solverScope.getClock().millis()); // The original bestSolution might be the final bestSolution and should have an accurate Score solverScope.getSolutionDescriptor().setScore(solverScope.getBestSolution(), score); if (innerScore.isFullyAssigned()) { solverScope.setStartingInitializedScore(innerScore.raw()); } else { solverScope.setStartingInitializedScore(null); } if (assertInitialScoreFromScratch) { scoreDirector.assertWorkingScoreFromScratch(innerScore, "Initial score calculated"); } if (assertShadowVariablesAreNotStale) { scoreDirector.assertShadowVariablesAreNotStale(innerScore, "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 <Score_ extends Score<Score_>> void processWorkingSolutionDuringStep(AbstractStepScope<Solution_> stepScope) { var phaseScope = stepScope.getPhaseScope(); var score = stepScope.<Score_> getScore(); var solverScope = phaseScope.getSolverScope(); var bestScoreImproved = score.compareTo(solverScope.getBestScore()) > 0; stepScope.setBestScoreImproved(bestScoreImproved); if (bestScoreImproved) { phaseScope.setBestSolutionStepIndex(stepScope.getStepIndex()); var newBestSolution = stepScope.createOrGetClonedSolution(); var innerScore = InnerScore.withUnassignedCount( solverScope.getSolutionDescriptor().<Score_> getScore(newBestSolution), -stepScope.getScoreDirector().getWorkingInitScore()); updateBestSolutionAndFire(solverScope, innerScore, newBestSolution); } else if (assertBestScoreIsUnmodified) { solverScope.assertScoreFromScratch(solverScope.getBestSolution()); } } public <Score_ extends Score<Score_>> void processWorkingSolutionDuringMove(InnerScore<Score_> moveScore, AbstractStepScope<Solution_> stepScope) { var phaseScope = stepScope.getPhaseScope(); var solverScope = phaseScope.getSolverScope(); var bestScoreImproved = moveScore.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()); var newBestSolution = solverScope.getScoreDirector().cloneWorkingSolution(); var innerScore = new InnerScore<>(moveScore.raw(), solverScope.getScoreDirector().getWorkingInitScore()); updateBestSolutionAndFire(solverScope, innerScore, 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, InnerScore<?> bestScore, Solution_ bestSolution) { updateBestSolutionWithoutFiring(solverScope, bestScore, bestSolution); solverEventSupport.fireBestSolutionChanged(solverScope, bestSolution); } @SuppressWarnings({ "unchecked", "rawtypes" }) private void updateBestSolutionWithoutFiring(SolverScope<Solution_> solverScope) { // We clone the existing working solution to set it as the best current solution var newBestSolution = solverScope.getScoreDirector().cloneWorkingSolution(); var newBestScore = solverScope.getSolutionDescriptor().<Score> getScore(newBestSolution); var innerScore = InnerScore.withUnassignedCount(newBestScore, -solverScope.getScoreDirector().getWorkingInitScore()); updateBestSolutionWithoutFiring(solverScope, innerScore, newBestSolution); } private void updateBestSolutionWithoutFiring(SolverScope<Solution_> solverScope, InnerScore<?> bestScore, Solution_ bestSolution) { if (bestScore.isFullyAssigned() && !solverScope.isBestSolutionInitialized()) { solverScope.setStartingInitializedScore(bestScore.raw()); } solverScope.setBestSolution(bestSolution); solverScope.setBestScore(bestScore); solverScope.setBestSolutionTimeMillis(solverScope.getClock().millis()); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/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.isFullyAsserted()) { bestSolutionRecaller.setAssertInitialScoreFromScratch(true); bestSolutionRecaller.setAssertShadowVariablesAreNotStale(true); bestSolutionRecaller.setAssertBestScoreIsUnmodified(true); } return bestSolutionRecaller; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/scope/SolverScope.java
package ai.timefold.solver.core.impl.solver.scope; import static ai.timefold.solver.core.impl.util.MathUtils.getSpeed; import java.time.Clock; import java.util.Collections; import java.util.EnumSet; import java.util.Map; import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicLong; 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.InnerScore; import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; import ai.timefold.solver.core.impl.solver.AbstractSolver; import ai.timefold.solver.core.impl.solver.change.DefaultProblemChangeDirector; import ai.timefold.solver.core.impl.solver.monitoring.ScoreLevels; import ai.timefold.solver.core.impl.solver.termination.PhaseTermination; 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_> { private final Clock clock; // Solution-derived fields have the potential for race conditions. private final AtomicReference<ProblemSizeStatistics> problemSizeStatistics = new AtomicReference<>(); private final AtomicReference<Solution_> bestSolution = new AtomicReference<>(); private final AtomicReference<InnerScore<?>> bestScore = new AtomicReference<>(); private final AtomicLong startingSystemTimeMillis = resetAtomicLongTimeMillis(new AtomicLong()); private final AtomicLong endingSystemTimeMillis = resetAtomicLongTimeMillis(new AtomicLong()); private Set<SolverMetric> solverMetricSet = Collections.emptySet(); private Tags monitoringTags; private int startingSolverCount; private Random workingRandom; private InnerScoreDirector<Solution_, ?> scoreDirector; private AbstractSolver<Solution_> solver; private DefaultProblemChangeDirector<Solution_> problemChangeDirector; /** * Used for capping CPU power usage in multithreaded scenarios. */ private Semaphore runnableThreadSemaphore = null; private long childThreadsScoreCalculationCount = 0L; private long moveEvaluationCount = 0L; private Score<?> startingInitializedScore; private Long bestSolutionTimeMillis; /** * Used for tracking step score */ private final Map<Tags, ScoreLevels> stepScoreMap = new ConcurrentHashMap<>(); /** * Used for tracking move count per move type */ private final Map<String, Long> moveEvaluationCountPerTypeMap = new ConcurrentHashMap<>(); private static AtomicLong resetAtomicLongTimeMillis(AtomicLong atomicLong) { atomicLong.set(-1); return atomicLong; } private static Long readAtomicLongTimeMillis(AtomicLong atomicLong) { var value = atomicLong.get(); return value == -1 ? null : value; } public SolverScope() { this.clock = Clock.systemDefaultZone(); } public SolverScope(Clock clock) { this.clock = Objects.requireNonNull(clock); } public Clock getClock() { return clock; } public AbstractSolver<Solution_> getSolver() { return solver; } public void setSolver(AbstractSolver<Solution_> solver) { this.solver = solver; } 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, ScoreLevels> 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; } @SuppressWarnings("unchecked") 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 readAtomicLongTimeMillis(startingSystemTimeMillis); } public Long getEndingSystemTimeMillis() { return readAtomicLongTimeMillis(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_ extends Score<Score_>> InnerScore<Score_> calculateScore() { return this.<Score_> getScoreDirector().calculateScore(); } public void assertScoreFromScratch(Solution_ solution) { scoreDirector.getScoreDirectorFactory().assertScoreFromScratch(solution); } @SuppressWarnings("unchecked") public <Score_ extends Score<Score_>> Score_ getStartingInitializedScore() { return (Score_) startingInitializedScore; } public void setStartingInitializedScore(Score<?> startingInitializedScore) { this.startingInitializedScore = startingInitializedScore; } public void addChildThreadsScoreCalculationCount(long addition) { childThreadsScoreCalculationCount += addition; } public long getScoreCalculationCount() { return scoreDirector.getCalculationCount() + childThreadsScoreCalculationCount; } public void addMoveEvaluationCount(long addition) { moveEvaluationCount += addition; } public long getMoveEvaluationCount() { return moveEvaluationCount; } public Solution_ getBestSolution() { return bestSolution.get(); } /** * 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.set(bestSolution); } @SuppressWarnings("unchecked") public <Score_ extends Score<Score_>> InnerScore<Score_> getBestScore() { return (InnerScore<Score_>) bestScore.get(); } public <Score_ extends Score<Score_>> void setInitializedBestScore(Score_ bestScore) { setBestScore(InnerScore.fullyAssigned(bestScore)); } public <Score_ extends Score<Score_>> void setBestScore(InnerScore<Score_> bestScore) { this.bestScore.set(bestScore); } public Long getBestSolutionTimeMillis() { return bestSolutionTimeMillis; } public void setBestSolutionTimeMillis(Long bestSolutionTimeMillis) { this.bestSolutionTimeMillis = bestSolutionTimeMillis; } public Set<String> getMoveCountTypes() { return moveEvaluationCountPerTypeMap.keySet(); } public Map<String, Long> getMoveEvaluationCountPerType() { return moveEvaluationCountPerTypeMap; } // ************************************************************************ // Calculated methods // ************************************************************************ public boolean isMetricEnabled(SolverMetric solverMetric) { return solverMetricSet.contains(solverMetric); } public void startingNow() { startingSystemTimeMillis.set(getClock().millis()); resetAtomicLongTimeMillis(endingSystemTimeMillis); this.moveEvaluationCount = 0L; } public Long getBestSolutionTimeMillisSpent() { return getBestSolutionTimeMillis() - getStartingSystemTimeMillis(); } public void endingNow() { endingSystemTimeMillis.set(getClock().millis()); } public boolean isBestSolutionInitialized() { return getBestScore().isFullyAssigned(); } public long calculateTimeMillisSpentUpToNow() { var now = getClock().millis(); return now - getStartingSystemTimeMillis(); } public long getTimeMillisSpent() { var startingMillis = getStartingSystemTimeMillis(); if (startingMillis == null) { // The solver hasn't started yet. return 0L; } var endingMillis = getEndingSystemTimeMillis(); if (endingMillis == null) { // The solver hasn't ended yet. endingMillis = getClock().millis(); } return endingMillis - startingMillis; } public ProblemSizeStatistics getProblemSizeStatistics() { return problemSizeStatistics.get(); } public void setProblemSizeStatistics(ProblemSizeStatistics problemSizeStatistics) { this.problemSizeStatistics.set(problemSizeStatistics); } /** * @return at least 0, per second */ public long getScoreCalculationSpeed() { long timeMillisSpent = getTimeMillisSpent(); return getSpeed(getScoreCalculationCount(), timeMillisSpent); } /** * @return at least 0, per second */ public long getMoveEvaluationSpeed() { long timeMillisSpent = getTimeMillisSpent(); return getSpeed(getMoveEvaluationCount(), timeMillisSpent); } public void setWorkingSolutionFromBestSolution() { // The workingSolution must never be the same instance as the bestSolution. // Since we are doing a planning clone, we need to update consistency shadows // that are inside identity hash map. scoreDirector.setWorkingSolution(scoreDirector.cloneSolution(getBestSolution())); } public void setInitialSolution(Solution_ initialSolution) { // The workingSolution must never be the same instance as the bestSolution. scoreDirector.setWorkingSolution(scoreDirector.cloneSolution(initialSolution)); // Set the best solution to the solution with shadow variable updated. setBestSolution(scoreDirector.cloneSolution(scoreDirector.getWorkingSolution())); } public SolverScope<Solution_> createChildThreadSolverScope(ChildThreadType childThreadType) { SolverScope<Solution_> childThreadSolverScope = new SolverScope<>(clock); childThreadSolverScope.bestSolution.set(null); childThreadSolverScope.bestScore.set(null); 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.set(startingSystemTimeMillis.get()); resetAtomicLongTimeMillis(childThreadSolverScope.endingSystemTimeMillis); childThreadSolverScope.startingInitializedScore = 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 PhaseTermination#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(); } } public void addMoveEvaluationCountPerType(String moveType, long count) { moveEvaluationCountPerTypeMap.compute(moveType, (key, counter) -> { if (counter == null) { counter = 0L; } counter += count; return counter; }); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/AbstractCompositeTermination.java
package ai.timefold.solver.core.impl.solver.termination; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import ai.timefold.solver.core.impl.solver.thread.ChildThreadType; import org.jspecify.annotations.NullMarked; /** * Abstract superclass that combines multiple {@link Termination}s. * * @see AndCompositeTermination * @see OrCompositeTermination */ @NullMarked abstract sealed class AbstractCompositeTermination<Solution_> extends AbstractUniversalTermination<Solution_> permits AndCompositeTermination, OrCompositeTermination { protected final List<Termination<Solution_>> terminationList; protected final List<PhaseTermination<Solution_>> phaseTerminationList; protected final List<SolverTermination<Solution_>> solverTerminationList; protected AbstractCompositeTermination(List<Termination<Solution_>> terminationList) { this.terminationList = Objects.requireNonNull(terminationList); this.phaseTerminationList = terminationList.stream() .filter(PhaseTermination.class::isInstance) .map(t -> (PhaseTermination<Solution_>) t) .toList(); this.solverTerminationList = terminationList.stream() .filter(SolverTermination.class::isInstance) .map(t -> (SolverTermination<Solution_>) t) .toList(); } @SafeVarargs public AbstractCompositeTermination(Termination<Solution_>... terminations) { this(Arrays.asList(terminations)); } @Override public final void solvingStarted(SolverScope<Solution_> solverScope) { for (var termination : solverTerminationList) { termination.solvingStarted(solverScope); } } @Override public final void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { for (var termination : phaseTerminationList) { termination.phaseStarted(phaseScope); } } @Override public final void stepStarted(AbstractStepScope<Solution_> stepScope) { for (var termination : phaseTerminationList) { termination.stepStarted(stepScope); } } @Override public final void stepEnded(AbstractStepScope<Solution_> stepScope) { for (var termination : phaseTerminationList) { termination.stepEnded(stepScope); } } @Override public final void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { for (var termination : phaseTerminationList) { termination.phaseEnded(phaseScope); } } @Override public final void solvingEnded(SolverScope<Solution_> solverScope) { for (var termination : solverTerminationList) { termination.solvingEnded(solverScope); } } protected final List<Termination<Solution_>> createChildThreadTerminationList(SolverScope<Solution_> solverScope, ChildThreadType childThreadType) { List<Termination<Solution_>> childThreadTerminationList = new ArrayList<>(terminationList.size()); for (var termination : terminationList) { var childThreadSupportingTermination = ChildThreadSupportingTermination.assertChildThreadSupport(termination); childThreadTerminationList .add(childThreadSupportingTermination.createChildThreadTermination(solverScope, childThreadType)); } return childThreadTerminationList; } @Override public final List<PhaseTermination<Solution_>> getPhaseTerminationList() { var result = new ArrayList<PhaseTermination<Solution_>>(); for (var termination : phaseTerminationList) { result.add(termination); if (termination instanceof UniversalTermination<Solution_> universalTermination) { result.addAll(universalTermination.getPhaseTerminationList()); } } return List.copyOf(result); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/AbstractPhaseTermination.java
package ai.timefold.solver.core.impl.solver.termination; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope; import org.jspecify.annotations.NullMarked; @NullMarked abstract sealed class AbstractPhaseTermination<Solution_> extends AbstractTermination<Solution_> implements PhaseTermination<Solution_> permits DiminishedReturnsTermination, SolverBridgePhaseTermination, StepCountTermination, UnimprovedStepCountTermination { @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { // Override if needed. } @Override public void stepStarted(AbstractStepScope<Solution_> stepScope) { // Override if needed. } @Override public void stepEnded(AbstractStepScope<Solution_> stepScope) { // Override if needed. } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { // Override if needed. } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/AbstractTermination.java
package ai.timefold.solver.core.impl.solver.termination; import org.jspecify.annotations.NullMarked; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @NullMarked abstract sealed class AbstractTermination<Solution_> implements Termination<Solution_> permits AbstractPhaseTermination, AbstractUniversalTermination { protected final transient Logger logger = LoggerFactory.getLogger(getClass()); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/AbstractUniversalTermination.java
package ai.timefold.solver.core.impl.solver.termination; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import org.jspecify.annotations.NullMarked; @NullMarked abstract sealed class AbstractUniversalTermination<Solution_> extends AbstractTermination<Solution_> implements UniversalTermination<Solution_> permits AbstractCompositeTermination, BasicPlumbingTermination, BestScoreFeasibleTermination, BestScoreTermination, ChildThreadPlumbingTermination, MoveCountTermination, ScoreCalculationCountTermination, TimeMillisSpentTermination, UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination, UnimprovedTimeMillisSpentTermination { @Override public void solvingStarted(SolverScope<Solution_> solverScope) { // Override if needed. } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { // Override if needed. } @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { // Override if needed. } @Override public void stepStarted(AbstractStepScope<Solution_> stepScope) { // Override if needed. } @Override public void stepEnded(AbstractStepScope<Solution_> stepScope) { // Override if needed. } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { // Override if needed. } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/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; import org.jspecify.annotations.NullMarked; @NullMarked final class AndCompositeTermination<Solution_> extends AbstractCompositeTermination<Solution_> implements ChildThreadSupportingTermination<Solution_, SolverScope<Solution_>> { public AndCompositeTermination(List<Termination<Solution_>> terminationList) { super(terminationList); } @SafeVarargs public AndCompositeTermination(Termination<Solution_>... terminations) { super(terminations); } /** * @return true if all terminations are terminated. */ @Override public boolean isSolverTerminated(SolverScope<Solution_> solverScope) { for (var termination : solverTerminationList) { if (!termination.isSolverTerminated(solverScope)) { return false; } } return true; } /** * @return true if all supported terminations are terminated. */ @Override public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) { for (var termination : phaseTerminationList) { if (termination.isApplicableTo(phaseScope.getClass()) && !termination.isPhaseTerminated(phaseScope)) { return false; } } return true; } /** * Calculates the minimum timeGradient of all Terminations. * Not supported timeGradients (-1.0) are ignored. * * @return the minimum timeGradient of the Terminations. */ @Override public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) { var timeGradient = 1.0; for (var termination : solverTerminationList) { var 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. * * @return the minimum timeGradient of the Terminations. */ @Override public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) { var timeGradient = 1.0; for (var termination : phaseTerminationList) { if (!termination.isApplicableTo(phaseScope.getClass())) { continue; } var nextTimeGradient = termination.calculatePhaseTimeGradient(phaseScope); if (nextTimeGradient >= 0.0) { timeGradient = Math.min(timeGradient, nextTimeGradient); } } return timeGradient; } @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/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/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; import org.jspecify.annotations.NullMarked; /** * Concurrency notes: * Condition predicate on ({@link #problemChangeQueue} is not empty or {@link #terminatedEarly} is true). */ @NullMarked public final class BasicPlumbingTermination<Solution_> extends AbstractUniversalTermination<Solution_> implements ChildThreadSupportingTermination<Solution_, SolverScope<Solution_>> { private final boolean daemon; private final BlockingQueue<ProblemChangeAdapter<Solution_>> problemChangeQueue = new LinkedBlockingQueue<>(); private boolean terminatedEarly = false; private boolean problemChangesBeingProcessed = false; public BasicPlumbingTermination(boolean daemon) { this.daemon = daemon; } /** * 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 #problemChangeQueue} is not empty or {@link #terminatedEarly} is true. * * @return true if the solver needs to be restarted */ public synchronized boolean waitForRestartSolverDecision() { if (!daemon) { return !problemChangeQueue.isEmpty() && !terminatedEarly; } else { while (problemChangeQueue.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 problemChangeList never null * @return as specified by {@link Collection#add} */ public synchronized boolean addProblemChanges(List<ProblemChangeAdapter<Solution_>> problemChangeList) { boolean added = problemChangeQueue.addAll(problemChangeList); notifyAll(); return added; } public synchronized BlockingQueue<ProblemChangeAdapter<Solution_>> startProblemChangesProcessing() { problemChangesBeingProcessed = true; return problemChangeQueue; } public synchronized void endProblemChangesProcessing() { problemChangesBeingProcessed = false; } public synchronized boolean isEveryProblemChangeProcessed() { return problemChangeQueue.isEmpty() && !problemChangesBeingProcessed; } @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 || !problemChangeQueue.isEmpty(); } @Override public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) { return -1.0; // Not supported } @Override public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) { return isSolverTerminated(phaseScope.getSolverScope()); } @Override public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) { return calculateSolverTimeGradient(phaseScope.getSolverScope()); } @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/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/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.score.director.InnerScore; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked final class BestScoreFeasibleTermination<Solution_> extends AbstractUniversalTermination<Solution_> { private final int feasibleLevelsSize; private final double[] timeGradientWeightFeasibleNumbers; public BestScoreFeasibleTermination(ScoreDefinition<?> scoreDefinition, double[] timeGradientWeightFeasibleNumbers) { this.feasibleLevelsSize = scoreDefinition.getFeasibleLevelsSize(); this.timeGradientWeightFeasibleNumbers = timeGradientWeightFeasibleNumbers; if (timeGradientWeightFeasibleNumbers.length != this.feasibleLevelsSize - 1) { throw new IllegalStateException( "The timeGradientWeightNumbers (%s)'s length (%d) is not 1 less than the feasibleLevelsSize (%d)." .formatted(Arrays.toString(timeGradientWeightFeasibleNumbers), timeGradientWeightFeasibleNumbers.length, scoreDefinition.getFeasibleLevelsSize())); } } @Override public boolean isSolverTerminated(SolverScope<Solution_> solverScope) { return isTerminated(solverScope.getBestScore()); } @Override public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) { return isTerminated(phaseScope.getBestScore()); } private static boolean isTerminated(InnerScore<?> innerScore) { return innerScore.isFullyAssigned() && innerScore.raw().isFeasible(); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) { return calculateFeasibilityTimeGradient(InnerScore.fullyAssigned((Score) solverScope.getStartingInitializedScore()), solverScope.getBestScore().raw()); } @Override public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) { return calculateFeasibilityTimeGradient(phaseScope.getStartingScore(), phaseScope.getBestScore().raw()); } <Score_ extends Score<Score_>> double calculateFeasibilityTimeGradient(@Nullable InnerScore<Score_> innerStartScore, Score_ score) { if (innerStartScore == null || !innerStartScore.isFullyAssigned()) { return 0.0; } var startScore = innerStartScore.raw(); var totalDiff = startScore.negate(); var totalDiffNumbers = totalDiff.toLevelNumbers(); var scoreDiff = score.subtract(startScore); var 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); } @Override public String toString() { return "BestScoreFeasible()"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/BestScoreTermination.java
package ai.timefold.solver.core.impl.solver.termination; import java.util.Arrays; import java.util.Objects; 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.score.director.InnerScore; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import org.jspecify.annotations.NullMarked; @NullMarked final class BestScoreTermination<Solution_> extends AbstractUniversalTermination<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 = Objects.requireNonNull(bestScoreLimit, "The bestScoreLimit cannot be null."); this.timeGradientWeightNumbers = timeGradientWeightNumbers; if (timeGradientWeightNumbers.length != levelsSize - 1) { throw new IllegalStateException( "The timeGradientWeightNumbers (%s)'s length (%d) is not 1 less than the levelsSize (%d)." .formatted(Arrays.toString(timeGradientWeightNumbers), timeGradientWeightNumbers.length, scoreDefinition.getLevelsSize())); } } @Override public boolean isSolverTerminated(SolverScope<Solution_> solverScope) { return isTerminated(solverScope.isBestSolutionInitialized(), solverScope.getBestScore().raw()); } @Override public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) { return isTerminated(phaseScope.isBestSolutionInitialized(), phaseScope.getBestScore().raw()); } private <Score_ extends Score<Score_>> boolean isTerminated(boolean bestSolutionInitialized, Score_ bestScore) { return bestSolutionInitialized && bestScore.compareTo(getBestScoreLimit()) >= 0; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) { var startingInitializedScore = solverScope.getStartingInitializedScore(); var bestScore = solverScope.getBestScore(); return calculateTimeGradient((Score) startingInitializedScore, getBestScoreLimit(), (Score) bestScore.raw()); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) { var startingInitializedScore = phaseScope.<Score> getStartingScore(); var bestScore = phaseScope.<Score> getBestScore(); return calculateTimeGradient(startingInitializedScore.raw(), getBestScoreLimit(), bestScore.raw()); } /** * CH is not allowed to compute a time gradient. * Therefore the scores at this point no longer need to be {@link InnerScore}. */ <Score_ extends Score<Score_>> double calculateTimeGradient(Score_ startScore, Score_ endScore, Score_ score) { var totalDiff = endScore.subtract(startScore); var totalDiffNumbers = totalDiff.toLevelNumbers(); var scoreDiff = score.subtract(startScore); var 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) { var timeGradient = 0.0; var remainingTimeGradient = 1.0; for (var i = 0; i < levelDepth; i++) { double levelTimeGradientWeight; if (i != (levelDepth - 1)) { levelTimeGradientWeight = remainingTimeGradient * timeGradientWeightNumbers[i]; remainingTimeGradient -= levelTimeGradientWeight; } else { levelTimeGradientWeight = remainingTimeGradient; remainingTimeGradient = 0.0; } var totalDiffLevel = totalDiffNumbers[i].doubleValue(); var 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 { var levelTimeGradient = scoreDiffLevel / totalDiffLevel; timeGradient += levelTimeGradient * levelTimeGradientWeight; } } if (timeGradient > 1.0) { // Rounding error due to calculating with doubles timeGradient = 1.0; } return timeGradient; } @SuppressWarnings("unchecked") public <Score_ extends Score<Score_>> Score_ getBestScoreLimit() { return (Score_) bestScoreLimit; } @Override public String toString() { return "BestScore(" + bestScoreLimit + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/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; import org.jspecify.annotations.NullMarked; @NullMarked public final class ChildThreadPlumbingTermination<Solution_> extends AbstractUniversalTermination<Solution_> implements ChildThreadSupportingTermination<Solution_, SolverScope<Solution_>> { private boolean terminateChildren = false; /** * This method is thread-safe. * * @return true if termination hasn't been requested previously */ public synchronized boolean terminateChildren() { var terminationEarlySuccessful = !terminateChildren; terminateChildren = true; return terminationEarlySuccessful; } @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 double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) { return -1.0; // Not supported } @Override public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) { return isSolverTerminated(phaseScope.getSolverScope()); } @Override public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) { return calculateSolverTimeGradient(phaseScope.getSolverScope()); } @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/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/ChildThreadSupportingTermination.java
package ai.timefold.solver.core.impl.solver.termination; import ai.timefold.solver.core.api.solver.Solver; 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; import org.jspecify.annotations.NullMarked; @NullMarked public interface ChildThreadSupportingTermination<Solution_, Scope_> { /** * Create a {@link Termination} for a child {@link Thread} of the {@link Solver}. * * @param scope Either {@link SolverScope} or {@link AbstractPhaseScope} * @return not null */ Termination<Solution_> createChildThreadTermination(Scope_ scope, ChildThreadType childThreadType); @SuppressWarnings({ "rawtypes", "unchecked" }) static <Solution_, Scope_> ChildThreadSupportingTermination<Solution_, Scope_> assertChildThreadSupport(Termination<Solution_> termination) { if (termination instanceof ChildThreadSupportingTermination childThreadSupportingTermination) { return childThreadSupportingTermination; } throw new UnsupportedOperationException( "This terminationClass (%s) does not yet support being used in child threads." .formatted(termination.getClass().getSimpleName())); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/DiminishedReturnsScoreRingBuffer.java
package ai.timefold.solver.core.impl.solver.termination; import java.util.Arrays; import java.util.NavigableMap; import java.util.Objects; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.score.director.InnerScore; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; /** * A heavily specialized pair of * <a href="https://en.wikipedia.org/wiki/Circular_buffer">ring buffers</a> * that acts as a {@link NavigableMap} for getting the scores at a prior time. * <br/> * The ring buffers operate with the following assumptions: * <ul> * <li>Keys (i.e. {@link System#nanoTime()} are inserted in ascending order</li> * <li>Times are queried in ascending order</li> * <li>The queried time is probably near the start of the ring buffer</li> * </ul> * <br/> * {@link DiminishedReturnsScoreRingBuffer} automatically clear entries prior * to the queried time when polled (if the queried time is not in the * {@link DiminishedReturnsScoreRingBuffer}, then the largest entry prior * to the queried time is kept and returned). * The ring buffers will automatically resize when filled past their capacity. * * @param <Score_> The score type */ final class DiminishedReturnsScoreRingBuffer<Score_ extends Score<Score_>> { /** * Arbitrary; 4096 is a common buffer size and is * the default page size in the linux kernel. */ private static final int DEFAULT_CAPACITY = 4096; int readIndex; int writeIndex; private long[] nanoTimeRingBuffer; private InnerScore<Score_>[] scoreRingBuffer; DiminishedReturnsScoreRingBuffer() { this(DEFAULT_CAPACITY); } @SuppressWarnings("unchecked") DiminishedReturnsScoreRingBuffer(int capacity) { this(0, 0, new long[capacity], new InnerScore[capacity]); } DiminishedReturnsScoreRingBuffer(int readIndex, int writeIndex, long[] nanoTimeRingBuffer, @Nullable InnerScore<Score_>[] scoreRingBuffer) { this.nanoTimeRingBuffer = nanoTimeRingBuffer; this.scoreRingBuffer = scoreRingBuffer; this.readIndex = readIndex; this.writeIndex = writeIndex; } record RingBufferState(int readIndex, int writeIndex, long[] nanoTimeRingBuffer, @Nullable InnerScore<?>[] scoreRingBuffer) { @Override public boolean equals(Object o) { if (!(o instanceof RingBufferState that)) { return false; } return readIndex == that.readIndex && writeIndex == that.writeIndex && Objects.deepEquals(nanoTimeRingBuffer, that.nanoTimeRingBuffer) && Objects.deepEquals(scoreRingBuffer, that.scoreRingBuffer); } @Override public int hashCode() { return Objects.hash(readIndex, writeIndex, Arrays.hashCode(nanoTimeRingBuffer), Arrays.hashCode(scoreRingBuffer)); } @Override public String toString() { return "RingBufferState{" + "readIndex=" + readIndex + ", writeIndex=" + writeIndex + ", nanoTimeRingBuffer=" + Arrays.toString(nanoTimeRingBuffer) + ", scoreRingBuffer=" + Arrays.toString(scoreRingBuffer) + '}'; } } @NonNull RingBufferState getState() { return new RingBufferState(readIndex, writeIndex, nanoTimeRingBuffer, scoreRingBuffer); } @SuppressWarnings("unchecked") void resize() { var newCapacity = nanoTimeRingBuffer.length * 2; var newNanoTimeRingBuffer = new long[newCapacity]; var newScoreRingBuffer = new InnerScore[newCapacity]; if (readIndex < writeIndex) { // entries are [startIndex, writeIndex) var newLength = writeIndex - readIndex; System.arraycopy(nanoTimeRingBuffer, readIndex, newNanoTimeRingBuffer, 0, newLength); System.arraycopy(scoreRingBuffer, readIndex, newScoreRingBuffer, 0, newLength); readIndex = 0; writeIndex = newLength; } else { // entries are [readIndex, CAPACITY) + [0, writeIndex) var firstLength = nanoTimeRingBuffer.length - readIndex; var secondLength = writeIndex; var totalLength = firstLength + secondLength; System.arraycopy(nanoTimeRingBuffer, readIndex, newNanoTimeRingBuffer, 0, firstLength); System.arraycopy(scoreRingBuffer, readIndex, newScoreRingBuffer, 0, firstLength); System.arraycopy(nanoTimeRingBuffer, 0, newNanoTimeRingBuffer, firstLength, secondLength); System.arraycopy(scoreRingBuffer, 0, newScoreRingBuffer, firstLength, secondLength); readIndex = 0; writeIndex = totalLength; } nanoTimeRingBuffer = newNanoTimeRingBuffer; scoreRingBuffer = newScoreRingBuffer; } /** * Removes all elements in the buffer. */ public void clear() { readIndex = 0; writeIndex = 0; Arrays.fill(nanoTimeRingBuffer, 0); Arrays.fill(scoreRingBuffer, null); } /** * Returns the first element of the score ring buffer. * Does not remove the element. * Raises an exception if the buffer is * empty. * * @return the first element of the score ring buffer */ public @NonNull InnerScore<Score_> peekFirst() { var out = scoreRingBuffer[readIndex]; if (out == null) { throw new IllegalStateException("Impossible state: buffer is empty"); } return out; } /** * Adds a time-score pairing to the ring buffers, resizing the * ring buffers if necessary. * * @param nanoTime the {@link System#nanoTime()} when the score was produced. * @param score the score that was produced. */ public void put(long nanoTime, @NonNull InnerScore<Score_> score) { if (nanoTimeRingBuffer[writeIndex] != 0L) { resize(); } nanoTimeRingBuffer[writeIndex] = nanoTime; scoreRingBuffer[writeIndex] = score; writeIndex = (writeIndex + 1) % nanoTimeRingBuffer.length; } /** * Removes count elements from both ring buffers, * and returns the next element (which remains in the buffers). * * @param count the number of items to remove from both buffers. * @return the first element in the score ring buffer after the count * elements were removed. */ private @NonNull InnerScore<Score_> clearCountAndPeekNext(int count) { if (readIndex + count < nanoTimeRingBuffer.length) { Arrays.fill(nanoTimeRingBuffer, readIndex, readIndex + count, 0L); Arrays.fill(scoreRingBuffer, readIndex, readIndex + count, null); readIndex += count; } else { int remaining = count - (nanoTimeRingBuffer.length - readIndex); Arrays.fill(nanoTimeRingBuffer, readIndex, nanoTimeRingBuffer.length, 0L); Arrays.fill(scoreRingBuffer, readIndex, nanoTimeRingBuffer.length, null); Arrays.fill(nanoTimeRingBuffer, 0, remaining, 0L); Arrays.fill(scoreRingBuffer, 0, remaining, null); readIndex = remaining; } return scoreRingBuffer[readIndex]; } /** * Returns the latest score prior or at the given time, and removes * all time-score pairings prior to it. * * @param nanoTime the queried time in nanoseconds. * @return the latest score prior to the given time. */ public @NonNull InnerScore<Score_> pollLatestScoreBeforeTimeAndClearPrior(long nanoTime) { if (readIndex == writeIndex && nanoTimeRingBuffer[writeIndex] == 0L) { throw new IllegalStateException("Impossible state: buffer is empty"); } // entries are [readIndex, CAPACITY) + [0, writeIndex) int end = (readIndex < writeIndex) ? writeIndex : nanoTimeRingBuffer.length; for (int i = readIndex; i < end; i++) { if (nanoTimeRingBuffer[i] == nanoTime) { return clearCountAndPeekNext(i - readIndex); } if (nanoTimeRingBuffer[i] > nanoTime) { return clearCountAndPeekNext(i - readIndex - 1); } } int countRead = end - readIndex; if (writeIndex < readIndex && writeIndex != 0) { if (nanoTimeRingBuffer[0] == nanoTime) { return clearCountAndPeekNext(countRead); } if (nanoTimeRingBuffer[0] > nanoTime) { return clearCountAndPeekNext(countRead - 1); } for (int i = 1; i < writeIndex; i++) { if (nanoTimeRingBuffer[i] == nanoTime) { return clearCountAndPeekNext(countRead + i); } if (nanoTimeRingBuffer[i] > nanoTime) { return clearCountAndPeekNext(countRead + i - 1); } } // Buffer has at least one element, and the query should always be // greater than it. Since we exited the loop, return the last element. return clearCountAndPeekNext(countRead + writeIndex - 1); } else { // Buffer has at least one element, and the query should always be // greater than it. Since we exited the loop, return the last element. return clearCountAndPeekNext(countRead - 1); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/DiminishedReturnsTermination.java
package ai.timefold.solver.core.impl.solver.termination; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicPhaseScope; import ai.timefold.solver.core.impl.phase.custom.scope.CustomPhaseScope; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope; import ai.timefold.solver.core.impl.score.director.InnerScore; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import ai.timefold.solver.core.impl.solver.thread.ChildThreadType; import org.jspecify.annotations.NullMarked; @NullMarked final class DiminishedReturnsTermination<Solution_, Score_ extends Score<Score_>> extends AbstractPhaseTermination<Solution_> implements ChildThreadSupportingTermination<Solution_, SolverScope<Solution_>> { static final long NANOS_PER_MILLISECOND = 1_000_000; private final long slidingWindowNanos; private final double minimumImprovementRatio; private boolean isGracePeriodActive; private boolean isGracePeriodStarted = false; private long gracePeriodStartTimeNanos; private double gracePeriodSoftestImprovementDouble; private final DiminishedReturnsScoreRingBuffer<Score_> scoresByTime; public DiminishedReturnsTermination(long slidingWindowMillis, double minimumImprovementRatio) { if (slidingWindowMillis < 0L) { throw new IllegalArgumentException("The slidingWindowMillis (%d) cannot be negative." .formatted(slidingWindowMillis)); } if (minimumImprovementRatio <= 0.0) { throw new IllegalArgumentException("The minimumImprovementRatio (%f) must be positive." .formatted(minimumImprovementRatio)); } // convert to nanoseconds here so we don't need to do a // division in the hot loop this.slidingWindowNanos = slidingWindowMillis * NANOS_PER_MILLISECOND; this.minimumImprovementRatio = minimumImprovementRatio; this.scoresByTime = new DiminishedReturnsScoreRingBuffer<>(); } public long getSlidingWindowNanos() { return slidingWindowNanos; } public double getMinimumImprovementRatio() { return minimumImprovementRatio; } /** * Returns the improvement in the softest level between the prior * and current best scores as a double, or {@link Double#NaN} if * there is a difference in any of their other levels. * * @param start the prior best score * @param end the current best score * @return the softest level difference between end and start, or * {@link Double#NaN} if a harder level changed * @param <Score_> The score type */ private static <Score_ extends Score<Score_>> double softImprovementOrNaNForHarderChange(InnerScore<Score_> start, InnerScore<Score_> end) { if (start.equals(end)) { // optimization: since most of the time the score the same, // we can use equals to avoid creating double arrays in the // vast majority of comparisons return 0.0; } if (start.unassignedCount() != end.unassignedCount()) { // init score improved return Double.NaN; } var scoreDiffs = end.raw().subtract(start.raw()).toLevelDoubles(); var softestLevel = scoreDiffs.length - 1; for (int i = 0; i < softestLevel; i++) { if (scoreDiffs[i] != 0.0) { return Double.NaN; } } return scoreDiffs[softestLevel]; } public void start(long startTime, InnerScore<Score_> startingScore) { resetGracePeriod(startTime, startingScore); } public void step(long time, InnerScore<Score_> bestScore) { scoresByTime.put(time, bestScore); } private void resetGracePeriod(long currentTime, InnerScore<Score_> startingScore) { gracePeriodStartTimeNanos = currentTime; isGracePeriodActive = true; isGracePeriodStarted = true; // Remove all entries in the map since grace is reset scoresByTime.clear(); // Put the current best score as the first entry scoresByTime.put(currentTime, startingScore); } public boolean isTerminated(long currentTime, InnerScore<Score_> endScore) { if (!isGracePeriodStarted) { return false; } if (isGracePeriodActive) { // first score in scoresByTime = first score in grace period window var endpointDiff = softImprovementOrNaNForHarderChange(scoresByTime.peekFirst(), endScore); if (Double.isNaN(endpointDiff)) { resetGracePeriod(currentTime, endScore); return false; } var timeElapsedNanos = currentTime - gracePeriodStartTimeNanos; if (timeElapsedNanos >= slidingWindowNanos) { // grace period over, record the reference diff isGracePeriodActive = false; gracePeriodSoftestImprovementDouble = endpointDiff; if (endpointDiff < 0.0) { // Should be impossible; the only cases where the best score improves // and have a lower softest level are if either a harder level or init score // improves, but if that happens, we reset the grace period. throw new IllegalStateException( "Impossible state: The score deteriorated from (%s) to (%s) during the grace period." .formatted(scoresByTime.peekFirst(), endScore)); } return endpointDiff == 0.0; } return false; } var startScore = scoresByTime.pollLatestScoreBeforeTimeAndClearPrior(currentTime - slidingWindowNanos); var scoreDiff = softImprovementOrNaNForHarderChange(startScore, endScore); if (Double.isNaN(scoreDiff)) { resetGracePeriod(currentTime, endScore); return false; } if (gracePeriodSoftestImprovementDouble == 0.0) { // The termination may be queried multiple times, even after completion. // We must ensure the grace period improvement is greater than zero to avoid division by zero errors. return true; } return scoreDiff / gracePeriodSoftestImprovementDouble < minimumImprovementRatio; } @Override public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) { return isTerminated(System.nanoTime(), phaseScope.getBestScore()); } @Override public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) { return -1.0; } @Override public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope, ChildThreadType childThreadType) { return new DiminishedReturnsTermination<>(slidingWindowNanos, minimumImprovementRatio); } @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { isGracePeriodStarted = false; } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { scoresByTime.clear(); } @Override public void stepStarted(AbstractStepScope<Solution_> stepScope) { // We reset the count only when the first step begins, // as all necessary resources are loaded, and the phase is ready for execution if (!isGracePeriodStarted) { start(System.nanoTime(), stepScope.getPhaseScope().getBestScore()); } } @Override public void stepEnded(AbstractStepScope<Solution_> stepScope) { step(System.nanoTime(), stepScope.getPhaseScope().getBestScore()); } @SuppressWarnings("rawtypes") @Override public boolean isApplicableTo(Class<? extends AbstractPhaseScope> phaseScopeClass) { return !(phaseScopeClass == ConstructionHeuristicPhaseScope.class || phaseScopeClass == CustomPhaseScope.class); } boolean isGracePeriodStarted() { return isGracePeriodStarted; } long getGracePeriodStartTimeNanos() { return gracePeriodStartTimeNanos; } @Override public String toString() { return "DiminishedReturns()"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/MockablePhaseTermination.java
package ai.timefold.solver.core.impl.solver.termination; import org.jspecify.annotations.NullMarked; /** * Only exists to make testing easier. * This type is not accessible outside of this package. * * @param <Solution_> */ @NullMarked non-sealed interface MockablePhaseTermination<Solution_> extends PhaseTermination<Solution_> { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/MockableSolverTermination.java
package ai.timefold.solver.core.impl.solver.termination; import org.jspecify.annotations.NullMarked; /** * Only exists to make testing easier. * This type is not accessible outside of this package. * * @param <Solution_> */ @NullMarked non-sealed interface MockableSolverTermination<Solution_> extends SolverTermination<Solution_> { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/MoveCountTermination.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; import org.jspecify.annotations.NullMarked; @NullMarked final class MoveCountTermination<Solution_> extends AbstractUniversalTermination<Solution_> implements ChildThreadSupportingTermination<Solution_, SolverScope<Solution_>> { private final long moveCountLimit; public MoveCountTermination(long moveCountLimit) { this.moveCountLimit = moveCountLimit; if (moveCountLimit < 0L) { throw new IllegalArgumentException("The moveCountLimit (%d) cannot be negative.".formatted(moveCountLimit)); } } @Override public boolean isSolverTerminated(SolverScope<Solution_> solverScope) { return isTerminated(solverScope); } @Override public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) { return isTerminated(phaseScope.getSolverScope()); } private boolean isTerminated(SolverScope<Solution_> solverScope) { long moveEvaluationCount = solverScope.getMoveEvaluationCount(); return moveEvaluationCount >= moveCountLimit; } @Override public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) { return calculateTimeGradient(solverScope); } @Override public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) { return calculateTimeGradient(phaseScope.getSolverScope()); } private double calculateTimeGradient(SolverScope<Solution_> solverScope) { var moveEvaluationCount = solverScope.getMoveEvaluationCount(); var timeGradient = moveEvaluationCount / ((double) moveCountLimit); return Math.min(timeGradient, 1.0); } @Override public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope, ChildThreadType childThreadType) { return new MoveCountTermination<>(moveCountLimit); } @Override public String toString() { return "MoveCount(%d)".formatted(moveCountLimit); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/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; import org.jspecify.annotations.NullMarked; @NullMarked final class OrCompositeTermination<Solution_> extends AbstractCompositeTermination<Solution_> implements ChildThreadSupportingTermination<Solution_, SolverScope<Solution_>> { public OrCompositeTermination(List<Termination<Solution_>> terminationList) { super(terminationList); } @SafeVarargs public OrCompositeTermination(Termination<Solution_>... terminations) { super(terminations); } /** * @param solverScope never null * @return true if any one of the terminations is terminated. */ @Override public boolean isSolverTerminated(SolverScope<Solution_> solverScope) { for (var termination : solverTerminationList) { if (termination.isSolverTerminated(solverScope)) { return true; } } return false; } /** * @return true if any one of the supported terminations is terminated. */ @Override public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) { for (var termination : phaseTerminationList) { if (!termination.isApplicableTo(phaseScope.getClass())) { continue; } if (termination.isPhaseTerminated(phaseScope)) { return true; } } return false; } /** * Calculates the maximum timeGradient of all Terminations. * Not supported timeGradients (-1.0) are ignored. * * @return the maximum timeGradient of the terminations. */ @Override public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) { var timeGradient = 0.0; for (var termination : solverTerminationList) { var 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. * * @return the maximum timeGradient of the supported terminations. */ @Override public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) { var timeGradient = 0.0; for (var termination : phaseTerminationList) { if (!termination.isApplicableTo(phaseScope.getClass())) { continue; } var nextTimeGradient = termination.calculatePhaseTimeGradient(phaseScope); if (nextTimeGradient >= 0.0) { timeGradient = Math.max(timeGradient, nextTimeGradient); } } return timeGradient; } @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/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/PhaseTermination.java
package ai.timefold.solver.core.impl.solver.termination; 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.scope.AbstractPhaseScope; import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope; import org.jspecify.annotations.NullMarked; /** * Determines when a {@link Phase} should stop. */ @NullMarked public sealed interface PhaseTermination<Solution_> extends Termination<Solution_> permits AbstractPhaseTermination, MockablePhaseTermination, UniversalTermination { /** * @return false if the termination should be skipped on the given phase, * when used as part of {@link AbstractCompositeTermination}. */ @SuppressWarnings("rawtypes") default boolean isApplicableTo(Class<? extends AbstractPhaseScope> phaseScopeClass) { return true; } /** * Called by the {@link Phase} after every step and every move to determine if the search should stop. * * @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. * * @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 calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope); void phaseStarted(AbstractPhaseScope<Solution_> phaseScope); void stepStarted(AbstractStepScope<Solution_> stepScope); void stepEnded(AbstractStepScope<Solution_> stepScope); void phaseEnded(AbstractPhaseScope<Solution_> phaseScope); static <Solution_> PhaseTermination<Solution_> bridge(SolverTermination<Solution_> termination) { return new SolverBridgePhaseTermination<>(termination); } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/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; import org.jspecify.annotations.NullMarked; @NullMarked final class ScoreCalculationCountTermination<Solution_> extends AbstractUniversalTermination<Solution_> implements ChildThreadSupportingTermination<Solution_, SolverScope<Solution_>> { private final long scoreCalculationCountLimit; public ScoreCalculationCountTermination(long scoreCalculationCountLimit) { this.scoreCalculationCountLimit = scoreCalculationCountLimit; if (scoreCalculationCountLimit < 0L) { throw new IllegalArgumentException( "The scoreCalculationCountLimit (%d) cannot be negative." .formatted(scoreCalculationCountLimit)); } } @Override public boolean isSolverTerminated(SolverScope<Solution_> solverScope) { return isTerminated(solverScope.getScoreDirector()); } @Override public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) { return isTerminated(phaseScope.getScoreDirector()); } private boolean isTerminated(InnerScoreDirector<Solution_, ?> scoreDirector) { var scoreCalculationCount = scoreDirector.getCalculationCount(); return scoreCalculationCount >= scoreCalculationCountLimit; } @Override public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) { return calculateTimeGradient(solverScope.getScoreDirector()); } @Override public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) { return calculateTimeGradient(phaseScope.getScoreDirector()); } private double calculateTimeGradient(InnerScoreDirector<Solution_, ?> scoreDirector) { var scoreCalculationCount = scoreDirector.getCalculationCount(); var timeGradient = scoreCalculationCount / ((double) scoreCalculationCountLimit); return Math.min(timeGradient, 1.0); } @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 UnsupportedOperationException("The childThreadType (%s) is not implemented." .formatted(childThreadType)); } } @Override public String toString() { return "ScoreCalculationCount(" + scoreCalculationCountLimit + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/SolverBridgePhaseTermination.java
package ai.timefold.solver.core.impl.solver.termination; import java.util.Objects; 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; import org.jspecify.annotations.NullMarked; /** * Delegates phase calls (such as {@link #isPhaseTerminated(AbstractPhaseScope)}) * to solver calls (such as {@link SolverTermination#isSolverTerminated(SolverScope)}) * on the bridged termination. * <p> * Had this not happened, * the solver-level termination running at phase-level * would call {@link #isPhaseTerminated(AbstractPhaseScope)} * instead of {@link SolverTermination#isSolverTerminated(SolverScope)}, * and would therefore use the phase start timestamp as its reference, * and not the solver start timestamp. * The effect of this in practice would have been that, * if a solver-level {@link TimeMillisSpentTermination} were configured to terminate after 10 seconds, * each phase would effectively start a new 10-second counter. * * @param <Solution_> */ @NullMarked final class SolverBridgePhaseTermination<Solution_> extends AbstractPhaseTermination<Solution_> implements ChildThreadSupportingTermination<Solution_, SolverScope<Solution_>> { final SolverTermination<Solution_> solverTermination; public SolverBridgePhaseTermination(SolverTermination<Solution_> solverTermination) { this.solverTermination = Objects.requireNonNull(solverTermination); } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) { var terminated = solverTermination.isSolverTerminated(phaseScope.getSolverScope()); // If the solver is not finished yet, we need to check the phase termination if (!terminated && solverTermination instanceof PhaseTermination phaseTermination) { return phaseTermination.isPhaseTerminated(phaseScope); } return terminated; } @Override public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) { return solverTermination.calculateSolverTimeGradient(phaseScope.getSolverScope()); } @Override public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> scope, ChildThreadType childThreadType) { if (childThreadType == ChildThreadType.PART_THREAD) { // This strips the bridge, but the partitioned phase factory will add it back. return ChildThreadSupportingTermination.assertChildThreadSupport(solverTermination) .createChildThreadTermination(scope, childThreadType); } else { throw new UnsupportedOperationException("The childThreadType (%s) is not implemented." .formatted(childThreadType)); } } @Override public String toString() { return "Bridge(" + solverTermination + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/SolverTermination.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.solver.event.SolverLifecycleListener; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import org.jspecify.annotations.NullMarked; /** * Determines when a {@link Solver} should stop. */ @NullMarked public sealed interface SolverTermination<Solution_> extends Termination<Solution_>, SolverLifecycleListener<Solution_> permits MockableSolverTermination, UniversalTermination { /** * Called by the {@link Solver} after every phase to determine if the search should stop. * * @return true if the search should terminate. */ boolean isSolverTerminated(SolverScope<Solution_> solverScope); /** * 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. * * @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); }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/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; import org.jspecify.annotations.NullMarked; @NullMarked final class StepCountTermination<Solution_> extends AbstractPhaseTermination<Solution_> implements ChildThreadSupportingTermination<Solution_, SolverScope<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; } @Override public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) { int nextStepIndex = phaseScope.getNextStepIndex(); return nextStepIndex >= stepCountLimit; } @Override public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) { int nextStepIndex = phaseScope.getNextStepIndex(); double timeGradient = nextStepIndex / ((double) stepCountLimit); return Math.min(timeGradient, 1.0); } @Override public Termination<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/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/Termination.java
package ai.timefold.solver.core.impl.solver.termination; import ai.timefold.solver.core.impl.phase.Phase; import org.jspecify.annotations.NullMarked; /** * Determines when a {@link Phase} should stop. * See {@link SolverTermination} for the termination that also supports stopping the solver. * Many terminations are used at both solver-level and phase-level. */ @NullMarked public sealed interface Termination<Solution_> permits AbstractTermination, PhaseTermination, SolverTermination { }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/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; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked public final 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; } @SuppressWarnings("unchecked") public <Termination_ extends Termination<Solution_>> Termination_ buildTermination(HeuristicConfigPolicy<Solution_> configPolicy, Termination_ chainedTermination) { var termination = buildTermination(configPolicy); if (termination == null) { return chainedTermination; } // This cast works, because composite termination is Universal, // and therefore extends both SolverTermination and PhaseTermination. return (Termination_) new OrCompositeTermination<>(chainedTermination, termination); } /** * @param configPolicy never null * @return sometimes null */ @SuppressWarnings("unchecked") public <Score_ extends Score<Score_>> @Nullable 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)); } var bestScoreFeasible = terminationConfig.getBestScoreFeasible(); if (bestScoreFeasible != null) { ScoreDefinition<Score_> scoreDefinition = configPolicy.getScoreDefinition(); if (!bestScoreFeasible) { throw new IllegalArgumentException("The termination bestScoreFeasible (%s) cannot be false." .formatted(bestScoreFeasible)); } int feasibleLevelsSize = scoreDefinition.getFeasibleLevelsSize(); if (feasibleLevelsSize < 1) { throw new IllegalStateException(""" The termination with bestScoreFeasible (%s) can only be used with a score type \ that has at least 1 feasible level but the scoreDefinition (%s) has feasibleLevelsSize (%s), \ which is less than 1.""" .formatted(bestScoreFeasible, scoreDefinition, feasibleLevelsSize)); } 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())); } if (terminationConfig.getMoveCountLimit() != null) { terminationList.add(new MoveCountTermination<>(terminationConfig.getMoveCountLimit())); } terminationList.addAll(buildInnerTermination(configPolicy)); return buildTerminationFromList(terminationList); } @SuppressWarnings("unchecked") <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."); } if (terminationConfig.getDiminishedReturnsConfig() != null) { var diminishedReturnsConfig = terminationConfig.getDiminishedReturnsConfig(); var gracePeriodMillis = diminishedReturnsConfig.calculateSlidingWindowMilliseconds(); if (gracePeriodMillis == null) { gracePeriodMillis = 30_000L; } var minimumImprovementRatio = diminishedReturnsConfig.getMinimumImprovementRatio(); if (minimumImprovementRatio == null) { minimumImprovementRatio = 0.0001; } terminationList.add(new DiminishedReturnsTermination<>(gracePeriodMillis, minimumImprovementRatio)); } return terminationList; } List<Termination<Solution_>> buildInnerTermination(HeuristicConfigPolicy<Solution_> configPolicy) { var terminationConfigList = terminationConfig.getTerminationConfigList(); if (ConfigUtils.isEmptyCollection(terminationConfigList)) { return Collections.emptyList(); } return terminationConfigList.stream() .map(config -> TerminationFactory.<Solution_> create(config) .buildTermination(configPolicy)) .filter(Objects::nonNull) .collect(Collectors.toList()); } @SuppressWarnings("unchecked") @Nullable Termination<Solution_> buildTerminationFromList(List<Termination<Solution_>> terminationList) { if (terminationList.size() == 1) { return terminationList.get(0); } var terminationArray = terminationList.toArray(new Termination[0]); var compositionStyle = Objects.requireNonNullElse(terminationConfig.getTerminationCompositionStyle(), TerminationCompositionStyle.OR); return switch (compositionStyle) { case AND -> UniversalTermination.and(terminationArray); case OR -> UniversalTermination.or(terminationArray); }; } }
0
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/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; import org.jspecify.annotations.NullMarked; @NullMarked final class TimeMillisSpentTermination<Solution_> extends AbstractUniversalTermination<Solution_> implements ChildThreadSupportingTermination<Solution_, SolverScope<Solution_>> { private final long timeMillisSpentLimit; public TimeMillisSpentTermination(long timeMillisSpentLimit) { this.timeMillisSpentLimit = timeMillisSpentLimit; if (timeMillisSpentLimit < 0L) { throw new IllegalArgumentException("The timeMillisSpentLimit (%d) cannot be negative." .formatted(timeMillisSpentLimit)); } } public long getTimeMillisSpentLimit() { return timeMillisSpentLimit; } @Override public boolean isSolverTerminated(SolverScope<Solution_> solverScope) { var solverTimeMillisSpent = solverScope.calculateTimeMillisSpentUpToNow(); return isTerminated(solverTimeMillisSpent); } @Override public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) { var phaseTimeMillisSpent = phaseScope.calculatePhaseTimeMillisSpentUpToNow(); return isTerminated(phaseTimeMillisSpent); } private boolean isTerminated(long timeMillisSpent) { return timeMillisSpent >= timeMillisSpentLimit; } @Override public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) { var solverTimeMillisSpent = solverScope.calculateTimeMillisSpentUpToNow(); return calculateTimeGradient(solverTimeMillisSpent); } @Override public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) { var phaseTimeMillisSpent = phaseScope.calculatePhaseTimeMillisSpentUpToNow(); return calculateTimeGradient(phaseTimeMillisSpent); } private double calculateTimeGradient(long timeMillisSpent) { var timeGradient = timeMillisSpent / ((double) timeMillisSpentLimit); return Math.min(timeGradient, 1.0); } @Override public Termination<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/1.26.1/ai/timefold/solver/core/impl/solver
java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/solver/termination/UnimprovedStepCountTermination.java
package ai.timefold.solver.core.impl.solver.termination; import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicPhaseScope; import ai.timefold.solver.core.impl.phase.custom.scope.CustomPhaseScope; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import ai.timefold.solver.core.impl.solver.thread.ChildThreadType; import org.jspecify.annotations.NullMarked; @NullMarked final class UnimprovedStepCountTermination<Solution_> extends AbstractPhaseTermination<Solution_> implements ChildThreadSupportingTermination<Solution_, SolverScope<Solution_>> { private final int unimprovedStepCountLimit; public UnimprovedStepCountTermination(int unimprovedStepCountLimit) { this.unimprovedStepCountLimit = unimprovedStepCountLimit; if (unimprovedStepCountLimit < 0) { throw new IllegalArgumentException("The unimprovedStepCountLimit (%d) cannot be negative." .formatted(unimprovedStepCountLimit)); } } @Override public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) { var unimprovedStepCount = calculateUnimprovedStepCount(phaseScope); return unimprovedStepCount >= unimprovedStepCountLimit; } private static int calculateUnimprovedStepCount(AbstractPhaseScope<?> phaseScope) { var bestStepIndex = phaseScope.getBestSolutionStepIndex(); var lastStepIndex = phaseScope.getLastCompletedStepScope().getStepIndex(); return lastStepIndex - bestStepIndex; } @Override public double calculatePhaseTimeGradient(AbstractPhaseScope<Solution_> phaseScope) { var unimprovedStepCount = calculateUnimprovedStepCount(phaseScope); var timeGradient = unimprovedStepCount / ((double) unimprovedStepCountLimit); return Math.min(timeGradient, 1.0); } @Override public Termination<Solution_> createChildThreadTermination(SolverScope<Solution_> solverScope, ChildThreadType childThreadType) { return new UnimprovedStepCountTermination<>(unimprovedStepCountLimit); } @Override public boolean isApplicableTo(Class<? extends AbstractPhaseScope> phaseScopeClass) { return !(phaseScopeClass == ConstructionHeuristicPhaseScope.class || phaseScopeClass == CustomPhaseScope.class); } @Override public String toString() { return "UnimprovedStepCount(" + unimprovedStepCountLimit + ")"; } }