index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/buildin/HardMediumSoftLongScoreDefinition.java
package ai.timefold.solver.core.impl.score.buildin; import java.util.Arrays; import ai.timefold.solver.core.api.score.buildin.hardmediumsoftlong.HardMediumSoftLongScore; import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel; import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition; import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend; public class HardMediumSoftLongScoreDefinition extends AbstractScoreDefinition<HardMediumSoftLongScore> { public HardMediumSoftLongScoreDefinition() { super(new String[] { "hard score", "medium score", "soft score" }); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public int getLevelsSize() { return 3; } @Override public int getFeasibleLevelsSize() { return 1; } @Override public Class<HardMediumSoftLongScore> getScoreClass() { return HardMediumSoftLongScore.class; } @Override public HardMediumSoftLongScore getZeroScore() { return HardMediumSoftLongScore.ZERO; } @Override public HardMediumSoftLongScore getOneSoftestScore() { return HardMediumSoftLongScore.ONE_SOFT; } @Override public HardMediumSoftLongScore parseScore(String scoreString) { return HardMediumSoftLongScore.parseScore(scoreString); } @Override public HardMediumSoftLongScore fromLevelNumbers(int initScore, Number[] levelNumbers) { if (levelNumbers.length != getLevelsSize()) { throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers) + ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ")."); } return HardMediumSoftLongScore.ofUninitialized(initScore, (Long) levelNumbers[0], (Long) levelNumbers[1], (Long) levelNumbers[2]); } @Override public HardMediumSoftLongScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, HardMediumSoftLongScore score) { InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels(); return HardMediumSoftLongScore.ofUninitialized(0, trendLevels[0] == InitializingScoreTrendLevel.ONLY_DOWN ? score.hardScore() : Long.MAX_VALUE, trendLevels[1] == InitializingScoreTrendLevel.ONLY_DOWN ? score.mediumScore() : Long.MAX_VALUE, trendLevels[2] == InitializingScoreTrendLevel.ONLY_DOWN ? score.softScore() : Long.MAX_VALUE); } @Override public HardMediumSoftLongScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, HardMediumSoftLongScore score) { InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels(); return HardMediumSoftLongScore.ofUninitialized(0, trendLevels[0] == InitializingScoreTrendLevel.ONLY_UP ? score.hardScore() : Long.MIN_VALUE, trendLevels[1] == InitializingScoreTrendLevel.ONLY_UP ? score.mediumScore() : Long.MIN_VALUE, trendLevels[2] == InitializingScoreTrendLevel.ONLY_UP ? score.softScore() : Long.MIN_VALUE); } @Override public HardMediumSoftLongScore divideBySanitizedDivisor(HardMediumSoftLongScore dividend, HardMediumSoftLongScore divisor) { int dividendInitScore = dividend.initScore(); int divisorInitScore = sanitize(divisor.initScore()); long dividendHardScore = dividend.hardScore(); long divisorHardScore = sanitize(divisor.hardScore()); long dividendMediumScore = dividend.mediumScore(); long divisorMediumScore = sanitize(divisor.mediumScore()); long dividendSoftScore = dividend.softScore(); long divisorSoftScore = sanitize(divisor.softScore()); return fromLevelNumbers( divide(dividendInitScore, divisorInitScore), new Number[] { divide(dividendHardScore, divisorHardScore), divide(dividendMediumScore, divisorMediumScore), divide(dividendSoftScore, divisorSoftScore) }); } @Override public Class<?> getNumericType() { return long.class; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/buildin/HardMediumSoftScoreDefinition.java
package ai.timefold.solver.core.impl.score.buildin; import java.util.Arrays; import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore; import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel; import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition; import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend; public class HardMediumSoftScoreDefinition extends AbstractScoreDefinition<HardMediumSoftScore> { public HardMediumSoftScoreDefinition() { super(new String[] { "hard score", "medium score", "soft score" }); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public int getLevelsSize() { return 3; } @Override public int getFeasibleLevelsSize() { return 1; } @Override public Class<HardMediumSoftScore> getScoreClass() { return HardMediumSoftScore.class; } @Override public HardMediumSoftScore getZeroScore() { return HardMediumSoftScore.ZERO; } @Override public HardMediumSoftScore getOneSoftestScore() { return HardMediumSoftScore.ONE_SOFT; } @Override public HardMediumSoftScore parseScore(String scoreString) { return HardMediumSoftScore.parseScore(scoreString); } @Override public HardMediumSoftScore fromLevelNumbers(int initScore, Number[] levelNumbers) { if (levelNumbers.length != getLevelsSize()) { throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers) + ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ")."); } return HardMediumSoftScore.ofUninitialized(initScore, (Integer) levelNumbers[0], (Integer) levelNumbers[1], (Integer) levelNumbers[2]); } @Override public HardMediumSoftScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, HardMediumSoftScore score) { InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels(); return HardMediumSoftScore.ofUninitialized(0, trendLevels[0] == InitializingScoreTrendLevel.ONLY_DOWN ? score.hardScore() : Integer.MAX_VALUE, trendLevels[1] == InitializingScoreTrendLevel.ONLY_DOWN ? score.mediumScore() : Integer.MAX_VALUE, trendLevels[2] == InitializingScoreTrendLevel.ONLY_DOWN ? score.softScore() : Integer.MAX_VALUE); } @Override public HardMediumSoftScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, HardMediumSoftScore score) { InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels(); return HardMediumSoftScore.ofUninitialized(0, trendLevels[0] == InitializingScoreTrendLevel.ONLY_UP ? score.hardScore() : Integer.MIN_VALUE, trendLevels[1] == InitializingScoreTrendLevel.ONLY_UP ? score.mediumScore() : Integer.MIN_VALUE, trendLevels[2] == InitializingScoreTrendLevel.ONLY_UP ? score.softScore() : Integer.MIN_VALUE); } @Override public HardMediumSoftScore divideBySanitizedDivisor(HardMediumSoftScore dividend, HardMediumSoftScore divisor) { int dividendInitScore = dividend.initScore(); int divisorInitScore = sanitize(divisor.initScore()); int dividendHardScore = dividend.hardScore(); int divisorHardScore = sanitize(divisor.hardScore()); int dividendMediumScore = dividend.mediumScore(); int divisorMediumScore = sanitize(divisor.mediumScore()); int dividendSoftScore = dividend.softScore(); int divisorSoftScore = sanitize(divisor.softScore()); return fromLevelNumbers( divide(dividendInitScore, divisorInitScore), new Number[] { divide(dividendHardScore, divisorHardScore), divide(dividendMediumScore, divisorMediumScore), divide(dividendSoftScore, divisorSoftScore) }); } @Override public Class<?> getNumericType() { return int.class; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/buildin/HardSoftBigDecimalScoreDefinition.java
package ai.timefold.solver.core.impl.score.buildin; import java.math.BigDecimal; import java.util.Arrays; import ai.timefold.solver.core.api.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScore; import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition; import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend; public class HardSoftBigDecimalScoreDefinition extends AbstractScoreDefinition<HardSoftBigDecimalScore> { public HardSoftBigDecimalScoreDefinition() { super(new String[] { "hard score", "soft score" }); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public int getLevelsSize() { return 2; } @Override public int getFeasibleLevelsSize() { return 1; } @Override public Class<HardSoftBigDecimalScore> getScoreClass() { return HardSoftBigDecimalScore.class; } @Override public HardSoftBigDecimalScore getZeroScore() { return HardSoftBigDecimalScore.ZERO; } @Override public HardSoftBigDecimalScore getOneSoftestScore() { return HardSoftBigDecimalScore.ONE_SOFT; } @Override public HardSoftBigDecimalScore parseScore(String scoreString) { return HardSoftBigDecimalScore.parseScore(scoreString); } @Override public HardSoftBigDecimalScore fromLevelNumbers(int initScore, Number[] levelNumbers) { if (levelNumbers.length != getLevelsSize()) { throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers) + ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ")."); } return HardSoftBigDecimalScore.ofUninitialized(initScore, (BigDecimal) levelNumbers[0], (BigDecimal) levelNumbers[1]); } @Override public HardSoftBigDecimalScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, HardSoftBigDecimalScore score) { // TODO https://issues.redhat.com/browse/PLANNER-232 throw new UnsupportedOperationException("PLANNER-232: BigDecimalScore does not support bounds" + " because a BigDecimal cannot represent infinity."); } @Override public HardSoftBigDecimalScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, HardSoftBigDecimalScore score) { // TODO https://issues.redhat.com/browse/PLANNER-232 throw new UnsupportedOperationException("PLANNER-232: BigDecimalScore does not support bounds" + " because a BigDecimal cannot represent infinity."); } @Override public HardSoftBigDecimalScore divideBySanitizedDivisor(HardSoftBigDecimalScore dividend, HardSoftBigDecimalScore divisor) { int dividendInitScore = dividend.initScore(); int divisorInitScore = sanitize(divisor.initScore()); BigDecimal dividendHardScore = dividend.hardScore(); BigDecimal divisorHardScore = sanitize(divisor.hardScore()); BigDecimal dividendSoftScore = dividend.softScore(); BigDecimal divisorSoftScore = sanitize(divisor.softScore()); return fromLevelNumbers( divide(dividendInitScore, divisorInitScore), new Number[] { divide(dividendHardScore, divisorHardScore), divide(dividendSoftScore, divisorSoftScore) }); } @Override public Class<?> getNumericType() { return BigDecimal.class; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/buildin/HardSoftLongScoreDefinition.java
package ai.timefold.solver.core.impl.score.buildin; import java.util.Arrays; import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore; import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel; import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition; import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend; public class HardSoftLongScoreDefinition extends AbstractScoreDefinition<HardSoftLongScore> { public HardSoftLongScoreDefinition() { super(new String[] { "hard score", "soft score" }); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public int getLevelsSize() { return 2; } @Override public int getFeasibleLevelsSize() { return 1; } @Override public Class<HardSoftLongScore> getScoreClass() { return HardSoftLongScore.class; } @Override public HardSoftLongScore getZeroScore() { return HardSoftLongScore.ZERO; } @Override public HardSoftLongScore getOneSoftestScore() { return HardSoftLongScore.ONE_SOFT; } @Override public HardSoftLongScore parseScore(String scoreString) { return HardSoftLongScore.parseScore(scoreString); } @Override public HardSoftLongScore fromLevelNumbers(int initScore, Number[] levelNumbers) { if (levelNumbers.length != getLevelsSize()) { throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers) + ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ")."); } return HardSoftLongScore.ofUninitialized(initScore, (Long) levelNumbers[0], (Long) levelNumbers[1]); } @Override public HardSoftLongScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, HardSoftLongScore score) { InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels(); return HardSoftLongScore.ofUninitialized(0, trendLevels[0] == InitializingScoreTrendLevel.ONLY_DOWN ? score.hardScore() : Long.MAX_VALUE, trendLevels[1] == InitializingScoreTrendLevel.ONLY_DOWN ? score.softScore() : Long.MAX_VALUE); } @Override public HardSoftLongScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, HardSoftLongScore score) { InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels(); return HardSoftLongScore.ofUninitialized(0, trendLevels[0] == InitializingScoreTrendLevel.ONLY_UP ? score.hardScore() : Long.MIN_VALUE, trendLevels[1] == InitializingScoreTrendLevel.ONLY_UP ? score.softScore() : Long.MIN_VALUE); } @Override public HardSoftLongScore divideBySanitizedDivisor(HardSoftLongScore dividend, HardSoftLongScore divisor) { int dividendInitScore = dividend.initScore(); int divisorInitScore = sanitize(divisor.initScore()); long dividendHardScore = dividend.hardScore(); long divisorHardScore = sanitize(divisor.hardScore()); long dividendSoftScore = dividend.softScore(); long divisorSoftScore = sanitize(divisor.softScore()); return fromLevelNumbers( divide(dividendInitScore, divisorInitScore), new Number[] { divide(dividendHardScore, divisorHardScore), divide(dividendSoftScore, divisorSoftScore) }); } @Override public Class<?> getNumericType() { return long.class; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/buildin/HardSoftScoreDefinition.java
package ai.timefold.solver.core.impl.score.buildin; import java.util.Arrays; import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel; import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition; import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend; public class HardSoftScoreDefinition extends AbstractScoreDefinition<HardSoftScore> { public HardSoftScoreDefinition() { super(new String[] { "hard score", "soft score" }); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public int getFeasibleLevelsSize() { return 1; } @Override public Class<HardSoftScore> getScoreClass() { return HardSoftScore.class; } @Override public HardSoftScore getZeroScore() { return HardSoftScore.ZERO; } @Override public HardSoftScore getOneSoftestScore() { return HardSoftScore.ONE_SOFT; } @Override public HardSoftScore parseScore(String scoreString) { return HardSoftScore.parseScore(scoreString); } @Override public HardSoftScore fromLevelNumbers(int initScore, Number[] levelNumbers) { if (levelNumbers.length != getLevelsSize()) { throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers) + ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ")."); } return HardSoftScore.ofUninitialized(initScore, (Integer) levelNumbers[0], (Integer) levelNumbers[1]); } @Override public HardSoftScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, HardSoftScore score) { InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels(); return HardSoftScore.ofUninitialized(0, trendLevels[0] == InitializingScoreTrendLevel.ONLY_DOWN ? score.hardScore() : Integer.MAX_VALUE, trendLevels[1] == InitializingScoreTrendLevel.ONLY_DOWN ? score.softScore() : Integer.MAX_VALUE); } @Override public HardSoftScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, HardSoftScore score) { InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels(); return HardSoftScore.ofUninitialized(0, trendLevels[0] == InitializingScoreTrendLevel.ONLY_UP ? score.hardScore() : Integer.MIN_VALUE, trendLevels[1] == InitializingScoreTrendLevel.ONLY_UP ? score.softScore() : Integer.MIN_VALUE); } @Override public HardSoftScore divideBySanitizedDivisor(HardSoftScore dividend, HardSoftScore divisor) { int dividendInitScore = dividend.initScore(); int divisorInitScore = sanitize(divisor.initScore()); int dividendHardScore = dividend.hardScore(); int divisorHardScore = sanitize(divisor.hardScore()); int dividendSoftScore = dividend.softScore(); int divisorSoftScore = sanitize(divisor.softScore()); return fromLevelNumbers( divide(dividendInitScore, divisorInitScore), new Number[] { divide(dividendHardScore, divisorHardScore), divide(dividendSoftScore, divisorSoftScore) }); } @Override public Class<?> getNumericType() { return int.class; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/buildin/SimpleBigDecimalScoreDefinition.java
package ai.timefold.solver.core.impl.score.buildin; import java.math.BigDecimal; import java.util.Arrays; import ai.timefold.solver.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore; import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition; import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend; public class SimpleBigDecimalScoreDefinition extends AbstractScoreDefinition<SimpleBigDecimalScore> { public SimpleBigDecimalScoreDefinition() { super(new String[] { "score" }); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public int getLevelsSize() { return 1; } @Override public int getFeasibleLevelsSize() { return 0; } @Override public Class<SimpleBigDecimalScore> getScoreClass() { return SimpleBigDecimalScore.class; } @Override public SimpleBigDecimalScore getZeroScore() { return SimpleBigDecimalScore.ZERO; } @Override public SimpleBigDecimalScore getOneSoftestScore() { return SimpleBigDecimalScore.ONE; } @Override public SimpleBigDecimalScore parseScore(String scoreString) { return SimpleBigDecimalScore.parseScore(scoreString); } @Override public SimpleBigDecimalScore fromLevelNumbers(int initScore, Number[] levelNumbers) { if (levelNumbers.length != getLevelsSize()) { throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers) + ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ")."); } return SimpleBigDecimalScore.ofUninitialized(initScore, (BigDecimal) levelNumbers[0]); } @Override public SimpleBigDecimalScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, SimpleBigDecimalScore score) { // TODO https://issues.redhat.com/browse/PLANNER-232 throw new UnsupportedOperationException("PLANNER-232: BigDecimalScore does not support bounds" + " because a BigDecimal cannot represent infinity."); } @Override public SimpleBigDecimalScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, SimpleBigDecimalScore score) { // TODO https://issues.redhat.com/browse/PLANNER-232 throw new UnsupportedOperationException("PLANNER-232: BigDecimalScore does not support bounds" + " because a BigDecimal cannot represent infinity."); } @Override public SimpleBigDecimalScore divideBySanitizedDivisor(SimpleBigDecimalScore dividend, SimpleBigDecimalScore divisor) { int dividendInitScore = dividend.initScore(); int divisorInitScore = sanitize(divisor.initScore()); BigDecimal dividendScore = dividend.score(); BigDecimal divisorScore = sanitize(divisor.score()); return fromLevelNumbers( divide(dividendInitScore, divisorInitScore), new Number[] { divide(dividendScore, divisorScore) }); } @Override public Class<?> getNumericType() { return BigDecimal.class; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/buildin/SimpleLongScoreDefinition.java
package ai.timefold.solver.core.impl.score.buildin; import java.util.Arrays; import ai.timefold.solver.core.api.score.buildin.simplelong.SimpleLongScore; import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel; import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition; import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend; public class SimpleLongScoreDefinition extends AbstractScoreDefinition<SimpleLongScore> { public SimpleLongScoreDefinition() { super(new String[] { "score" }); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public int getFeasibleLevelsSize() { return 0; } @Override public Class<SimpleLongScore> getScoreClass() { return SimpleLongScore.class; } @Override public SimpleLongScore getZeroScore() { return SimpleLongScore.ZERO; } @Override public SimpleLongScore getOneSoftestScore() { return SimpleLongScore.ONE; } @Override public SimpleLongScore parseScore(String scoreString) { return SimpleLongScore.parseScore(scoreString); } @Override public SimpleLongScore fromLevelNumbers(int initScore, Number[] levelNumbers) { if (levelNumbers.length != getLevelsSize()) { throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers) + ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ")."); } return SimpleLongScore.ofUninitialized(initScore, (Long) levelNumbers[0]); } @Override public SimpleLongScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, SimpleLongScore score) { InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels(); return SimpleLongScore.ofUninitialized(0, trendLevels[0] == InitializingScoreTrendLevel.ONLY_DOWN ? score.score() : Long.MAX_VALUE); } @Override public SimpleLongScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, SimpleLongScore score) { InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels(); return SimpleLongScore.ofUninitialized(0, trendLevels[0] == InitializingScoreTrendLevel.ONLY_UP ? score.score() : Long.MIN_VALUE); } @Override public SimpleLongScore divideBySanitizedDivisor(SimpleLongScore dividend, SimpleLongScore divisor) { int dividendInitScore = dividend.initScore(); int divisorInitScore = sanitize(divisor.initScore()); long dividendScore = dividend.score(); long divisorScore = sanitize(divisor.score()); return fromLevelNumbers( divide(dividendInitScore, divisorInitScore), new Number[] { divide(dividendScore, divisorScore) }); } @Override public Class<?> getNumericType() { return long.class; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/buildin/SimpleScoreDefinition.java
package ai.timefold.solver.core.impl.score.buildin; import java.util.Arrays; import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore; import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel; import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition; import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend; public class SimpleScoreDefinition extends AbstractScoreDefinition<SimpleScore> { public SimpleScoreDefinition() { super(new String[] { "score" }); } // ************************************************************************ // Worker methods // ************************************************************************ @Override public int getLevelsSize() { return 1; } @Override public int getFeasibleLevelsSize() { return 0; } @Override public Class<SimpleScore> getScoreClass() { return SimpleScore.class; } @Override public SimpleScore getZeroScore() { return SimpleScore.ZERO; } @Override public SimpleScore getOneSoftestScore() { return SimpleScore.ONE; } @Override public SimpleScore parseScore(String scoreString) { return SimpleScore.parseScore(scoreString); } @Override public SimpleScore fromLevelNumbers(int initScore, Number[] levelNumbers) { if (levelNumbers.length != getLevelsSize()) { throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers) + ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ")."); } return SimpleScore.ofUninitialized(initScore, (Integer) levelNumbers[0]); } @Override public SimpleScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, SimpleScore score) { InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels(); return SimpleScore.ofUninitialized(0, trendLevels[0] == InitializingScoreTrendLevel.ONLY_DOWN ? score.score() : Integer.MAX_VALUE); } @Override public SimpleScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, SimpleScore score) { InitializingScoreTrendLevel[] trendLevels = initializingScoreTrend.getTrendLevels(); return SimpleScore.ofUninitialized(0, trendLevels[0] == InitializingScoreTrendLevel.ONLY_UP ? score.score() : Integer.MIN_VALUE); } @Override public SimpleScore divideBySanitizedDivisor(SimpleScore dividend, SimpleScore divisor) { int dividendInitScore = dividend.initScore(); int divisorInitScore = sanitize(divisor.initScore()); int dividendScore = dividend.score(); int divisorScore = sanitize(divisor.score()); return fromLevelNumbers( divide(dividendInitScore, divisorInitScore), new Number[] { divide(dividendScore, divisorScore) }); } @Override public Class<?> getNumericType() { return int.class; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/constraint/DefaultConstraintMatchTotal.java
package ai.timefold.solver.core.impl.score.constraint; import static java.util.Objects.requireNonNull; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.constraint.ConstraintMatch; import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal; import ai.timefold.solver.core.api.score.constraint.ConstraintRef; import ai.timefold.solver.core.api.score.stream.Constraint; import ai.timefold.solver.core.api.score.stream.ConstraintJustification; import ai.timefold.solver.core.api.score.stream.DefaultConstraintJustification; import ai.timefold.solver.core.api.solver.SolutionManager; /** * If possible, prefer using {@link SolutionManager#analyze(Object)} instead. * * @param <Score_> */ public final class DefaultConstraintMatchTotal<Score_ extends Score<Score_>> implements ConstraintMatchTotal<Score_>, Comparable<DefaultConstraintMatchTotal<Score_>> { private final ConstraintRef constraintRef; private final Score_ constraintWeight; private final Set<ConstraintMatch<Score_>> constraintMatchSet = new LinkedHashSet<>(); private Score_ score; /** * @deprecated Prefer {@link #DefaultConstraintMatchTotal(ConstraintRef, Score_)}. */ @Deprecated(forRemoval = true, since = "1.4.0") public DefaultConstraintMatchTotal(String constraintPackage, String constraintName) { this(ConstraintRef.of(constraintPackage, constraintName)); } /** * * @deprecated Prefer {@link #DefaultConstraintMatchTotal(ConstraintRef, Score_)}. */ @Deprecated(forRemoval = true, since = "1.5.0") public DefaultConstraintMatchTotal(ConstraintRef constraintRef) { this.constraintRef = requireNonNull(constraintRef); this.constraintWeight = null; } /** * @deprecated Prefer {@link #DefaultConstraintMatchTotal(ConstraintRef, Score_)}. */ @Deprecated(forRemoval = true, since = "1.4.0") public DefaultConstraintMatchTotal(Constraint constraint, Score_ constraintWeight) { this(constraint.getConstraintRef(), constraintWeight); } /** * @deprecated Prefer {@link #DefaultConstraintMatchTotal(ConstraintRef, Score_)}. */ @Deprecated(forRemoval = true, since = "1.4.0") public DefaultConstraintMatchTotal(String constraintPackage, String constraintName, Score_ constraintWeight) { this(ConstraintRef.of(constraintPackage, constraintName), constraintWeight); } public DefaultConstraintMatchTotal(ConstraintRef constraintRef, Score_ constraintWeight) { this.constraintRef = requireNonNull(constraintRef); this.constraintWeight = requireNonNull(constraintWeight); this.score = constraintWeight.zero(); } @Override public ConstraintRef getConstraintRef() { return constraintRef; } @Override public Score_ getConstraintWeight() { return constraintWeight; } @Override public Set<ConstraintMatch<Score_>> getConstraintMatchSet() { return constraintMatchSet; } @Override public Score_ getScore() { return score; } // ************************************************************************ // Worker methods // ************************************************************************ /** * Creates a {@link ConstraintMatch} and adds it to the collection returned by {@link #getConstraintMatchSet()}. * It will use {@link DefaultConstraintJustification}, * whose {@link DefaultConstraintJustification#getFacts()} method will return the given list of justifications. * Additionally, the constraint match will indict the objects in the given list of justifications. * * @param justifications never null, never empty * @param score never null * @return never null */ public ConstraintMatch<Score_> addConstraintMatch(List<Object> justifications, Score_ score) { return addConstraintMatch(DefaultConstraintJustification.of(score, justifications), justifications, score); } /** * Creates a {@link ConstraintMatch} and adds it to the collection returned by {@link #getConstraintMatchSet()}. * It will be justified with the provided {@link ConstraintJustification}. * Additionally, the constraint match will indict the objects in the given list of indicted objects. * * @param indictedObjects never null, may be empty * @param score never null * @return never null */ public ConstraintMatch<Score_> addConstraintMatch(ConstraintJustification justification, Collection<Object> indictedObjects, Score_ score) { ConstraintMatch<Score_> constraintMatch = new ConstraintMatch<>(constraintRef, justification, indictedObjects, score); addConstraintMatch(constraintMatch); return constraintMatch; } public void addConstraintMatch(ConstraintMatch<Score_> constraintMatch) { Score_ constraintMatchScore = constraintMatch.getScore(); this.score = this.score == null ? constraintMatchScore : this.score.add(constraintMatchScore); constraintMatchSet.add(constraintMatch); } public void removeConstraintMatch(ConstraintMatch<Score_> constraintMatch) { score = score.subtract(constraintMatch.getScore()); boolean removed = constraintMatchSet.remove(constraintMatch); if (!removed) { throw new IllegalStateException("The constraintMatchTotal (" + this + ") could not remove constraintMatch (" + constraintMatch + ") from its constraintMatchSet (" + constraintMatchSet + ")."); } } // ************************************************************************ // Infrastructure methods // ************************************************************************ @Override public int compareTo(DefaultConstraintMatchTotal<Score_> other) { return constraintRef.compareTo(other.constraintRef); } @Override public boolean equals(Object o) { if (o instanceof DefaultConstraintMatchTotal<?> other) { return constraintRef.equals(other.constraintRef); } return false; } @Override public int hashCode() { return constraintRef.hashCode(); } @Override public String toString() { return constraintRef + "=" + score; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/constraint/DefaultIndictment.java
package ai.timefold.solver.core.impl.score.constraint; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.constraint.ConstraintMatch; import ai.timefold.solver.core.api.score.constraint.Indictment; import ai.timefold.solver.core.api.score.stream.ConstraintJustification; import ai.timefold.solver.core.impl.util.CollectionUtils; public final class DefaultIndictment<Score_ extends Score<Score_>> implements Indictment<Score_> { private final Object indictedObject; private final Set<ConstraintMatch<Score_>> constraintMatchSet = new LinkedHashSet<>(); private List<ConstraintJustification> constraintJustificationList; private Score_ score; public DefaultIndictment(Object indictedObject, Score_ zeroScore) { this.indictedObject = indictedObject; this.score = zeroScore; } @Override public <IndictedObject_> IndictedObject_ getIndictedObject() { return (IndictedObject_) indictedObject; } @Override public Set<ConstraintMatch<Score_>> getConstraintMatchSet() { return constraintMatchSet; } @Override public List<ConstraintJustification> getJustificationList() { if (constraintJustificationList == null) { constraintJustificationList = buildConstraintJustificationList(); } return constraintJustificationList; } private List<ConstraintJustification> buildConstraintJustificationList() { var constraintMatchSetSize = constraintMatchSet.size(); switch (constraintMatchSetSize) { case 0 -> { return Collections.emptyList(); } case 1 -> { return Collections.singletonList(constraintMatchSet.iterator().next().getJustification()); } default -> { Set<ConstraintJustification> justificationSet = CollectionUtils.newLinkedHashSet(constraintMatchSetSize); for (ConstraintMatch<Score_> constraintMatch : constraintMatchSet) { justificationSet.add(constraintMatch.getJustification()); } return CollectionUtils.toDistinctList(justificationSet); } } } @Override public Score_ getScore() { return score; } // ************************************************************************ // Worker methods // ************************************************************************ public void addConstraintMatch(ConstraintMatch<Score_> constraintMatch) { boolean added = addConstraintMatchWithoutFail(constraintMatch); if (!added) { throw new IllegalStateException("The indictment (" + this + ") could not add constraintMatch (" + constraintMatch + ") to its constraintMatchSet (" + constraintMatchSet + ")."); } } public boolean addConstraintMatchWithoutFail(ConstraintMatch<Score_> constraintMatch) { boolean added = constraintMatchSet.add(constraintMatch); if (added) { score = score.add(constraintMatch.getScore()); constraintJustificationList = null; // Rebuild later. } return added; } public void removeConstraintMatch(ConstraintMatch<Score_> constraintMatch) { score = score.subtract(constraintMatch.getScore()); boolean removed = constraintMatchSet.remove(constraintMatch); if (!removed) { throw new IllegalStateException("The indictment (" + this + ") could not remove constraintMatch (" + constraintMatch + ") from its constraintMatchSet (" + constraintMatchSet + ")."); } constraintJustificationList = null; // Rebuild later. } // ************************************************************************ // Infrastructure methods // ************************************************************************ @Override public boolean equals(Object o) { if (o instanceof DefaultIndictment other) { return indictedObject.equals(other.indictedObject); } return false; } @Override public int hashCode() { return indictedObject.hashCode(); } @Override public String toString() { return indictedObject + "=" + score; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/definition/AbstractBendableScoreDefinition.java
package ai.timefold.solver.core.impl.score.definition; import ai.timefold.solver.core.api.score.IBendableScore; import ai.timefold.solver.core.api.score.Score; public abstract class AbstractBendableScoreDefinition<Score_ extends Score<Score_>> extends AbstractScoreDefinition<Score_> implements ScoreDefinition<Score_> { protected static String[] generateLevelLabels(int hardLevelsSize, int softLevelsSize) { if (hardLevelsSize < 0 || softLevelsSize < 0) { throw new IllegalArgumentException("The hardLevelsSize (" + hardLevelsSize + ") and softLevelsSize (" + softLevelsSize + ") should be positive."); } String[] levelLabels = new String[hardLevelsSize + softLevelsSize]; for (int i = 0; i < levelLabels.length; i++) { String labelPrefix; if (i < hardLevelsSize) { labelPrefix = "hard " + i; } else { labelPrefix = "soft " + (i - hardLevelsSize); } levelLabels[i] = labelPrefix + " score"; } return levelLabels; } protected final int hardLevelsSize; protected final int softLevelsSize; public AbstractBendableScoreDefinition(int hardLevelsSize, int softLevelsSize) { super(generateLevelLabels(hardLevelsSize, softLevelsSize)); this.hardLevelsSize = hardLevelsSize; this.softLevelsSize = softLevelsSize; } public int getHardLevelsSize() { return hardLevelsSize; } public int getSoftLevelsSize() { return softLevelsSize; } // ************************************************************************ // Worker methods // ************************************************************************ @Override public int getLevelsSize() { return hardLevelsSize + softLevelsSize; } @Override public int getFeasibleLevelsSize() { return hardLevelsSize; } @Override public boolean isCompatibleArithmeticArgument(Score score) { if (super.isCompatibleArithmeticArgument(score)) { IBendableScore<?> bendableScore = (IBendableScore<?>) score; return getLevelsSize() == bendableScore.levelsSize() && getHardLevelsSize() == bendableScore.hardLevelsSize() && getSoftLevelsSize() == bendableScore.softLevelsSize(); } return false; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/definition/AbstractScoreDefinition.java
package ai.timefold.solver.core.impl.score.definition; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Objects; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.score.buildin.HardSoftScoreDefinition; /** * Abstract superclass for {@link ScoreDefinition}. * * @see ScoreDefinition * @see HardSoftScoreDefinition */ public abstract class AbstractScoreDefinition<Score_ extends Score<Score_>> implements ScoreDefinition<Score_> { private final String[] levelLabels; protected static int sanitize(int number) { return number == 0 ? 1 : number; } protected static long sanitize(long number) { return number == 0L ? 1L : number; } protected static BigDecimal sanitize(BigDecimal number) { return number.signum() == 0 ? BigDecimal.ONE : number; } protected static int divide(int dividend, int divisor) { return (int) Math.floor(divide(dividend, (double) divisor)); } protected static long divide(long dividend, long divisor) { return (long) Math.floor(divide(dividend, (double) divisor)); } protected static double divide(double dividend, double divisor) { return dividend / divisor; } protected static BigDecimal divide(BigDecimal dividend, BigDecimal divisor) { return dividend.divide(divisor, dividend.scale() - divisor.scale(), RoundingMode.FLOOR); } /** * @param levelLabels never null, as defined by {@link ScoreDefinition#getLevelLabels()} */ public AbstractScoreDefinition(String[] levelLabels) { this.levelLabels = levelLabels; } @Override public String getInitLabel() { return "init score"; } @Override public int getLevelsSize() { return levelLabels.length; } @Override public String[] getLevelLabels() { return levelLabels; } @Override public String formatScore(Score_ score) { return score.toString(); } @Override public boolean isCompatibleArithmeticArgument(Score score) { return Objects.equals(score.getClass(), getScoreClass()); } @Override public String toString() { return getClass().getSimpleName(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/definition/ScoreDefinition.java
package ai.timefold.solver.core.impl.score.definition; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore; import ai.timefold.solver.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore; import ai.timefold.solver.core.impl.score.buildin.HardSoftScoreDefinition; import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend; /** * A ScoreDefinition knows how to compare {@link Score}s and what the perfect maximum/minimum {@link Score} is. * * @see AbstractScoreDefinition * @see HardSoftScoreDefinition * @param <Score_> the {@link Score} type */ public interface ScoreDefinition<Score_ extends Score<Score_>> { /** * Returns the label for {@link Score#initScore()}. * * @return never null * @see #getLevelLabels() */ String getInitLabel(); /** * Returns the length of {@link Score#toLevelNumbers()} for every {@link Score} of this definition. * For example: returns 2 on {@link HardSoftScoreDefinition}. * * @return at least 1 */ int getLevelsSize(); /** * Returns the number of levels of {@link Score#toLevelNumbers()}. * that are used to determine {@link Score#isFeasible()}. * * @return at least 0, at most {@link #getLevelsSize()} */ int getFeasibleLevelsSize(); /** * Returns a label for each score level. Each label includes the suffix "score" and must start in lower case. * For example: returns {@code {"hard score", "soft score "}} on {@link HardSoftScoreDefinition}. * <p> * It does not include the {@link #getInitLabel()}. * * @return never null, array with length of {@link #getLevelsSize()}, each element is never null */ String[] getLevelLabels(); /** * Returns the {@link Class} of the actual {@link Score} implementation. * For example: returns {@link HardSoftScore HardSoftScore.class} on {@link HardSoftScoreDefinition}. * * @return never null */ Class<Score_> getScoreClass(); /** * The score that represents zero. * * @return never null */ Score_ getZeroScore(); /** * The score that represents the softest possible one. * * @return never null */ Score_ getOneSoftestScore(); /** * @param score never null * @return true if the score is higher or equal to {@link #getZeroScore()} */ default boolean isPositiveOrZero(Score_ score) { return score.compareTo(getZeroScore()) >= 0; } /** * @param score never null * @return true if the score is lower or equal to {@link #getZeroScore()} */ default boolean isNegativeOrZero(Score_ score) { return score.compareTo(getZeroScore()) <= 0; } /** * Returns a {@link String} representation of the {@link Score}. * * @param score never null * @return never null * @see #parseScore(String) */ String formatScore(Score_ score); /** * Parses the {@link String} and returns a {@link Score}. * * @param scoreString never null * @return never null * @see #formatScore(Score) */ Score_ parseScore(String scoreString); /** * The opposite of {@link Score#toLevelNumbers()}. * * @param initScore {@code <= 0}, managed by Timefold, needed as a parameter in the {@link Score}'s creation * method, see {@link Score#initScore()} * @param levelNumbers never null * @return never null */ Score_ fromLevelNumbers(int initScore, Number[] levelNumbers); /** * Builds a {@link Score} which is equal or better than any other {@link Score} with more variables initialized * (while the already variables don't change). * * @param initializingScoreTrend never null, with {@link InitializingScoreTrend#getLevelsSize()} * equal to {@link #getLevelsSize()}. * @param score never null, with {@link Score#initScore()} {@code 0}. * @return never null */ Score_ buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, Score_ score); /** * Builds a {@link Score} which is equal or worse than any other {@link Score} with more variables initialized * (while the already variables don't change). * * @param initializingScoreTrend never null, with {@link InitializingScoreTrend#getLevelsSize()} * equal to {@link #getLevelsSize()}. * @param score never null, with {@link Score#initScore()} {@code 0} * @return never null */ Score_ buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, Score_ score); /** * Return {@link Score} whose every level is the result of dividing the matching levels in this and the divisor. * When rounding is needed, it is floored (as defined by {@link Math#floor(double)}). * <p> * If any of the levels in the divisor are equal to zero, the method behaves as if they were equal to one instead. * * @param divisor value by which this Score is to be divided * @return this / divisor */ Score_ divideBySanitizedDivisor(Score_ dividend, Score_ divisor); /** * @param score never null * @return true if the otherScore is accepted as a parameter of {@link Score#add(Score)}, * {@link Score#subtract(Score)} and {@link Score#compareTo(Object)} for scores of this score definition. */ boolean isCompatibleArithmeticArgument(Score score); /** * Return the type of number that the score implementation operates on. * Examples: * <ul> * <li>int.class for {@link SimpleScore}</li> * <li>BigDecimal.class for {@link SimpleBigDecimalScore}</li> * </ul> * * @return never null */ Class<?> getNumericType(); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director/AbstractScoreDirector.java
package ai.timefold.solver.core.impl.score.director; import static java.util.Objects.requireNonNull; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Consumer; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner; import ai.timefold.solver.core.api.domain.variable.VariableListener; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.analysis.MatchAnalysis; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.api.solver.change.ProblemChange; import ai.timefold.solver.core.api.solver.change.ProblemChangeDirector; import ai.timefold.solver.core.config.solver.EnvironmentMode; import ai.timefold.solver.core.impl.domain.constraintweight.descriptor.ConstraintConfigurationDescriptor; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.lookup.LookUpManager; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.listener.support.VariableListenerSupport; import ai.timefold.solver.core.impl.domain.variable.listener.support.violation.SolutionTracker; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import ai.timefold.solver.core.impl.solver.exception.UndoScoreCorruptionException; import ai.timefold.solver.core.impl.solver.thread.ChildThreadType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Abstract superclass for {@link ScoreDirector}. * <p> * Implementation note: Extending classes should follow these guidelines: * <ul> * <li>before* method: last statement should be a call to the super method</li> * <li>after* method: first statement should be a call to the super method</li> * </ul> * * @see ScoreDirector */ public abstract class AbstractScoreDirector<Solution_, Score_ extends Score<Score_>, Factory_ extends AbstractScoreDirectorFactory<Solution_, Score_>> implements InnerScoreDirector<Solution_, Score_>, Cloneable { private static final int CONSTRAINT_MATCH_DISPLAY_LIMIT = 8; protected final transient Logger logger = LoggerFactory.getLogger(getClass()); private final boolean lookUpEnabled; private final LookUpManager lookUpManager; private final boolean expectShadowVariablesInCorrectState; protected final Factory_ scoreDirectorFactory; private final VariableDescriptorCache<Solution_> variableDescriptorCache; protected final VariableListenerSupport<Solution_> variableListenerSupport; /** * The first dimension is the entity descriptor ordinal. * The second dimension is the ordinal of list variable descriptor in that entity. * This is a performance optimization which helps avoid requesting a new supply in before/after methods, * and avoids hash lookups which would be used by the map that otherwise would have been used for this. */ protected final ListVariableStateSupply<Solution_>[][] listVariableDataSupplies; protected final boolean constraintMatchEnabledPreference; private long workingEntityListRevision = 0L; private int workingGenuineEntityCount = 0; private boolean allChangesWillBeUndoneBeforeStepEnds = false; private long calculationCount = 0L; protected Solution_ workingSolution; private int workingInitScore = 0; private String undoMoveText; // Null when tracking disabled private final boolean trackingWorkingSolution; private final SolutionTracker<Solution_> solutionTracker; protected AbstractScoreDirector(Factory_ scoreDirectorFactory, boolean lookUpEnabled, boolean constraintMatchEnabledPreference, boolean expectShadowVariablesInCorrectState) { var solutionDescriptor = scoreDirectorFactory.getSolutionDescriptor(); this.lookUpEnabled = lookUpEnabled; this.lookUpManager = lookUpEnabled ? new LookUpManager(solutionDescriptor.getLookUpStrategyResolver()) : null; this.expectShadowVariablesInCorrectState = expectShadowVariablesInCorrectState; this.scoreDirectorFactory = scoreDirectorFactory; this.variableDescriptorCache = new VariableDescriptorCache<>(solutionDescriptor); this.variableListenerSupport = VariableListenerSupport.create(this); this.variableListenerSupport.linkVariableListeners(); this.listVariableDataSupplies = buildListVariableDataSupplies(solutionDescriptor, variableListenerSupport); this.constraintMatchEnabledPreference = constraintMatchEnabledPreference; if (scoreDirectorFactory.isTrackingWorkingSolution()) { this.solutionTracker = new SolutionTracker<>(getSolutionDescriptor(), getSupplyManager()); this.trackingWorkingSolution = true; } else { this.solutionTracker = null; this.trackingWorkingSolution = false; } } private static <Solution_> ListVariableStateSupply<Solution_>[][] buildListVariableDataSupplies( SolutionDescriptor<Solution_> solutionDescriptor, VariableListenerSupport<Solution_> variableListenerSupport) { var entityDescriptorCollection = solutionDescriptor.getEntityDescriptors(); var listVariableDataSupplyArrayArray = new ListVariableStateSupply[entityDescriptorCollection.size()][]; for (var entityDescriptor : entityDescriptorCollection) { var variableDescriptorList = entityDescriptor.getGenuineVariableDescriptorList(); var listVariableDataSupplyArray = new ListVariableStateSupply[variableDescriptorList.size()]; for (var variableDescriptor : variableDescriptorList) { if (variableDescriptor instanceof ListVariableDescriptor<Solution_> listVariableDescriptor) { var demand = variableListenerSupport.demand(listVariableDescriptor.getStateDemand()); listVariableDataSupplyArray[variableDescriptor.getOrdinal()] = demand; } } listVariableDataSupplyArrayArray[entityDescriptor.getOrdinal()] = listVariableDataSupplyArray; } return listVariableDataSupplyArrayArray; } @Override public Factory_ getScoreDirectorFactory() { return scoreDirectorFactory; } @Override public SolutionDescriptor<Solution_> getSolutionDescriptor() { return scoreDirectorFactory.getSolutionDescriptor(); } @Override public ScoreDefinition<Score_> getScoreDefinition() { return scoreDirectorFactory.getScoreDefinition(); } @Override public VariableDescriptorCache<Solution_> getVariableDescriptorCache() { return variableDescriptorCache; } @Override public boolean expectShadowVariablesInCorrectState() { return expectShadowVariablesInCorrectState; } @Override public Solution_ getWorkingSolution() { return workingSolution; } protected int getWorkingInitScore() { return workingInitScore; } @Override public long getWorkingEntityListRevision() { return workingEntityListRevision; } @Override public int getWorkingGenuineEntityCount() { return workingGenuineEntityCount; } @Override public void setAllChangesWillBeUndoneBeforeStepEnds(boolean allChangesWillBeUndoneBeforeStepEnds) { this.allChangesWillBeUndoneBeforeStepEnds = allChangesWillBeUndoneBeforeStepEnds; } @Override public long getCalculationCount() { return calculationCount; } @Override public void resetCalculationCount() { this.calculationCount = 0L; } @Override public void incrementCalculationCount() { this.calculationCount++; } @Override public SupplyManager getSupplyManager() { return variableListenerSupport; } // ************************************************************************ // Complex methods // ************************************************************************ /** * Note: resetting the working solution does NOT substitute the calls to before/after methods of * the {@link ProblemChangeDirector} during {@link ProblemChange problem changes}, * as these calls are propagated to {@link VariableListener variable listeners}, * which update shadow variables in the {@link PlanningSolution working solution} to keep it consistent. */ @Override public void setWorkingSolution(Solution_ workingSolution) { this.workingSolution = requireNonNull(workingSolution); var solutionDescriptor = getSolutionDescriptor(); /* * Both problem facts and entities need to be asserted, * which requires iterating over all of them, * possibly many thousands of objects. * Providing the init score and genuine entity count requires another pass over the entities. * The following code does all of those operations in a single pass. */ Consumer<Object> visitor = null; if (lookUpEnabled) { lookUpManager.reset(); visitor = lookUpManager::addWorkingObject; // This visits all the problem facts, applying the visitor. solutionDescriptor.visitAllProblemFacts(workingSolution, visitor); } // This visits all the entities, applying the visitor if non-null. var initializationStatistics = solutionDescriptor.computeInitializationStatistics(workingSolution, visitor); setWorkingEntityListDirty(); workingInitScore = -(initializationStatistics.unassignedValueCount() + initializationStatistics.uninitializedVariableCount()); assertInitScoreZeroOrLess(); workingGenuineEntityCount = initializationStatistics.genuineEntityCount(); variableListenerSupport.resetWorkingSolution(); } private void assertInitScoreZeroOrLess() { if (workingInitScore > 0) { throw new IllegalStateException(""" workingInitScore > 0 (%d). Maybe a custom move is removing more entities than were ever added? """.formatted(workingInitScore)); } } @Override public Score_ doAndProcessMove(Move<Solution_> move, boolean assertMoveScoreFromScratch, Consumer<Score_> moveProcessor) { if (trackingWorkingSolution) { solutionTracker.setBeforeMoveSolution(workingSolution); } Move<Solution_> undoMove = move.doMove(this); Score_ score = calculateScore(); if (assertMoveScoreFromScratch) { undoMoveText = undoMove.toString(); if (trackingWorkingSolution) { solutionTracker.setAfterMoveSolution(workingSolution); } assertWorkingScoreFromScratch(score, move); } if (moveProcessor != null) { moveProcessor.accept(score); } undoMove.doMoveOnly(this); return score; } @Override public boolean isWorkingEntityListDirty(long expectedWorkingEntityListRevision) { return workingEntityListRevision != expectedWorkingEntityListRevision; } protected void setWorkingEntityListDirty() { workingEntityListRevision++; } @Override public Solution_ cloneWorkingSolution() { return cloneSolution(workingSolution); } @Override public Solution_ cloneSolution(Solution_ originalSolution) { SolutionDescriptor<Solution_> solutionDescriptor = getSolutionDescriptor(); Score_ originalScore = (Score_) solutionDescriptor.getScore(originalSolution); Solution_ cloneSolution = solutionDescriptor.getSolutionCloner().cloneSolution(originalSolution); Score_ cloneScore = (Score_) solutionDescriptor.getScore(cloneSolution); if (scoreDirectorFactory.isAssertClonedSolution()) { if (!Objects.equals(originalScore, cloneScore)) { throw new IllegalStateException("Cloning corruption: " + "the original's score (" + originalScore + ") is different from the clone's score (" + cloneScore + ").\n" + "Check the " + SolutionCloner.class.getSimpleName() + "."); } Map<Object, Object> originalEntityMap = new IdentityHashMap<>(); solutionDescriptor.visitAllEntities(originalSolution, originalEntity -> originalEntityMap.put(originalEntity, null)); solutionDescriptor.visitAllEntities(cloneSolution, cloneEntity -> { if (originalEntityMap.containsKey(cloneEntity)) { throw new IllegalStateException("Cloning corruption: " + "the same entity (" + cloneEntity + ") is present in both the original and the clone.\n" + "So when a planning variable in the original solution changes, " + "the cloned solution will change too.\n" + "Check the " + SolutionCloner.class.getSimpleName() + "."); } }); } return cloneSolution; } @Override public void triggerVariableListeners() { variableListenerSupport.triggerVariableListenersInNotificationQueues(); } @Override public void forceTriggerVariableListeners() { variableListenerSupport.forceTriggerAllVariableListeners(getWorkingSolution()); } protected void setCalculatedScore(Score_ score) { getSolutionDescriptor().setScore(workingSolution, score); calculationCount++; } @Override public AbstractScoreDirector<Solution_, Score_, Factory_> clone() { // Breaks incremental score calculation. // Subclasses should overwrite this method to avoid breaking it if possible. AbstractScoreDirector<Solution_, Score_, Factory_> clone = (AbstractScoreDirector<Solution_, Score_, Factory_>) scoreDirectorFactory .buildScoreDirector(lookUpEnabled, constraintMatchEnabledPreference); clone.setWorkingSolution(cloneWorkingSolution()); return clone; } @Override public InnerScoreDirector<Solution_, Score_> createChildThreadScoreDirector(ChildThreadType childThreadType) { if (childThreadType == ChildThreadType.PART_THREAD) { AbstractScoreDirector<Solution_, Score_, Factory_> childThreadScoreDirector = (AbstractScoreDirector<Solution_, Score_, Factory_>) scoreDirectorFactory .buildScoreDirector(lookUpEnabled, constraintMatchEnabledPreference); // ScoreCalculationCountTermination takes into account previous phases // but the calculationCount of partitions is maxed, not summed. childThreadScoreDirector.calculationCount = calculationCount; return childThreadScoreDirector; } else if (childThreadType == ChildThreadType.MOVE_THREAD) { // TODO The move thread must use constraintMatchEnabledPreference in FULL_ASSERT, // but it doesn't have to for Indictment Local Search, in which case it is a performance loss AbstractScoreDirector<Solution_, Score_, Factory_> childThreadScoreDirector = (AbstractScoreDirector<Solution_, Score_, Factory_>) scoreDirectorFactory .buildScoreDirector(true, constraintMatchEnabledPreference); childThreadScoreDirector.setWorkingSolution(cloneWorkingSolution()); return childThreadScoreDirector; } else { throw new IllegalStateException("The childThreadType (" + childThreadType + ") is not implemented."); } } @Override public void close() { workingSolution = null; workingInitScore = 0; if (lookUpEnabled) { lookUpManager.reset(); } variableListenerSupport.close(); } // ************************************************************************ // Entity/variable add/change/remove methods // ************************************************************************ public void beforeEntityAdded(EntityDescriptor<Solution_> entityDescriptor, Object entity) { variableListenerSupport.beforeEntityAdded(entityDescriptor, entity); } public void afterEntityAdded(EntityDescriptor<Solution_> entityDescriptor, Object entity) { workingInitScore -= entityDescriptor.countUninitializedVariables(entity); if (entityDescriptor.isGenuine()) { workingGenuineEntityCount++; } if (lookUpEnabled) { lookUpManager.addWorkingObject(entity); } if (!allChangesWillBeUndoneBeforeStepEnds) { setWorkingEntityListDirty(); } } @Override public void beforeVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity) { if (variableDescriptor.isGenuineAndUninitialized(entity)) { workingInitScore++; } assertInitScoreZeroOrLess(); variableListenerSupport.beforeVariableChanged(variableDescriptor, entity); } @Override public void afterVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity) { if (variableDescriptor.isGenuineAndUninitialized(entity)) { workingInitScore--; } } @Override public void changeVariableFacade(VariableDescriptor<Solution_> variableDescriptor, Object entity, Object newValue) { beforeVariableChanged(variableDescriptor, entity); variableDescriptor.setValue(entity, newValue); afterVariableChanged(variableDescriptor, entity); } @Override public void beforeListVariableElementAssigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) { // Do nothing } @Override public void afterListVariableElementAssigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) { if (!variableDescriptor.allowsUnassignedValues()) { // Unassigned elements don't count towards the initScore here. workingInitScore++; assertInitScoreZeroOrLess(); } } @Override public void beforeListVariableElementUnassigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) { // Do nothing } @Override public void afterListVariableElementUnassigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) { if (!variableDescriptor.allowsUnassignedValues()) { // Unassigned elements don't count towards the initScore here. workingInitScore--; } variableListenerSupport.afterElementUnassigned(variableDescriptor, element); } @Override public void beforeListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex, int toIndex) { // Pinning is implemented in generic moves, but custom moves need to take it into account as well. // This fail-fast exists to detect situations where pinned things are being moved, in case of user error. if (variableDescriptor.isElementPinned(this, entity, fromIndex)) { throw new IllegalStateException( """ Attempting to change list variable (%s) on an entity (%s) in range [%d, %d), which is partially or entirely pinned. This is most likely a bug in a move. Maybe you are using an improperly implemented custom move?""" .formatted(variableDescriptor, entity, fromIndex, toIndex)); } variableListenerSupport.beforeListVariableChanged(variableDescriptor, entity, fromIndex, toIndex); } @Override public void afterListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex, int toIndex) { variableListenerSupport.afterListVariableChanged(variableDescriptor, entity, fromIndex, toIndex); } public void beforeEntityRemoved(EntityDescriptor<Solution_> entityDescriptor, Object entity) { workingInitScore += entityDescriptor.countUninitializedVariables(entity); assertInitScoreZeroOrLess(); variableListenerSupport.beforeEntityRemoved(entityDescriptor, entity); } public void afterEntityRemoved(EntityDescriptor<Solution_> entityDescriptor, Object entity) { if (entityDescriptor.isGenuine()) { workingGenuineEntityCount--; } if (lookUpEnabled) { lookUpManager.removeWorkingObject(entity); } if (!allChangesWillBeUndoneBeforeStepEnds) { setWorkingEntityListDirty(); } } // ************************************************************************ // Problem fact add/change/remove methods // ************************************************************************ @Override public void beforeProblemFactAdded(Object problemFact) { // Do nothing } @Override public void afterProblemFactAdded(Object problemFact) { if (lookUpEnabled) { lookUpManager.addWorkingObject(problemFact); } variableListenerSupport.resetWorkingSolution(); // TODO do not nuke the variable listeners } @Override public void beforeProblemPropertyChanged(Object problemFactOrEntity) { // Do nothing } @Override public void afterProblemPropertyChanged(Object problemFactOrEntity) { if (isConstraintConfiguration(problemFactOrEntity)) { setWorkingSolution(workingSolution); // Nuke everything and recalculate, constraint weights have changed. } else { variableListenerSupport.resetWorkingSolution(); // TODO do not nuke the variable listeners } } @Override public void beforeProblemFactRemoved(Object problemFact) { if (isConstraintConfiguration(problemFact)) { throw new IllegalStateException("Attempted to remove constraint configuration (" + problemFact + ") from solution (" + workingSolution + ").\n" + "Maybe use before/afterProblemPropertyChanged(...) instead."); } } @Override public void afterProblemFactRemoved(Object problemFact) { if (lookUpEnabled) { lookUpManager.removeWorkingObject(problemFact); } variableListenerSupport.resetWorkingSolution(); // TODO do not nuke the variable listeners } @Override public <E> E lookUpWorkingObject(E externalObject) { if (!lookUpEnabled) { throw new IllegalStateException("When lookUpEnabled (" + lookUpEnabled + ") is disabled in the constructor, this method should not be called."); } return lookUpManager.lookUpWorkingObject(externalObject); } @Override public <E> E lookUpWorkingObjectOrReturnNull(E externalObject) { if (!lookUpEnabled) { throw new IllegalStateException("When lookUpEnabled (" + lookUpEnabled + ") is disabled in the constructor, this method should not be called."); } return lookUpManager.lookUpWorkingObjectOrReturnNull(externalObject); } // ************************************************************************ // Assert methods // ************************************************************************ @Override public void assertExpectedWorkingScore(Score_ expectedWorkingScore, Object completedAction) { Score_ workingScore = calculateScore(); if (!expectedWorkingScore.equals(workingScore)) { throw new IllegalStateException( "Score corruption (" + expectedWorkingScore.subtract(workingScore).toShortString() + "): the expectedWorkingScore (" + expectedWorkingScore + ") is not the workingScore (" + workingScore + ") after completedAction (" + completedAction + ")."); } } @Override public void assertShadowVariablesAreNotStale(Score_ expectedWorkingScore, Object completedAction) { String violationMessage = variableListenerSupport.createShadowVariablesViolationMessage(); if (violationMessage != null) { throw new IllegalStateException( VariableListener.class.getSimpleName() + " corruption after completedAction (" + completedAction + "):\n" + violationMessage); } Score_ workingScore = calculateScore(); if (!expectedWorkingScore.equals(workingScore)) { assertWorkingScoreFromScratch(workingScore, "assertShadowVariablesAreNotStale(" + expectedWorkingScore + ", " + completedAction + ")"); throw new IllegalStateException("Impossible " + VariableListener.class.getSimpleName() + " corruption (" + expectedWorkingScore.subtract(workingScore).toShortString() + "):" + " the expectedWorkingScore (" + expectedWorkingScore + ") is not the workingScore (" + workingScore + ") after all " + VariableListener.class.getSimpleName() + "s were triggered without changes to the genuine variables" + " after completedAction (" + completedAction + ").\n" + "But all the shadow variable values are still the same, so this is impossible.\n" + "Maybe run with " + EnvironmentMode.TRACKED_FULL_ASSERT + " if you aren't already, to fail earlier."); } } /** * @param predicted true if the score was predicted and might have been calculated on another thread * @return never null */ protected String buildShadowVariableAnalysis(boolean predicted) { String violationMessage = variableListenerSupport.createShadowVariablesViolationMessage(); String workingLabel = predicted ? "working" : "corrupted"; if (violationMessage == null) { return "Shadow variable corruption in the " + workingLabel + " scoreDirector:\n" + " None"; } return "Shadow variable corruption in the " + workingLabel + " scoreDirector:\n" + violationMessage + " Maybe there is a bug in the " + VariableListener.class.getSimpleName() + " of those shadow variable(s)."; } @Override public void assertWorkingScoreFromScratch(Score_ workingScore, Object completedAction) { assertScoreFromScratch(workingScore, completedAction, false); } @Override public void assertPredictedScoreFromScratch(Score_ workingScore, Object completedAction) { assertScoreFromScratch(workingScore, completedAction, true); } private void assertScoreFromScratch(Score_ score, Object completedAction, boolean predicted) { InnerScoreDirectorFactory<Solution_, Score_> assertionScoreDirectorFactory = scoreDirectorFactory .getAssertionScoreDirectorFactory(); if (assertionScoreDirectorFactory == null) { assertionScoreDirectorFactory = scoreDirectorFactory; } try (var uncorruptedScoreDirector = assertionScoreDirectorFactory.buildScoreDirector(false, true)) { uncorruptedScoreDirector.setWorkingSolution(workingSolution); Score_ uncorruptedScore = uncorruptedScoreDirector.calculateScore(); if (!score.equals(uncorruptedScore)) { String scoreCorruptionAnalysis = buildScoreCorruptionAnalysis(uncorruptedScoreDirector, predicted); String shadowVariableAnalysis = buildShadowVariableAnalysis(predicted); throw new IllegalStateException( "Score corruption (" + score.subtract(uncorruptedScore).toShortString() + "): the " + (predicted ? "predictedScore" : "workingScore") + " (" + score + ") is not the uncorruptedScore (" + uncorruptedScore + ") after completedAction (" + completedAction + "):\n" + scoreCorruptionAnalysis + "\n" + shadowVariableAnalysis); } } } @Override public void assertExpectedUndoMoveScore(Move<Solution_> move, Score_ beforeMoveScore) { Score_ undoScore = calculateScore(); if (!undoScore.equals(beforeMoveScore)) { logger.trace(" Corruption detected. Diagnosing..."); if (trackingWorkingSolution) { solutionTracker.setAfterUndoSolution(workingSolution); } // Precondition: assert that there are probably no corrupted constraints assertWorkingScoreFromScratch(undoScore, undoMoveText); // Precondition: assert that shadow variables aren't stale after doing the undoMove assertShadowVariablesAreNotStale(undoScore, undoMoveText); String corruptionDiagnosis = ""; if (trackingWorkingSolution) { // Recalculate all shadow variables from scratch. // We cannot set all shadow variables to null, since some variable listeners // may expect them to be non-null. // Instead, we just simulate a change to all genuine variables. variableListenerSupport.forceTriggerAllVariableListeners(workingSolution); solutionTracker.setUndoFromScratchSolution(workingSolution); // Also calculate from scratch for the before solution, since it might // have been corrupted but was only detected now solutionTracker.restoreBeforeSolution(); variableListenerSupport.forceTriggerAllVariableListeners(workingSolution); solutionTracker.setBeforeFromScratchSolution(workingSolution); corruptionDiagnosis = solutionTracker.buildScoreCorruptionMessage(); } String scoreDifference = undoScore.subtract(beforeMoveScore).toShortString(); String corruptionMessage = """ UndoMove corruption (%s): the beforeMoveScore (%s) is not the undoScore (%s) which is the uncorruptedScore (%s) of the workingSolution. %s 1) Enable EnvironmentMode %s (if you haven't already) to fail-faster in case there's a score corruption or variable listener corruption. 2) Check the Move.createUndoMove(...) method of the moveClass (%s). The move (%s) might have a corrupted undoMove (%s). 3) Check your custom %ss (if you have any) for shadow variables that are used by score constraints that could cause the scoreDifference (%s). """ .formatted(scoreDifference, beforeMoveScore, undoScore, undoScore, corruptionDiagnosis, EnvironmentMode.TRACKED_FULL_ASSERT, move.getClass().getSimpleName(), move, undoMoveText, VariableListener.class.getSimpleName(), scoreDifference); if (trackingWorkingSolution) { throw new UndoScoreCorruptionException(corruptionMessage, solutionTracker.getBeforeMoveSolution(), solutionTracker.getAfterMoveSolution(), solutionTracker.getAfterUndoSolution()); } else { throw new IllegalStateException(corruptionMessage); } } } /** * @param uncorruptedScoreDirector never null * @param predicted true if the score was predicted and might have been calculated on another thread * @return never null */ protected String buildScoreCorruptionAnalysis(InnerScoreDirector<Solution_, Score_> uncorruptedScoreDirector, boolean predicted) { if (!isConstraintMatchEnabled() || !uncorruptedScoreDirector.isConstraintMatchEnabled()) { return """ Score corruption analysis could not be generated because either corrupted constraintMatchEnabled (%s) \ or uncorrupted constraintMatchEnabled (%s) is disabled. Check your score constraints manually.""" .formatted(constraintMatchEnabledPreference, uncorruptedScoreDirector.isConstraintMatchEnabled()); } var corruptedAnalysis = buildScoreAnalysis(true, ScoreAnalysisMode.SCORE_CORRUPTION); var uncorruptedAnalysis = uncorruptedScoreDirector.buildScoreAnalysis(true, ScoreAnalysisMode.SCORE_CORRUPTION); var excessSet = new LinkedHashSet<MatchAnalysis<Score_>>(); var missingSet = new LinkedHashSet<MatchAnalysis<Score_>>(); uncorruptedAnalysis.constraintMap().forEach((constraintRef, uncorruptedConstraintAnalysis) -> { var corruptedConstraintAnalysis = corruptedAnalysis.constraintMap() .get(constraintRef); if (corruptedConstraintAnalysis == null || corruptedConstraintAnalysis.matches().isEmpty()) { missingSet.addAll(uncorruptedConstraintAnalysis.matches()); return; } updateExcessAndMissingConstraintMatches(uncorruptedConstraintAnalysis.matches(), corruptedConstraintAnalysis.matches(), excessSet, missingSet); }); corruptedAnalysis.constraintMap().forEach((constraintRef, corruptedConstraintAnalysis) -> { var uncorruptedConstraintAnalysis = uncorruptedAnalysis.constraintMap() .get(constraintRef); if (uncorruptedConstraintAnalysis == null || uncorruptedConstraintAnalysis.matches().isEmpty()) { excessSet.addAll(corruptedConstraintAnalysis.matches()); return; } updateExcessAndMissingConstraintMatches(uncorruptedConstraintAnalysis.matches(), corruptedConstraintAnalysis.matches(), excessSet, missingSet); }); var analysis = new StringBuilder(); analysis.append("Score corruption analysis:\n"); // If predicted, the score calculation might have happened on another thread, so a different ScoreDirector // so there is no guarantee that the working ScoreDirector is the corrupted ScoreDirector var workingLabel = predicted ? "working" : "corrupted"; appendAnalysis(analysis, workingLabel, "should not be there", excessSet); appendAnalysis(analysis, workingLabel, "are missing", missingSet); if (!missingSet.isEmpty() || !excessSet.isEmpty()) { analysis.append(""" Maybe there is a bug in the score constraints of those ConstraintMatch(s). Maybe a score constraint doesn't select all the entities it depends on, but discovers some transitively through a reference from the selected entity. This corrupts incremental score calculation, because the constraint is not re-evaluated if the transitively discovered entity changes. """.stripTrailing()); } else { if (predicted) { analysis.append(""" If multi-threaded solving is active: - the working scoreDirector is probably not the corrupted scoreDirector. - maybe the rebase() method of the move is bugged. - maybe a VariableListener affected the moveThread's workingSolution after doing and undoing a move, but this didn't happen here on the solverThread, so we can't detect it. """.stripTrailing()); } else { analysis.append(" Impossible state. Maybe this is a bug in the scoreDirector (%s)." .formatted(getClass())); } } return analysis.toString(); } private void appendAnalysis(StringBuilder analysis, String workingLabel, String suffix, Set<MatchAnalysis<Score_>> matches) { if (matches.isEmpty()) { analysis.append(""" The %s scoreDirector has no ConstraintMatch(es) which %s. """.formatted(workingLabel, suffix)); } else { analysis.append(""" The %s scoreDirector has %s ConstraintMatch(es) which %s: """.formatted(workingLabel, matches.size(), suffix)); matches.stream().sorted().limit(CONSTRAINT_MATCH_DISPLAY_LIMIT) .forEach(match -> analysis.append(""" %s/%s=%s """.formatted(match.constraintRef().constraintId(), match.justification(), match.score()))); if (matches.size() >= CONSTRAINT_MATCH_DISPLAY_LIMIT) { analysis.append(""" ... %s more """.formatted(matches.size() - CONSTRAINT_MATCH_DISPLAY_LIMIT)); } } } private void updateExcessAndMissingConstraintMatches(List<MatchAnalysis<Score_>> uncorruptedList, List<MatchAnalysis<Score_>> corruptedList, Set<MatchAnalysis<Score_>> excessSet, Set<MatchAnalysis<Score_>> missingSet) { iterateAndAddIfFound(corruptedList, uncorruptedList, excessSet); iterateAndAddIfFound(uncorruptedList, corruptedList, missingSet); } private void iterateAndAddIfFound(List<MatchAnalysis<Score_>> referenceList, List<MatchAnalysis<Score_>> lookupList, Set<MatchAnalysis<Score_>> targetSet) { if (referenceList.isEmpty()) { return; } var lookupSet = new LinkedHashSet<>(lookupList); // Guaranteed to not contain duplicates anyway. for (var reference : referenceList) { if (!lookupSet.contains(reference)) { targetSet.add(reference); } } } protected boolean isConstraintConfiguration(Object problemFactOrEntity) { SolutionDescriptor<Solution_> solutionDescriptor = scoreDirectorFactory.getSolutionDescriptor(); ConstraintConfigurationDescriptor<Solution_> constraintConfigurationDescriptor = solutionDescriptor.getConstraintConfigurationDescriptor(); if (constraintConfigurationDescriptor == null) { return false; } return constraintConfigurationDescriptor.getConstraintConfigurationClass() .isInstance(problemFactOrEntity); } @Override public String toString() { return getClass().getSimpleName() + "(" + calculationCount + ")"; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director/AbstractScoreDirectorFactory.java
package ai.timefold.solver.core.impl.score.director; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Abstract superclass for {@link ScoreDirectorFactory}. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <Score_> the score type to go with the solution * @see ScoreDirectorFactory */ public abstract class AbstractScoreDirectorFactory<Solution_, Score_ extends Score<Score_>> implements InnerScoreDirectorFactory<Solution_, Score_> { protected final transient Logger logger = LoggerFactory.getLogger(getClass()); protected SolutionDescriptor<Solution_> solutionDescriptor; protected InitializingScoreTrend initializingScoreTrend; protected InnerScoreDirectorFactory<Solution_, Score_> assertionScoreDirectorFactory = null; protected boolean assertClonedSolution = false; protected boolean trackingWorkingSolution = false; public AbstractScoreDirectorFactory(SolutionDescriptor<Solution_> solutionDescriptor) { this.solutionDescriptor = solutionDescriptor; } @Override public SolutionDescriptor<Solution_> getSolutionDescriptor() { return solutionDescriptor; } @Override public ScoreDefinition<Score_> getScoreDefinition() { return solutionDescriptor.getScoreDefinition(); } @Override public InitializingScoreTrend getInitializingScoreTrend() { return initializingScoreTrend; } public void setInitializingScoreTrend(InitializingScoreTrend initializingScoreTrend) { this.initializingScoreTrend = initializingScoreTrend; } public InnerScoreDirectorFactory<Solution_, Score_> getAssertionScoreDirectorFactory() { return assertionScoreDirectorFactory; } public void setAssertionScoreDirectorFactory(InnerScoreDirectorFactory<Solution_, Score_> assertionScoreDirectorFactory) { this.assertionScoreDirectorFactory = assertionScoreDirectorFactory; } public boolean isAssertClonedSolution() { return assertClonedSolution; } public void setAssertClonedSolution(boolean assertClonedSolution) { this.assertClonedSolution = assertClonedSolution; } /** * When true, a snapshot of the solution is created before, after and after the undo of a move. * In {@link ai.timefold.solver.core.config.solver.EnvironmentMode#TRACKED_FULL_ASSERT}, * the snapshots are compared when corruption is detected, * allowing us to report exactly what variables are different. */ public boolean isTrackingWorkingSolution() { return trackingWorkingSolution; } public void setTrackingWorkingSolution(boolean trackingWorkingSolution) { this.trackingWorkingSolution = trackingWorkingSolution; } // ************************************************************************ // Complex methods // ************************************************************************ @Override public InnerScoreDirector<Solution_, Score_> buildScoreDirector() { return buildScoreDirector(true, true); } @Override public void assertScoreFromScratch(Solution_ solution) { // Get the score before uncorruptedScoreDirector.calculateScore() modifies it Score_ score = (Score_) getSolutionDescriptor().getScore(solution); try (InnerScoreDirector<Solution_, Score_> uncorruptedScoreDirector = buildScoreDirector(false, true)) { uncorruptedScoreDirector.setWorkingSolution(solution); Score_ uncorruptedScore = uncorruptedScoreDirector.calculateScore(); if (!score.equals(uncorruptedScore)) { throw new IllegalStateException( "Score corruption (" + score.subtract(uncorruptedScore).toShortString() + "): the solution's score (" + score + ") is not the uncorruptedScore (" + uncorruptedScore + ")."); } } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director/InnerScoreDirector.java
package ai.timefold.solver.core.impl.score.director; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.TreeMap; import java.util.function.Consumer; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import ai.timefold.solver.core.api.domain.variable.VariableListener; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.analysis.ConstraintAnalysis; import ai.timefold.solver.core.api.score.analysis.MatchAnalysis; import ai.timefold.solver.core.api.score.analysis.ScoreAnalysis; import ai.timefold.solver.core.api.score.constraint.ConstraintMatch; import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal; import ai.timefold.solver.core.api.score.constraint.ConstraintRef; import ai.timefold.solver.core.api.score.constraint.Indictment; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.api.score.stream.Constraint; import ai.timefold.solver.core.api.score.stream.ConstraintJustification; import ai.timefold.solver.core.api.solver.SolutionManager; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; import ai.timefold.solver.core.impl.heuristic.move.Move; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import ai.timefold.solver.core.impl.solver.thread.ChildThreadType; import ai.timefold.solver.core.impl.util.CollectionUtils; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <Score_> the score type to go with the solution */ public interface InnerScoreDirector<Solution_, Score_ extends Score<Score_>> extends VariableDescriptorAwareScoreDirector<Solution_>, AutoCloseable { static <Score_ extends Score<Score_>> ConstraintAnalysis<Score_> getConstraintAnalysis( ConstraintMatchTotal<Score_> constraintMatchTotal, boolean analyzeConstraintMatches) { Score_ zero = constraintMatchTotal.getScore().zero(); if (analyzeConstraintMatches) { // Marge all constraint matches with the same justification. Map<ConstraintJustification, List<ConstraintMatch<Score_>>> deduplicatedConstraintMatchMap = CollectionUtils.newLinkedHashMap(constraintMatchTotal.getConstraintMatchCount()); for (var constraintMatch : constraintMatchTotal.getConstraintMatchSet()) { var constraintJustification = constraintMatch.getJustification(); var constraintMatchList = deduplicatedConstraintMatchMap.computeIfAbsent(constraintJustification, k -> new ArrayList<>(1)); constraintMatchList.add(constraintMatch); } // Sum scores for each duplicate justification; this is the total score for the match. var matchAnalyses = deduplicatedConstraintMatchMap.entrySet().stream() .map(entry -> { var score = entry.getValue().stream() .map(ConstraintMatch::getScore) .reduce(zero, Score::add); return new MatchAnalysis<>(constraintMatchTotal.getConstraintRef(), score, entry.getKey()); }) .toList(); return new ConstraintAnalysis<>(constraintMatchTotal.getConstraintRef(), constraintMatchTotal.getConstraintWeight(), constraintMatchTotal.getScore(), matchAnalyses); } else { return new ConstraintAnalysis<>(constraintMatchTotal.getConstraintRef(), constraintMatchTotal.getConstraintWeight(), constraintMatchTotal.getScore(), null); } } /** * The {@link PlanningSolution working solution} must never be the same instance as the * {@link PlanningSolution best solution}, it should be a (un)changed clone. * * @param workingSolution never null */ void setWorkingSolution(Solution_ workingSolution); /** * Calculates the {@link Score} and updates the {@link PlanningSolution working solution} accordingly. * * @return never null, the {@link Score} of the {@link PlanningSolution working solution} */ Score_ calculateScore(); /** * @return true if {@link #getConstraintMatchTotalMap()} and {@link #getIndictmentMap} can be called */ boolean isConstraintMatchEnabled(); /** * Explains the {@link Score} of {@link #calculateScore()} by splitting it up per {@link Constraint}. * <p> * The sum of {@link ConstraintMatchTotal#getScore()} equals {@link #calculateScore()}. * <p> * Call {@link #calculateScore()} before calling this method, * unless that method has already been called since the last {@link PlanningVariable} changes. * * @return never null, the key is the constraintId * (to create one, use {@link ConstraintRef#composeConstraintId(String, String)}). * If a constraint is present in the problem but resulted in no matches, * it will still be in the map with a {@link ConstraintMatchTotal#getConstraintMatchSet()} size of 0. * @throws IllegalStateException if {@link #isConstraintMatchEnabled()} returns false * @see #getIndictmentMap() */ Map<String, ConstraintMatchTotal<Score_>> getConstraintMatchTotalMap(); /** * Explains the impact of each planning entity or problem fact on the {@link Score}. * An {@link Indictment} is basically the inverse of a {@link ConstraintMatchTotal}: * it is a {@link Score} total for each {@link ConstraintMatch#getJustification() constraint justification}. * <p> * The sum of {@link ConstraintMatchTotal#getScore()} differs from {@link #calculateScore()} * because each {@link ConstraintMatch#getScore()} is counted * for each {@link ConstraintMatch#getJustification() constraint justification}. * <p> * Call {@link #calculateScore()} before calling this method, * unless that method has already been called since the last {@link PlanningVariable} changes. * * @return never null, the key is a {@link ProblemFactCollectionProperty problem fact} or a * {@link PlanningEntity planning entity} * @throws IllegalStateException if {@link #isConstraintMatchEnabled()} returns false * @see #getConstraintMatchTotalMap() */ Map<Object, Indictment<Score_>> getIndictmentMap(); /** * @return used to check {@link #isWorkingEntityListDirty(long)} later on */ long getWorkingEntityListRevision(); int getWorkingGenuineEntityCount(); /** * @param move never null * @param assertMoveScoreFromScratch true will hurt performance * @return never null */ default Score_ doAndProcessMove(Move<Solution_> move, boolean assertMoveScoreFromScratch) { return doAndProcessMove(move, assertMoveScoreFromScratch, null); } /** * @param move never null * @param assertMoveScoreFromScratch true will hurt performance * @param moveProcessor use this to store the score as well as call the acceptor and forager; skipped if null. */ Score_ doAndProcessMove(Move<Solution_> move, boolean assertMoveScoreFromScratch, Consumer<Score_> moveProcessor); /** * @param expectedWorkingEntityListRevision an * @return true if the entityList might have a different set of instances now */ boolean isWorkingEntityListDirty(long expectedWorkingEntityListRevision); /** * Some score directors keep a set of changes * that they only apply when {@link #calculateScore()} is called. * Until that happens, this set accumulates and could possibly act as a memory leak. * * @return true if the score director can potentially cause a memory leak due to unflushed changes. */ boolean requiresFlushing(); /** * Inverse shadow variables have a fail-fast for cases * where the shadow variable doesn't actually point to its correct inverse. * This is very useful to pinpoint improperly initialized solutions. * <p> * However, {@link SolutionManager#update(Object)} exists precisely for the purpose of initializing solutions. * And when this API is used, the fail-fast must not be triggered as it is guaranteed and expected * that the inverse relationships will be wrong. * In fact, they will be null. * <p> * For this case and this case only, this method is allowed to return false. * All other cases must return true, otherwise a very valuable fail-fast is lost. * * @return false if the fail-fast on shadow variables should not be triggered */ boolean expectShadowVariablesInCorrectState(); /** * @return never null */ InnerScoreDirectorFactory<Solution_, Score_> getScoreDirectorFactory(); /** * @return never null */ SolutionDescriptor<Solution_> getSolutionDescriptor(); /** * @return never null */ ScoreDefinition<Score_> getScoreDefinition(); /** * Returns a planning clone of the solution, * which is not a shallow clone nor a deep clone nor a partition clone. * * @return never null, planning clone */ Solution_ cloneWorkingSolution(); /** * Returns a planning clone of the solution, * which is not a shallow clone nor a deep clone nor a partition clone. * * @param originalSolution never null * @return never null, planning clone */ Solution_ cloneSolution(Solution_ originalSolution); /** * @return at least 0L */ long getCalculationCount(); void resetCalculationCount(); void incrementCalculationCount(); /** * @return never null */ SupplyManager getSupplyManager(); /** * Clones this {@link ScoreDirector} and its {@link PlanningSolution working solution}. * Use {@link #getWorkingSolution()} to retrieve the {@link PlanningSolution working solution} of that clone. * <p> * This is heavy method, because it usually breaks incremental score calculation. Use it sparingly. * Therefore it's best to clone lazily by delaying the clone call as long as possible. * * @return never null */ InnerScoreDirector<Solution_, Score_> clone(); InnerScoreDirector<Solution_, Score_> createChildThreadScoreDirector(ChildThreadType childThreadType); /** * Do not waste performance by propagating changes to step (or higher) mechanisms. * * @param allChangesWillBeUndoneBeforeStepEnds true if all changes will be undone */ void setAllChangesWillBeUndoneBeforeStepEnds(boolean allChangesWillBeUndoneBeforeStepEnds); /** * Asserts that if the {@link Score} is calculated for the current {@link PlanningSolution working solution} * in the current {@link ScoreDirector} (with possibly incremental calculation residue), * it is equal to the parameter {@link Score expectedWorkingScore}. * <p> * Used to assert that skipping {@link #calculateScore()} (when the score is otherwise determined) is correct. * * @param expectedWorkingScore never null * @param completedAction sometimes null, when assertion fails then the completedAction's {@link Object#toString()} * is included in the exception message */ void assertExpectedWorkingScore(Score_ expectedWorkingScore, Object completedAction); /** * Asserts that if all {@link VariableListener}s are forcibly triggered, * and therefore all shadow variables are updated if needed, * that none of the shadow variables of the {@link PlanningSolution working solution} change, * Then also asserts that the {@link Score} calculated for the {@link PlanningSolution working solution} afterwards * is equal to the parameter {@link Score expectedWorkingScore}. * <p> * Used to assert that the shadow variables' state is consistent with the genuine variables' state. * * @param expectedWorkingScore never null * @param completedAction sometimes null, when assertion fails then the completedAction's {@link Object#toString()} * is included in the exception message */ void assertShadowVariablesAreNotStale(Score_ expectedWorkingScore, Object completedAction); /** * Asserts that if the {@link Score} is calculated for the current {@link PlanningSolution working solution} * in a fresh {@link ScoreDirector} (with no incremental calculation residue), * it is equal to the parameter {@link Score workingScore}. * <p> * Furthermore, if the assert fails, a score corruption analysis might be included in the exception message. * * @param workingScore never null * @param completedAction sometimes null, when assertion fails then the completedAction's {@link Object#toString()} * is included in the exception message * @see InnerScoreDirectorFactory#assertScoreFromScratch */ void assertWorkingScoreFromScratch(Score_ workingScore, Object completedAction); /** * Asserts that if the {@link Score} is calculated for the current {@link PlanningSolution working solution} * in a fresh {@link ScoreDirector} (with no incremental calculation residue), * it is equal to the parameter {@link Score predictedScore}. * <p> * Furthermore, if the assert fails, a score corruption analysis might be included in the exception message. * * @param predictedScore never null * @param completedAction sometimes null, when assertion fails then the completedAction's {@link Object#toString()} * is included in the exception message * @see InnerScoreDirectorFactory#assertScoreFromScratch */ void assertPredictedScoreFromScratch(Score_ predictedScore, Object completedAction); /** * Asserts that if the {@link Score} is calculated for the current {@link PlanningSolution working solution} * in the current {@link ScoreDirector} (with incremental calculation residue), * it is equal to the parameter {@link Score beforeMoveScore}. * <p> * Furthermore, if the assert fails, a score corruption analysis might be included in the exception message. * * @param move never null * @param beforeMoveScore never null */ void assertExpectedUndoMoveScore(Move<Solution_> move, Score_ beforeMoveScore); /** * Needs to be called after use because some implementations need to clean up their resources. */ @Override void close(); /** * Unlike {@link #triggerVariableListeners()} which only triggers notifications already in the queue, * this triggers every variable listener on every genuine variable. * This is useful in {@link SolutionManager#update(Object)} to fill in shadow variable values. */ void forceTriggerVariableListeners(); default ScoreAnalysis<Score_> buildScoreAnalysis(boolean analyzeConstraintMatches) { return buildScoreAnalysis(analyzeConstraintMatches, ScoreAnalysisMode.DEFAULT); } /** * * @param analyzeConstraintMatches True if the result's {@link ConstraintAnalysis} should have its {@link MatchAnalysis} * populated. * @param mode Allows to tweak the behavior of this method. * @return never null */ default ScoreAnalysis<Score_> buildScoreAnalysis(boolean analyzeConstraintMatches, ScoreAnalysisMode mode) { var score = calculateScore(); switch (Objects.requireNonNull(mode)) { case RECOMMENDATION_API -> score = score.withInitScore(0); case DEFAULT -> { if (!score.isSolutionInitialized()) { throw new IllegalArgumentException(""" Cannot analyze solution (%s) as it is not initialized (%s). Maybe run the solver first?""" .formatted(getWorkingSolution(), score)); } } } var constraintAnalysisMap = new TreeMap<ConstraintRef, ConstraintAnalysis<Score_>>(); for (var constraintMatchTotal : getConstraintMatchTotalMap().values()) { var constraintAnalysis = getConstraintAnalysis(constraintMatchTotal, analyzeConstraintMatches); constraintAnalysisMap.put(constraintMatchTotal.getConstraintRef(), constraintAnalysis); } return new ScoreAnalysis<>(score, constraintAnalysisMap); } enum ScoreAnalysisMode { /** * The default mode, which will throw an exception if the solution is not initialized. */ DEFAULT, /** * If analysis is requested as a result of a score corruption detection, * there will be no tweaks to the score and no initialization exception will be thrown. * This is because score corruption may have been detected during construction heuristics, * where the score is rightfully uninitialized. */ SCORE_CORRUPTION, /** * Will not throw an exception if the solution is not initialized, * but will set {@link Score#initScore()} to zero. * Recommendation API always has an uninitialized solution by design. */ RECOMMENDATION_API } /* * The following methods are copied here from ScoreDirector because they are deprecated there for removal. * They will only be supported on this type, which serves for internal use only, * as opposed to ScoreDirector, which is a public type. * This way, we can ensure that these methods are used correctly and in a safe manner. */ default void beforeEntityAdded(Object entity) { beforeEntityAdded(getSolutionDescriptor().findEntityDescriptorOrFail(entity.getClass()), entity); } void beforeEntityAdded(EntityDescriptor<Solution_> entityDescriptor, Object entity); default void afterEntityAdded(Object entity) { afterEntityAdded(getSolutionDescriptor().findEntityDescriptorOrFail(entity.getClass()), entity); } void afterEntityAdded(EntityDescriptor<Solution_> entityDescriptor, Object entity); default void beforeEntityRemoved(Object entity) { beforeEntityRemoved(getSolutionDescriptor().findEntityDescriptorOrFail(entity.getClass()), entity); } void beforeEntityRemoved(EntityDescriptor<Solution_> entityDescriptor, Object entity); default void afterEntityRemoved(Object entity) { afterEntityRemoved(getSolutionDescriptor().findEntityDescriptorOrFail(entity.getClass()), entity); } void afterEntityRemoved(EntityDescriptor<Solution_> entityDescriptor, Object entity); void beforeProblemFactAdded(Object problemFact); void afterProblemFactAdded(Object problemFact); void beforeProblemPropertyChanged(Object problemFactOrEntity); void afterProblemPropertyChanged(Object problemFactOrEntity); void beforeProblemFactRemoved(Object problemFact); void afterProblemFactRemoved(Object problemFact); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director/InnerScoreDirectorFactory.java
package ai.timefold.solver.core.impl.score.director; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.constraint.ConstraintMatch; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <Score_> the score type to go with the solution */ public interface InnerScoreDirectorFactory<Solution_, Score_ extends Score<Score_>> extends ScoreDirectorFactory<Solution_> { /** * @return never null */ SolutionDescriptor<Solution_> getSolutionDescriptor(); /** * @return never null */ ScoreDefinition<Score_> getScoreDefinition(); @Override InnerScoreDirector<Solution_, Score_> buildScoreDirector(); /** * Like {@link #buildScoreDirector()}, but optionally disables {@link ConstraintMatch} tracking and look up * for more performance (presuming the {@link ScoreDirector} implementation actually supports it to begin with). * * @param lookUpEnabled true if a {@link ScoreDirector} implementation should track all working objects * for {@link ScoreDirector#lookUpWorkingObject(Object)} * @param constraintMatchEnabledPreference false if a {@link ScoreDirector} implementation * should not do {@link ConstraintMatch} tracking even if it supports it. * @return never null * @see InnerScoreDirector#isConstraintMatchEnabled() * @see InnerScoreDirector#getConstraintMatchTotalMap() */ default InnerScoreDirector<Solution_, Score_> buildScoreDirector(boolean lookUpEnabled, boolean constraintMatchEnabledPreference) { return buildScoreDirector(lookUpEnabled, constraintMatchEnabledPreference, true); } /** * Like {@link #buildScoreDirector()}, but optionally disables {@link ConstraintMatch} tracking and look up * for more performance (presuming the {@link ScoreDirector} implementation actually supports it to begin with). * * @param lookUpEnabled true if a {@link ScoreDirector} implementation should track all working objects * for {@link ScoreDirector#lookUpWorkingObject(Object)} * @param constraintMatchEnabledPreference false if a {@link ScoreDirector} implementation * should not do {@link ConstraintMatch} tracking even if it supports it. * @param expectShadowVariablesInCorrectState true, unless you have an exceptional reason. * See {@link InnerScoreDirector#expectShadowVariablesInCorrectState()} for details. * @return never null * @see InnerScoreDirector#isConstraintMatchEnabled() * @see InnerScoreDirector#getConstraintMatchTotalMap() */ InnerScoreDirector<Solution_, Score_> buildScoreDirector(boolean lookUpEnabled, boolean constraintMatchEnabledPreference, boolean expectShadowVariablesInCorrectState); /** * @return never null */ InitializingScoreTrend getInitializingScoreTrend(); /** * Asserts that if the {@link Score} is calculated for the parameter solution, * it would be equal to the score of that parameter. * * @param solution never null * @see InnerScoreDirector#assertWorkingScoreFromScratch(Score, Object) */ void assertScoreFromScratch(Solution_ solution); default boolean supportsConstraintMatching() { return false; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director/ScoreDirectorFactory.java
package ai.timefold.solver.core.impl.score.director; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.director.ScoreDirector; /** * Builds a {@link ScoreDirector}. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public interface ScoreDirectorFactory<Solution_> { /** * Creates a new {@link ScoreDirector} instance. * * @return never null */ ScoreDirector<Solution_> buildScoreDirector(); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director/ScoreDirectorFactoryFactory.java
package ai.timefold.solver.core.impl.score.director; import static ai.timefold.solver.core.impl.score.director.ScoreDirectorType.CONSTRAINT_STREAMS; import static ai.timefold.solver.core.impl.score.director.ScoreDirectorType.EASY; import static ai.timefold.solver.core.impl.score.director.ScoreDirectorType.INCREMENTAL; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.ServiceLoader; import java.util.function.Supplier; import java.util.stream.Stream; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.config.score.director.ScoreDirectorFactoryConfig; import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel; import ai.timefold.solver.core.config.solver.EnvironmentMode; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend; public class ScoreDirectorFactoryFactory<Solution_, Score_ extends Score<Score_>> { private final ScoreDirectorFactoryConfig config; public ScoreDirectorFactoryFactory(ScoreDirectorFactoryConfig config) { this.config = config; } public InnerScoreDirectorFactory<Solution_, Score_> buildScoreDirectorFactory(ClassLoader classLoader, EnvironmentMode environmentMode, SolutionDescriptor<Solution_> solutionDescriptor) { AbstractScoreDirectorFactory<Solution_, Score_> scoreDirectorFactory = decideMultipleScoreDirectorFactories(classLoader, solutionDescriptor, environmentMode); if (config.getAssertionScoreDirectorFactory() != null) { if (config.getAssertionScoreDirectorFactory().getAssertionScoreDirectorFactory() != null) { throw new IllegalArgumentException("A assertionScoreDirectorFactory (" + config.getAssertionScoreDirectorFactory() + ") cannot have a non-null assertionScoreDirectorFactory (" + config.getAssertionScoreDirectorFactory().getAssertionScoreDirectorFactory() + ")."); } if (environmentMode.compareTo(EnvironmentMode.FAST_ASSERT) > 0) { throw new IllegalArgumentException("A non-null assertionScoreDirectorFactory (" + config.getAssertionScoreDirectorFactory() + ") requires an environmentMode (" + environmentMode + ") of " + EnvironmentMode.FAST_ASSERT + " or lower."); } ScoreDirectorFactoryFactory<Solution_, Score_> assertionScoreDirectorFactoryFactory = new ScoreDirectorFactoryFactory<>(config.getAssertionScoreDirectorFactory()); scoreDirectorFactory.setAssertionScoreDirectorFactory(assertionScoreDirectorFactoryFactory .buildScoreDirectorFactory(classLoader, EnvironmentMode.NON_REPRODUCIBLE, solutionDescriptor)); } scoreDirectorFactory.setInitializingScoreTrend(InitializingScoreTrend.parseTrend( config.getInitializingScoreTrend() == null ? InitializingScoreTrendLevel.ANY.name() : config.getInitializingScoreTrend(), solutionDescriptor.getScoreDefinition().getLevelsSize())); if (environmentMode.isNonIntrusiveFullAsserted()) { scoreDirectorFactory.setAssertClonedSolution(true); } if (environmentMode.isTracking()) { scoreDirectorFactory.setTrackingWorkingSolution(true); } return scoreDirectorFactory; } protected AbstractScoreDirectorFactory<Solution_, Score_> decideMultipleScoreDirectorFactories( ClassLoader classLoader, SolutionDescriptor<Solution_> solutionDescriptor, EnvironmentMode environmentMode) { // Load all known Score Director Factories via SPI. ServiceLoader<ScoreDirectorFactoryService> scoreDirectorFactoryServiceLoader = classLoader == null ? ServiceLoader.load(ScoreDirectorFactoryService.class) : ServiceLoader.load(ScoreDirectorFactoryService.class, classLoader); Map<ScoreDirectorType, Supplier<AbstractScoreDirectorFactory<Solution_, Score_>>> scoreDirectorFactorySupplierMap = new EnumMap<>(ScoreDirectorType.class); for (ScoreDirectorFactoryService<Solution_, Score_> service : scoreDirectorFactoryServiceLoader) { Supplier<AbstractScoreDirectorFactory<Solution_, Score_>> factory = service.buildScoreDirectorFactory(classLoader, solutionDescriptor, config, environmentMode); if (factory != null) { scoreDirectorFactorySupplierMap.put(service.getSupportedScoreDirectorType(), factory); } } Supplier<AbstractScoreDirectorFactory<Solution_, Score_>> easyScoreDirectorFactorySupplier = scoreDirectorFactorySupplierMap.get(EASY); Supplier<AbstractScoreDirectorFactory<Solution_, Score_>> constraintStreamScoreDirectorFactorySupplier = scoreDirectorFactorySupplierMap.get(CONSTRAINT_STREAMS); Supplier<AbstractScoreDirectorFactory<Solution_, Score_>> incrementalScoreDirectorFactorySupplier = scoreDirectorFactorySupplierMap.get(INCREMENTAL); if (!ConfigUtils.isEmptyCollection(config.getScoreDrlList())) { throw new IllegalStateException("DRL constraints requested via scoreDrlList (" + config.getScoreDrlList() + "), but this is no longer supported in Timefold Solver 0.9+.\n" + "Maybe upgrade from scoreDRL to ConstraintStreams using this recipe: https://www.optaplanner.org/download/upgradeRecipe/drl-to-constraint-streams-migration.html\n" + "Maybe use Timefold Solver 0.8 instead if you can't upgrade to ConstraintStreams now."); } // Every non-null supplier means that ServiceLoader successfully loaded and configured a score director factory. assertOnlyOneScoreDirectorFactory(easyScoreDirectorFactorySupplier, constraintStreamScoreDirectorFactorySupplier, incrementalScoreDirectorFactorySupplier); if (easyScoreDirectorFactorySupplier != null) { return easyScoreDirectorFactorySupplier.get(); } else if (incrementalScoreDirectorFactorySupplier != null) { return incrementalScoreDirectorFactorySupplier.get(); } if (constraintStreamScoreDirectorFactorySupplier != null) { return constraintStreamScoreDirectorFactorySupplier.get(); } else if (config.getConstraintProviderClass() != null) { throw new IllegalStateException("Constraint Streams requested via constraintProviderClass (" + config.getConstraintProviderClass() + ") but the supporting classes were not found on the classpath.\n" + "Maybe include ai.timefold.solver:timefold-solver-constraint-streams dependency in your project?\n" + "Maybe ensure your uberjar bundles META-INF/services from included JAR files?"); } throw new IllegalArgumentException("The scoreDirectorFactory lacks configuration for " + "either constraintProviderClass, easyScoreCalculatorClass or incrementalScoreCalculatorClass."); } private void assertOnlyOneScoreDirectorFactory( Supplier<? extends ScoreDirectorFactory<Solution_>> easyScoreDirectorFactorySupplier, Supplier<? extends ScoreDirectorFactory<Solution_>> constraintStreamScoreDirectorFactorySupplier, Supplier<? extends ScoreDirectorFactory<Solution_>> incrementalScoreDirectorFactorySupplier) { if (Stream.of(easyScoreDirectorFactorySupplier, constraintStreamScoreDirectorFactorySupplier, incrementalScoreDirectorFactorySupplier) .filter(Objects::nonNull).count() > 1) { List<String> scoreDirectorFactoryPropertyList = new ArrayList<>(4); if (easyScoreDirectorFactorySupplier != null) { scoreDirectorFactoryPropertyList .add("an easyScoreCalculatorClass (" + config.getEasyScoreCalculatorClass().getName() + ")"); } if (constraintStreamScoreDirectorFactorySupplier != null) { scoreDirectorFactoryPropertyList .add("a constraintProviderClass (" + config.getConstraintProviderClass().getName() + ")"); } if (incrementalScoreDirectorFactorySupplier != null) { scoreDirectorFactoryPropertyList.add( "an incrementalScoreCalculatorClass (" + config.getIncrementalScoreCalculatorClass().getName() + ")"); } throw new IllegalArgumentException("The scoreDirectorFactory cannot have " + String.join(" and ", scoreDirectorFactoryPropertyList) + " together."); } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director/ScoreDirectorFactoryService.java
package ai.timefold.solver.core.impl.score.director; import java.util.function.Supplier; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.config.score.director.ScoreDirectorFactoryConfig; import ai.timefold.solver.core.config.solver.EnvironmentMode; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; /** * All {@link ScoreDirectorFactory} implementations must provide an implementation of this interface, * as well as an entry in META-INF/services/ai.timefold.solver.core.impl.score.director.ScoreDirectorFactoryService file. * This makes it available for discovery in {@link ScoreDirectorFactoryFactory} via {@link java.util.ServiceLoader}. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <Score_> the score type to go with the solution */ public interface ScoreDirectorFactoryService<Solution_, Score_ extends Score<Score_>> { /** * * @return never null, the score director type that is implemented by the factory */ ScoreDirectorType getSupportedScoreDirectorType(); /** * Returns a {@link Supplier} which returns new instance of a score director defined by * {@link #getSupportedScoreDirectorType()}. * This is done so that the actual factory is only instantiated after all the configuration fail-fasts have been * performed. * * @param classLoader * @param solutionDescriptor never null, solution descriptor provided by the solver * @param config never null, configuration to use for instantiating the factory * @param environmentMode never null * @return null when this type is not configured * @throws IllegalStateException if the configuration has an issue */ Supplier<AbstractScoreDirectorFactory<Solution_, Score_>> buildScoreDirectorFactory(ClassLoader classLoader, SolutionDescriptor<Solution_> solutionDescriptor, ScoreDirectorFactoryConfig config, EnvironmentMode environmentMode); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director/ScoreDirectorType.java
package ai.timefold.solver.core.impl.score.director; public enum ScoreDirectorType { EASY, CONSTRAINT_STREAMS, INCREMENTAL }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director/VariableDescriptorAwareScoreDirector.java
package ai.timefold.solver.core.impl.score.director; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; public interface VariableDescriptorAwareScoreDirector<Solution_> extends ScoreDirector<Solution_> { SolutionDescriptor<Solution_> getSolutionDescriptor(); // ************************************************************************ // Basic variable // ************************************************************************ void beforeVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity); void afterVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity); void changeVariableFacade(VariableDescriptor<Solution_> variableDescriptor, Object entity, Object newValue); // ************************************************************************ // List variable // ************************************************************************ /** * Call this for each element that will be assigned (added to a list variable of one entity without being removed * from a list variable of another entity). * * @param variableDescriptor the list variable descriptor * @param element the assigned element */ void beforeListVariableElementAssigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element); /** * Call this for each element that was assigned (added to a list variable of one entity without being removed * from a list variable of another entity). * * @param variableDescriptor the list variable descriptor * @param element the assigned element */ void afterListVariableElementAssigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element); /** * Call this for each element that will be unassigned (removed from a list variable of one entity without being added * to a list variable of another entity). * * @param variableDescriptor the list variable descriptor * @param element the unassigned element */ void beforeListVariableElementUnassigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element); /** * Call this for each element that was unassigned (removed from a list variable of one entity without being added * to a list variable of another entity). * * @param variableDescriptor the list variable descriptor * @param element the unassigned element */ void afterListVariableElementUnassigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element); /** * Notify the score director before a list variable changes. * <p> * The list variable change includes: * <ul> * <li>Changing position (index) of one or more elements.</li> * <li>Removing one or more elements from the list variable.</li> * <li>Adding one or more elements to the list variable.</li> * <li>Any mix of the above.</li> * </ul> * For the sake of variable listeners' efficiency, the change notification requires an index range that contains elements * affected by the change. The range starts at {@code fromIndex} (inclusive) and ends at {@code toIndex} (exclusive). * <p> * The range has to comply with the following contract: * <ol> * <li>{@code fromIndex} must be greater than or equal to 0; {@code toIndex} must be less than or equal to the list variable * size.</li> * <li>{@code toIndex} must be greater than or equal to {@code fromIndex}.</li> * <li>The range must contain all elements that are going to be changed.</li> * <li>The range is allowed to contain elements that are not going to be changed.</li> * <li>The range may be empty ({@code fromIndex} equals {@code toIndex}) if none of the existing list variable elements * are going to be changed.</li> * </ol> * <p> * {@link #beforeListVariableElementUnassigned(ListVariableDescriptor, Object)} must be called for each element * that will be unassigned (removed from a list variable of one entity without being added * to a list variable of another entity). * * @param variableDescriptor descriptor of the list variable being changed * @param entity the entity owning the list variable being changed * @param fromIndex low endpoint (inclusive) of the changed range * @param toIndex high endpoint (exclusive) of the changed range */ void beforeListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex, int toIndex); /** * Notify the score director after a list variable changes. * <p> * The list variable change includes: * <ul> * <li>Changing position (index) of one or more elements.</li> * <li>Removing one or more elements from the list variable.</li> * <li>Adding one or more elements to the list variable.</li> * <li>Any mix of the above.</li> * </ul> * For the sake of variable listeners' efficiency, the change notification requires an index range that contains elements * affected by the change. The range starts at {@code fromIndex} (inclusive) and ends at {@code toIndex} (exclusive). * <p> * The range has to comply with the following contract: * <ol> * <li>{@code fromIndex} must be greater than or equal to 0; {@code toIndex} must be less than or equal to the list variable * size.</li> * <li>{@code toIndex} must be greater than or equal to {@code fromIndex}.</li> * <li>The range must contain all elements that have changed.</li> * <li>The range is allowed to contain elements that have not changed.</li> * <li>The range may be empty ({@code fromIndex} equals {@code toIndex}) if none of the existing list variable elements * have changed.</li> * </ol> * <p> * {@link #afterListVariableElementUnassigned(ListVariableDescriptor, Object)} must be called for each element * that was unassigned (removed from a list variable of one entity without being added * to a list variable of another entity). * * @param variableDescriptor descriptor of the list variable being changed * @param entity the entity owning the list variable being changed * @param fromIndex low endpoint (inclusive) of the changed range * @param toIndex high endpoint (exclusive) of the changed range */ void afterListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex, int toIndex); // ************************************************************************ // Overloads without known variable descriptors // ************************************************************************ VariableDescriptorCache<Solution_> getVariableDescriptorCache(); @Override default void beforeVariableChanged(Object entity, String variableName) { beforeVariableChanged(getVariableDescriptorCache().getVariableDescriptor(entity, variableName), entity); } @Override default void afterVariableChanged(Object entity, String variableName) { afterVariableChanged(getVariableDescriptorCache().getVariableDescriptor(entity, variableName), entity); } @Override default void beforeListVariableElementAssigned(Object entity, String variableName, Object element) { beforeListVariableElementAssigned(getVariableDescriptorCache().getListVariableDescriptor(entity, variableName), element); } @Override default void afterListVariableElementAssigned(Object entity, String variableName, Object element) { afterListVariableElementAssigned(getVariableDescriptorCache().getListVariableDescriptor(entity, variableName), element); } @Override default void beforeListVariableElementUnassigned(Object entity, String variableName, Object element) { beforeListVariableElementUnassigned(getVariableDescriptorCache().getListVariableDescriptor(entity, variableName), element); } @Override default void afterListVariableElementUnassigned(Object entity, String variableName, Object element) { afterListVariableElementUnassigned(getVariableDescriptorCache().getListVariableDescriptor(entity, variableName), element); } @Override default void beforeListVariableChanged(Object entity, String variableName, int fromIndex, int toIndex) { beforeListVariableChanged(getVariableDescriptorCache().getListVariableDescriptor(entity, variableName), entity, fromIndex, toIndex); } @Override default void afterListVariableChanged(Object entity, String variableName, int fromIndex, int toIndex) { afterListVariableChanged(getVariableDescriptorCache().getListVariableDescriptor(entity, variableName), entity, fromIndex, toIndex); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director/easy/EasyScoreDirector.java
package ai.timefold.solver.core.impl.score.director.easy; import java.util.Map; 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.calculator.EasyScoreCalculator; import ai.timefold.solver.core.api.score.constraint.ConstraintMatch; import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal; import ai.timefold.solver.core.api.score.constraint.Indictment; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.score.director.AbstractScoreDirector; /** * Easy java implementation of {@link ScoreDirector}, which recalculates the {@link Score} * of the {@link PlanningSolution working solution} every time. This is non-incremental calculation, which is slow. * This score director implementation does not support {@link ScoreExplanation#getConstraintMatchTotalMap()} and * {@link ScoreExplanation#getIndictmentMap()}. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <Score_> the score type to go with the solution * @see ScoreDirector */ public class EasyScoreDirector<Solution_, Score_ extends Score<Score_>> extends AbstractScoreDirector<Solution_, Score_, EasyScoreDirectorFactory<Solution_, Score_>> { private final EasyScoreCalculator<Solution_, Score_> easyScoreCalculator; public EasyScoreDirector(EasyScoreDirectorFactory<Solution_, Score_> scoreDirectorFactory, boolean lookUpEnabled, boolean constraintMatchEnabledPreference, boolean expectShadowVariablesInCorrectState, EasyScoreCalculator<Solution_, Score_> easyScoreCalculator) { super(scoreDirectorFactory, lookUpEnabled, constraintMatchEnabledPreference, expectShadowVariablesInCorrectState); this.easyScoreCalculator = easyScoreCalculator; } public EasyScoreCalculator<Solution_, Score_> getEasyScoreCalculator() { return easyScoreCalculator; } // ************************************************************************ // Complex methods // ************************************************************************ @Override public Score_ calculateScore() { variableListenerSupport.assertNotificationQueuesAreEmpty(); Score_ score = easyScoreCalculator.calculateScore(workingSolution); if (score == null) { throw new IllegalStateException("The easyScoreCalculator (" + easyScoreCalculator.getClass() + ") must return a non-null score (" + score + ") in the method calculateScore()."); } else if (!score.isSolutionInitialized()) { throw new IllegalStateException("The score (" + this + ")'s initScore (" + score.initScore() + ") should be 0.\n" + "Maybe the score calculator (" + easyScoreCalculator.getClass() + ") is calculating " + "the initScore too, although it's the score director's responsibility."); } int workingInitScore = getWorkingInitScore(); if (workingInitScore != 0) { score = score.withInitScore(workingInitScore); } setCalculatedScore(score); return score; } /** * Always false, {@link ConstraintMatchTotal}s are not supported by this {@link ScoreDirector} implementation. * * @return false */ @Override public boolean isConstraintMatchEnabled() { return false; } /** * {@link ConstraintMatch}s are not supported by this {@link ScoreDirector} implementation. * * @throws IllegalStateException always * @return throws {@link IllegalStateException} */ @Override public Map<String, ConstraintMatchTotal<Score_>> getConstraintMatchTotalMap() { throw new IllegalStateException(ConstraintMatch.class.getSimpleName() + " is not supported by " + EasyScoreDirector.class.getSimpleName() + "."); } /** * {@link ConstraintMatch}s are not supported by this {@link ScoreDirector} implementation. * * @throws IllegalStateException always * @return throws {@link IllegalStateException} */ @Override public Map<Object, Indictment<Score_>> getIndictmentMap() { throw new IllegalStateException(ConstraintMatch.class.getSimpleName() + " is not supported by " + EasyScoreDirector.class.getSimpleName() + "."); } @Override public boolean requiresFlushing() { return false; // Every score calculation starts from scratch; nothing is saved. } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director/easy/EasyScoreDirectorFactory.java
package ai.timefold.solver.core.impl.score.director.easy; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.calculator.EasyScoreCalculator; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.score.director.AbstractScoreDirectorFactory; import ai.timefold.solver.core.impl.score.director.ScoreDirectorFactory; /** * Easy implementation of {@link ScoreDirectorFactory}. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <Score_> the score type to go with the solution * @see EasyScoreDirector * @see ScoreDirectorFactory */ public class EasyScoreDirectorFactory<Solution_, Score_ extends Score<Score_>> extends AbstractScoreDirectorFactory<Solution_, Score_> { private final EasyScoreCalculator<Solution_, Score_> easyScoreCalculator; public EasyScoreDirectorFactory(SolutionDescriptor<Solution_> solutionDescriptor, EasyScoreCalculator<Solution_, Score_> easyScoreCalculator) { super(solutionDescriptor); this.easyScoreCalculator = easyScoreCalculator; } // ************************************************************************ // Complex methods // ************************************************************************ @Override public EasyScoreDirector<Solution_, Score_> buildScoreDirector( boolean lookUpEnabled, boolean constraintMatchEnabledPreference, boolean expectShadowVariablesInCorrectState) { return new EasyScoreDirector<>(this, lookUpEnabled, constraintMatchEnabledPreference, expectShadowVariablesInCorrectState, easyScoreCalculator); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director/easy/EasyScoreDirectorFactoryService.java
package ai.timefold.solver.core.impl.score.director.easy; import java.util.function.Supplier; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.calculator.EasyScoreCalculator; import ai.timefold.solver.core.config.score.director.ScoreDirectorFactoryConfig; import ai.timefold.solver.core.config.solver.EnvironmentMode; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.score.director.AbstractScoreDirectorFactory; import ai.timefold.solver.core.impl.score.director.ScoreDirectorFactoryService; import ai.timefold.solver.core.impl.score.director.ScoreDirectorType; public final class EasyScoreDirectorFactoryService<Solution_, Score_ extends Score<Score_>> implements ScoreDirectorFactoryService<Solution_, Score_> { @Override public ScoreDirectorType getSupportedScoreDirectorType() { return ScoreDirectorType.EASY; } @Override public Supplier<AbstractScoreDirectorFactory<Solution_, Score_>> buildScoreDirectorFactory(ClassLoader classLoader, SolutionDescriptor<Solution_> solutionDescriptor, ScoreDirectorFactoryConfig config, EnvironmentMode environmentMode) { if (config.getEasyScoreCalculatorClass() != null) { if (!EasyScoreCalculator.class.isAssignableFrom(config.getEasyScoreCalculatorClass())) { throw new IllegalArgumentException( "The easyScoreCalculatorClass (" + config.getEasyScoreCalculatorClass() + ") does not implement " + EasyScoreCalculator.class.getSimpleName() + "."); } return () -> { EasyScoreCalculator<Solution_, Score_> easyScoreCalculator = ConfigUtils.newInstance(config, "easyScoreCalculatorClass", config.getEasyScoreCalculatorClass()); ConfigUtils.applyCustomProperties(easyScoreCalculator, "easyScoreCalculatorClass", config.getEasyScoreCalculatorCustomProperties(), "easyScoreCalculatorCustomProperties"); return new EasyScoreDirectorFactory<>(solutionDescriptor, easyScoreCalculator); }; } else { if (config.getEasyScoreCalculatorCustomProperties() != null) { throw new IllegalStateException( "If there is no easyScoreCalculatorClass (" + config.getEasyScoreCalculatorClass() + "), then there can be no easyScoreCalculatorCustomProperties (" + config.getEasyScoreCalculatorCustomProperties() + ") either."); } return null; } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director/incremental/IncrementalScoreDirector.java
package ai.timefold.solver.core.impl.score.director.incremental; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.calculator.ConstraintMatchAwareIncrementalScoreCalculator; import ai.timefold.solver.core.api.score.calculator.IncrementalScoreCalculator; import ai.timefold.solver.core.api.score.constraint.ConstraintMatch; import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal; import ai.timefold.solver.core.api.score.constraint.Indictment; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; import ai.timefold.solver.core.impl.score.constraint.DefaultIndictment; import ai.timefold.solver.core.impl.score.director.AbstractScoreDirector; /** * Incremental java implementation of {@link ScoreDirector}, which only recalculates the {@link Score} * of the part of the {@link PlanningSolution working solution} that changed, * instead of the going through the entire {@link PlanningSolution}. This is incremental calculation, which is fast. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <Score_> the score type to go with the solution * @see ScoreDirector */ public class IncrementalScoreDirector<Solution_, Score_ extends Score<Score_>> extends AbstractScoreDirector<Solution_, Score_, IncrementalScoreDirectorFactory<Solution_, Score_>> { private final IncrementalScoreCalculator<Solution_, Score_> incrementalScoreCalculator; public IncrementalScoreDirector(IncrementalScoreDirectorFactory<Solution_, Score_> scoreDirectorFactory, boolean lookUpEnabled, boolean constraintMatchEnabledPreference, boolean expectShadowVariablesInCorrectState, IncrementalScoreCalculator<Solution_, Score_> incrementalScoreCalculator) { super(scoreDirectorFactory, lookUpEnabled, constraintMatchEnabledPreference, expectShadowVariablesInCorrectState); this.incrementalScoreCalculator = incrementalScoreCalculator; } public IncrementalScoreCalculator<Solution_, Score_> getIncrementalScoreCalculator() { return incrementalScoreCalculator; } // ************************************************************************ // Complex methods // ************************************************************************ @Override public void setWorkingSolution(Solution_ workingSolution) { super.setWorkingSolution(workingSolution); if (incrementalScoreCalculator instanceof ConstraintMatchAwareIncrementalScoreCalculator) { ((ConstraintMatchAwareIncrementalScoreCalculator<Solution_, ?>) incrementalScoreCalculator) .resetWorkingSolution(workingSolution, constraintMatchEnabledPreference); } else { incrementalScoreCalculator.resetWorkingSolution(workingSolution); } } @Override public Score_ calculateScore() { variableListenerSupport.assertNotificationQueuesAreEmpty(); Score_ score = incrementalScoreCalculator.calculateScore(); if (score == null) { throw new IllegalStateException("The incrementalScoreCalculator (" + incrementalScoreCalculator.getClass() + ") must return a non-null score (" + score + ") in the method calculateScore()."); } else if (!score.isSolutionInitialized()) { throw new IllegalStateException("The score (" + this + ")'s initScore (" + score.initScore() + ") should be 0.\n" + "Maybe the score calculator (" + incrementalScoreCalculator.getClass() + ") is calculating " + "the initScore too, although it's the score director's responsibility."); } int workingInitScore = getWorkingInitScore(); if (workingInitScore != 0) { score = score.withInitScore(workingInitScore); } setCalculatedScore(score); return score; } @Override public boolean isConstraintMatchEnabled() { return constraintMatchEnabledPreference && incrementalScoreCalculator instanceof ConstraintMatchAwareIncrementalScoreCalculator; } @Override public Map<String, ConstraintMatchTotal<Score_>> getConstraintMatchTotalMap() { if (!isConstraintMatchEnabled()) { throw new IllegalStateException("When constraintMatchEnabled (" + isConstraintMatchEnabled() + ") is disabled in the constructor, this method should not be called."); } // Notice that we don't trigger the variable listeners return ((ConstraintMatchAwareIncrementalScoreCalculator<Solution_, Score_>) incrementalScoreCalculator) .getConstraintMatchTotals() .stream() .collect(toMap(c -> c.getConstraintRef().constraintId(), identity())); } @Override public Map<Object, Indictment<Score_>> getIndictmentMap() { if (!isConstraintMatchEnabled()) { throw new IllegalStateException("When constraintMatchEnabled (" + isConstraintMatchEnabled() + ") is disabled in the constructor, this method should not be called."); } Map<Object, Indictment<Score_>> incrementalIndictmentMap = ((ConstraintMatchAwareIncrementalScoreCalculator<Solution_, Score_>) incrementalScoreCalculator) .getIndictmentMap(); if (incrementalIndictmentMap != null) { return incrementalIndictmentMap; } Map<Object, Indictment<Score_>> indictmentMap = new LinkedHashMap<>(); // TODO use entitySize Score_ zeroScore = getScoreDefinition().getZeroScore(); Map<String, ConstraintMatchTotal<Score_>> constraintMatchTotalMap = getConstraintMatchTotalMap(); for (ConstraintMatchTotal<Score_> constraintMatchTotal : constraintMatchTotalMap.values()) { for (ConstraintMatch<Score_> constraintMatch : constraintMatchTotal.getConstraintMatchSet()) { constraintMatch.getIndictedObjectList() .stream() .filter(Objects::nonNull) .distinct() // One match might have the same indictment twice. .forEach(fact -> { DefaultIndictment<Score_> indictment = (DefaultIndictment<Score_>) indictmentMap.computeIfAbsent(fact, k -> new DefaultIndictment<>(fact, zeroScore)); indictment.addConstraintMatch(constraintMatch); }); } } return indictmentMap; } @Override public boolean requiresFlushing() { return true; // Incremental may decide to keep events for delayed processing. } // ************************************************************************ // Entity/variable add/change/remove methods // ************************************************************************ @Override public void beforeEntityAdded(EntityDescriptor<Solution_> entityDescriptor, Object entity) { incrementalScoreCalculator.beforeEntityAdded(entity); super.beforeEntityAdded(entityDescriptor, entity); } @Override public void afterEntityAdded(EntityDescriptor<Solution_> entityDescriptor, Object entity) { incrementalScoreCalculator.afterEntityAdded(entity); super.afterEntityAdded(entityDescriptor, entity); } @Override public void beforeVariableChanged(VariableDescriptor variableDescriptor, Object entity) { incrementalScoreCalculator.beforeVariableChanged(entity, variableDescriptor.getVariableName()); super.beforeVariableChanged(variableDescriptor, entity); } @Override public void afterVariableChanged(VariableDescriptor variableDescriptor, Object entity) { incrementalScoreCalculator.afterVariableChanged(entity, variableDescriptor.getVariableName()); super.afterVariableChanged(variableDescriptor, entity); } // TODO Add support for list variable (https://issues.redhat.com/browse/PLANNER-2711). @Override public void beforeListVariableElementAssigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) { incrementalScoreCalculator.beforeListVariableElementAssigned(variableDescriptor.getVariableName(), element); super.beforeListVariableElementAssigned(variableDescriptor, element); } @Override public void afterListVariableElementAssigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) { incrementalScoreCalculator.afterListVariableElementAssigned(variableDescriptor.getVariableName(), element); super.afterListVariableElementAssigned(variableDescriptor, element); } @Override public void beforeListVariableElementUnassigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) { incrementalScoreCalculator.beforeListVariableElementUnassigned(variableDescriptor.getVariableName(), element); super.beforeListVariableElementUnassigned(variableDescriptor, element); } @Override public void afterListVariableElementUnassigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) { incrementalScoreCalculator.afterListVariableElementUnassigned(variableDescriptor.getVariableName(), element); super.afterListVariableElementUnassigned(variableDescriptor, element); } @Override public void beforeListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex, int toIndex) { incrementalScoreCalculator.beforeListVariableChanged(entity, variableDescriptor.getVariableName(), fromIndex, toIndex); super.beforeListVariableChanged(variableDescriptor, entity, fromIndex, toIndex); } @Override public void afterListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex, int toIndex) { incrementalScoreCalculator.afterListVariableChanged(entity, variableDescriptor.getVariableName(), fromIndex, toIndex); super.afterListVariableChanged(variableDescriptor, entity, fromIndex, toIndex); } @Override public void beforeEntityRemoved(EntityDescriptor<Solution_> entityDescriptor, Object entity) { incrementalScoreCalculator.beforeEntityRemoved(entity); super.beforeEntityRemoved(entityDescriptor, entity); } @Override public void afterEntityRemoved(EntityDescriptor<Solution_> entityDescriptor, Object entity) { incrementalScoreCalculator.afterEntityRemoved(entity); super.afterEntityRemoved(entityDescriptor, entity); } // ************************************************************************ // Problem fact add/change/remove methods // ************************************************************************ @Override public void beforeProblemFactAdded(Object problemFact) { super.beforeProblemFactAdded(problemFact); } @Override public void afterProblemFactAdded(Object problemFact) { incrementalScoreCalculator.resetWorkingSolution(workingSolution); // TODO do not nuke it super.afterProblemFactAdded(problemFact); } @Override public void beforeProblemPropertyChanged(Object problemFactOrEntity) { super.beforeProblemPropertyChanged(problemFactOrEntity); } @Override public void afterProblemPropertyChanged(Object problemFactOrEntity) { incrementalScoreCalculator.resetWorkingSolution(workingSolution); // TODO do not nuke it super.afterProblemPropertyChanged(problemFactOrEntity); } @Override public void beforeProblemFactRemoved(Object problemFact) { super.beforeProblemFactRemoved(problemFact); } @Override public void afterProblemFactRemoved(Object problemFact) { incrementalScoreCalculator.resetWorkingSolution(workingSolution); // TODO do not nuke it super.afterProblemFactRemoved(problemFact); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director/incremental/IncrementalScoreDirectorFactory.java
package ai.timefold.solver.core.impl.score.director.incremental; import java.util.function.Supplier; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.calculator.ConstraintMatchAwareIncrementalScoreCalculator; import ai.timefold.solver.core.api.score.calculator.IncrementalScoreCalculator; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.score.director.AbstractScoreDirectorFactory; import ai.timefold.solver.core.impl.score.director.ScoreDirectorFactory; /** * Incremental implementation of {@link ScoreDirectorFactory}. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation * @param <Score_> the score type to go with the solution * @see IncrementalScoreDirector * @see ScoreDirectorFactory */ public class IncrementalScoreDirectorFactory<Solution_, Score_ extends Score<Score_>> extends AbstractScoreDirectorFactory<Solution_, Score_> { private final Supplier<IncrementalScoreCalculator<Solution_, Score_>> incrementalScoreCalculatorSupplier; public IncrementalScoreDirectorFactory(SolutionDescriptor<Solution_> solutionDescriptor, Supplier<IncrementalScoreCalculator<Solution_, Score_>> incrementalScoreCalculatorSupplier) { super(solutionDescriptor); this.incrementalScoreCalculatorSupplier = incrementalScoreCalculatorSupplier; } @Override public boolean supportsConstraintMatching() { return incrementalScoreCalculatorSupplier.get() instanceof ConstraintMatchAwareIncrementalScoreCalculator; } @Override public IncrementalScoreDirector<Solution_, Score_> buildScoreDirector(boolean lookUpEnabled, boolean constraintMatchEnabledPreference, boolean expectShadowVariablesInCorrectState) { return new IncrementalScoreDirector<>(this, lookUpEnabled, constraintMatchEnabledPreference, expectShadowVariablesInCorrectState, incrementalScoreCalculatorSupplier.get()); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/director/incremental/IncrementalScoreDirectorFactoryService.java
package ai.timefold.solver.core.impl.score.director.incremental; import java.util.function.Supplier; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.calculator.IncrementalScoreCalculator; import ai.timefold.solver.core.config.score.director.ScoreDirectorFactoryConfig; import ai.timefold.solver.core.config.solver.EnvironmentMode; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.score.director.AbstractScoreDirectorFactory; import ai.timefold.solver.core.impl.score.director.ScoreDirectorFactoryService; import ai.timefold.solver.core.impl.score.director.ScoreDirectorType; public final class IncrementalScoreDirectorFactoryService<Solution_, Score_ extends Score<Score_>> implements ScoreDirectorFactoryService<Solution_, Score_> { @Override public ScoreDirectorType getSupportedScoreDirectorType() { return ScoreDirectorType.INCREMENTAL; } @Override public Supplier<AbstractScoreDirectorFactory<Solution_, Score_>> buildScoreDirectorFactory(ClassLoader classLoader, SolutionDescriptor<Solution_> solutionDescriptor, ScoreDirectorFactoryConfig config, EnvironmentMode environmentMode) { if (config.getIncrementalScoreCalculatorClass() != null) { if (!IncrementalScoreCalculator.class.isAssignableFrom(config.getIncrementalScoreCalculatorClass())) { throw new IllegalArgumentException( "The incrementalScoreCalculatorClass (" + config.getIncrementalScoreCalculatorClass() + ") does not implement " + IncrementalScoreCalculator.class.getSimpleName() + "."); } return () -> new IncrementalScoreDirectorFactory<>(solutionDescriptor, () -> { IncrementalScoreCalculator<Solution_, Score_> incrementalScoreCalculator = ConfigUtils.newInstance(config, "incrementalScoreCalculatorClass", config.getIncrementalScoreCalculatorClass()); ConfigUtils.applyCustomProperties(incrementalScoreCalculator, "incrementalScoreCalculatorClass", config.getIncrementalScoreCalculatorCustomProperties(), "incrementalScoreCalculatorCustomProperties"); return incrementalScoreCalculator; }); } else { if (config.getIncrementalScoreCalculatorCustomProperties() != null) { throw new IllegalStateException( "If there is no incrementalScoreCalculatorClass (" + config.getIncrementalScoreCalculatorClass() + "), then there can be no incrementalScoreCalculatorCustomProperties (" + config.getIncrementalScoreCalculatorCustomProperties() + ") either."); } return null; } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/BreakImpl.java
package ai.timefold.solver.core.impl.score.stream; import ai.timefold.solver.core.api.score.stream.common.Break; /** * When adding fields, remember to add them to the JSON serialization code as well, if you want them exposed. * * @param <Value_> * @param <Point_> * @param <Difference_> */ final class BreakImpl<Value_, Point_ extends Comparable<Point_>, Difference_ extends Comparable<Difference_>> implements Break<Value_, Difference_> { private final SequenceImpl<Value_, Point_, Difference_> nextSequence; SequenceImpl<Value_, Point_, Difference_> previousSequence; private Difference_ length; BreakImpl(SequenceImpl<Value_, Point_, Difference_> nextSequence, SequenceImpl<Value_, Point_, Difference_> previousSequence) { this.nextSequence = nextSequence; setPreviousSequence(previousSequence); } @Override public boolean isFirst() { return previousSequence.isFirst(); } @Override public boolean isLast() { return nextSequence.isLast(); } @Override public Value_ getPreviousSequenceEnd() { return previousSequence.lastItem.value(); } @Override public Value_ getNextSequenceStart() { return nextSequence.firstItem.value(); } @Override public Difference_ getLength() { return length; } void setPreviousSequence(SequenceImpl<Value_, Point_, Difference_> previousSequence) { this.previousSequence = previousSequence; updateLength(); } void updateLength() { this.length = previousSequence.computeDifference(nextSequence); } @Override public String toString() { return "Break{" + "previousSequence=" + previousSequence + ", nextSequence=" + nextSequence + ", length=" + length + '}'; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/ComparableValue.java
package ai.timefold.solver.core.impl.score.stream; import java.util.TreeMap; import java.util.TreeSet; /** * Each {@link #value()} is associated with a point ({@link #index()}) on the number line. * Comparisons are made using the points on the number line, not the actual values. * * <p> * {@link #equals(Object)} and {@link #hashCode()} of this class is not a concern, * as it is only used in a {@link TreeSet} or {@link TreeMap}. * No two values {@link #compareTo(ComparableValue) compare} equal unless they are the same object, * even if they are in the same position on the number line. * * @param value the value to be put on the number line * @param index position of the value on the number line * @param <Value_> generic type of the value * @param <Point_> generic type of the point on the number line */ record ComparableValue<Value_, Point_ extends Comparable<Point_>>(Value_ value, Point_ index) implements Comparable<ComparableValue<Value_, Point_>> { @Override public int compareTo(ComparableValue<Value_, Point_> other) { if (this == other) { return 0; } Point_ point1 = this.index; Point_ point2 = other.index; if (point1 != point2) { int comparison = point1.compareTo(point2); if (comparison != 0) { return comparison; } } return compareWithIdentityHashCode(this.value, other.value); } private int compareWithIdentityHashCode(Value_ o1, Value_ o2) { if (o1 == o2) { return 0; } // Identity Hashcode for duplicate protection; we must always include duplicates. // Ex: two different games on the same time slot int identityHashCode1 = System.identityHashCode(o1); int identityHashCode2 = System.identityHashCode(o2); return Integer.compare(identityHashCode1, identityHashCode2); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/ConsecutiveSetTree.java
package ai.timefold.solver.core.impl.score.stream; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.NavigableMap; import java.util.Objects; import java.util.TreeMap; import java.util.function.BiFunction; import ai.timefold.solver.core.api.score.stream.common.Break; import ai.timefold.solver.core.api.score.stream.common.Sequence; import ai.timefold.solver.core.api.score.stream.common.SequenceChain; /** * A {@code ConsecutiveSetTree} determines what values are consecutive. * A sequence <i>x<sub>1</sub>,&nbsp;x<sub>2</sub>,&nbsp;x<sub>3</sub>,&nbsp;...,&nbsp;x<sub>n</sub></i> * is understood to be consecutive by <i>d</i> iff * <i>x<sub>2</sub> &minus; x<sub>1</sub> &le; d, x<sub>3</sub> &minus; x<sub>2</sub> &le; d, ..., x<sub>n</sub> &minus; * x<sub>n-1</sub> &le; d</i>. * This data structure can be thought as an interval tree that maps the point <i>p</i> to the interval <i>[p, p + d]</i>. * * @param <Value_> The type of value stored (examples: shifts) * @param <Point_> The type of the point (examples: int, LocalDateTime) * @param <Difference_> The type of the difference (examples: int, Duration) */ public final class ConsecutiveSetTree<Value_, Point_ extends Comparable<Point_>, Difference_ extends Comparable<Difference_>> implements SequenceChain<Value_, Difference_> { final BiFunction<Point_, Point_, Difference_> differenceFunction; final BiFunction<Point_, Point_, Difference_> sequenceLengthFunction; private final Difference_ maxDifference; private final Difference_ zeroDifference; private final Map<Value_, ValueCount<ComparableValue<Value_, Point_>>> valueCountMap = new HashMap<>(); private final NavigableMap<ComparableValue<Value_, Point_>, Value_> itemMap = new TreeMap<>(); private final NavigableMap<ComparableValue<Value_, Point_>, SequenceImpl<Value_, Point_, Difference_>> startItemToSequence = new TreeMap<>(); private final NavigableMap<ComparableValue<Value_, Point_>, BreakImpl<Value_, Point_, Difference_>> startItemToPreviousBreak = new TreeMap<>(); private ComparableValue<Value_, Point_> firstItem; private ComparableValue<Value_, Point_> lastItem; public ConsecutiveSetTree(BiFunction<Point_, Point_, Difference_> differenceFunction, BiFunction<Difference_, Difference_, Difference_> sumFunction, Difference_ maxDifference, Difference_ zeroDifference) { this.differenceFunction = differenceFunction; this.sequenceLengthFunction = (first, last) -> sumFunction.apply(maxDifference, differenceFunction.apply(first, last)); this.maxDifference = maxDifference; this.zeroDifference = zeroDifference; } @Override public Collection<Sequence<Value_, Difference_>> getConsecutiveSequences() { return Collections.unmodifiableCollection(startItemToSequence.values()); } @Override public Collection<Break<Value_, Difference_>> getBreaks() { return Collections.unmodifiableCollection(startItemToPreviousBreak.values()); } @Override public Sequence<Value_, Difference_> getFirstSequence() { if (startItemToSequence.isEmpty()) { return null; } return startItemToSequence.firstEntry().getValue(); } @Override public Sequence<Value_, Difference_> getLastSequence() { if (startItemToSequence.isEmpty()) { return null; } return startItemToSequence.lastEntry().getValue(); } @Override public Break<Value_, Difference_> getFirstBreak() { if (startItemToSequence.size() <= 1) { return null; } return startItemToPreviousBreak.firstEntry().getValue(); } @Override public Break<Value_, Difference_> getLastBreak() { if (startItemToSequence.size() <= 1) { return null; } return startItemToPreviousBreak.lastEntry().getValue(); } public boolean add(Value_ value, Point_ valueIndex) { var valueCount = valueCountMap.get(value); if (valueCount != null) { // Item already in bag. var addingItem = valueCount.value; if (!Objects.equals(addingItem.index(), valueIndex)) { throw new IllegalStateException( "Impossible state: the item (" + value + ") is already in the bag with a different index (" + addingItem.index() + " vs " + valueIndex + ").\n" + "Maybe the index map function is not deterministic?"); } valueCount.count++; return true; } // Adding item to the bag. var addingItem = new ComparableValue<>(value, valueIndex); valueCountMap.put(value, new ValueCount<>(addingItem)); itemMap.put(addingItem, addingItem.value()); if (firstItem == null || addingItem.compareTo(firstItem) < 0) { firstItem = addingItem; } if (lastItem == null || addingItem.compareTo(lastItem) > 0) { lastItem = addingItem; } var firstBeforeItemEntry = startItemToSequence.floorEntry(addingItem); if (firstBeforeItemEntry != null) { var firstBeforeItem = firstBeforeItemEntry.getKey(); var endOfBeforeSequenceItem = firstBeforeItemEntry.getValue().lastItem; var endOfBeforeSequenceIndex = endOfBeforeSequenceItem.index(); if (isInNaturalOrderAndHashOrderIfEqual(valueIndex, value, endOfBeforeSequenceIndex, endOfBeforeSequenceItem.value())) { // Item is already in the bag; do nothing return true; } // Item is outside the bag var firstAfterItem = startItemToSequence.higherKey(addingItem); if (firstAfterItem != null) { addBetweenItems(addingItem, firstBeforeItem, endOfBeforeSequenceItem, firstAfterItem); } else { var prevBag = startItemToSequence.get(firstBeforeItem); if (isFirstSuccessorOfSecond(addingItem, endOfBeforeSequenceItem)) { // We need to extend the first bag // No break since afterItem is null prevBag.setEnd(addingItem); } else { // Start a new bag of consecutive items var newBag = new SequenceImpl<>(this, addingItem); startItemToSequence.put(addingItem, newBag); startItemToPreviousBreak.put(addingItem, new BreakImpl<>(newBag, prevBag)); } } } else { // No items before it var firstAfterItem = startItemToSequence.higherKey(addingItem); if (firstAfterItem != null) { if (isFirstSuccessorOfSecond(firstAfterItem, addingItem)) { // We need to move the after bag to use item as key var afterBag = startItemToSequence.remove(firstAfterItem); afterBag.setStart(addingItem); // No break since this is the first sequence startItemToSequence.put(addingItem, afterBag); } else { // Start a new bag of consecutive items var afterBag = startItemToSequence.get(firstAfterItem); var newBag = new SequenceImpl<>(this, addingItem); startItemToSequence.put(addingItem, newBag); startItemToPreviousBreak.put(firstAfterItem, new BreakImpl<>(afterBag, newBag)); } } else { // Start a new bag of consecutive items var newBag = new SequenceImpl<>(this, addingItem); startItemToSequence.put(addingItem, newBag); // Bag have no other items, so no break } } return true; } private static <T extends Comparable<T>, Value_> boolean isInNaturalOrderAndHashOrderIfEqual(T a, Value_ aItem, T b, Value_ bItem) { int difference = a.compareTo(b); if (difference != 0) { return difference < 0; } return System.identityHashCode(aItem) - System.identityHashCode(bItem) < 0; } private void addBetweenItems(ComparableValue<Value_, Point_> comparableItem, ComparableValue<Value_, Point_> firstBeforeItem, ComparableValue<Value_, Point_> endOfBeforeSequenceItem, ComparableValue<Value_, Point_> firstAfterItem) { if (isFirstSuccessorOfSecond(comparableItem, endOfBeforeSequenceItem)) { // We need to extend the first bag var prevBag = startItemToSequence.get(firstBeforeItem); if (isFirstSuccessorOfSecond(firstAfterItem, comparableItem)) { // We need to merge the two bags startItemToPreviousBreak.remove(firstAfterItem); var afterBag = startItemToSequence.remove(firstAfterItem); prevBag.merge(afterBag); var maybeNextBreak = startItemToPreviousBreak.higherEntry(firstAfterItem); if (maybeNextBreak != null) { maybeNextBreak.getValue().setPreviousSequence(prevBag); } } else { prevBag.setEnd(comparableItem); startItemToPreviousBreak.get(firstAfterItem).updateLength(); } } else { // Don't need to extend the first bag if (isFirstSuccessorOfSecond(firstAfterItem, comparableItem)) { // We need to move the after bag to use item as key var afterBag = startItemToSequence.remove(firstAfterItem); afterBag.setStart(comparableItem); startItemToSequence.put(comparableItem, afterBag); var prevBreak = startItemToPreviousBreak.remove(firstAfterItem); prevBreak.updateLength(); startItemToPreviousBreak.put(comparableItem, prevBreak); } else { // Start a new bag of consecutive items var newBag = new SequenceImpl<>(this, comparableItem); startItemToSequence.put(comparableItem, newBag); startItemToPreviousBreak.get(firstAfterItem).setPreviousSequence(newBag); SequenceImpl<Value_, Point_, Difference_> previousSequence = startItemToSequence.get(firstBeforeItem); startItemToPreviousBreak.put(comparableItem, new BreakImpl<>(newBag, previousSequence)); } } } public boolean remove(Value_ value) { var valueCount = valueCountMap.get(value); if (valueCount == null) { // Item not in bag. return false; } valueCount.count--; if (valueCount.count > 0) { // Item still in bag. return true; } // Item is removed from bag valueCountMap.remove(value); var removingItem = valueCount.value; itemMap.remove(removingItem); boolean noMoreItems = itemMap.isEmpty(); if (removingItem.compareTo(firstItem) == 0) { firstItem = noMoreItems ? null : itemMap.firstEntry().getKey(); } if (removingItem.compareTo(lastItem) == 0) { lastItem = noMoreItems ? null : itemMap.lastEntry().getKey(); } var firstBeforeItemEntry = startItemToSequence.floorEntry(removingItem); var firstBeforeItem = firstBeforeItemEntry.getKey(); var bag = firstBeforeItemEntry.getValue(); if (bag.getFirstItem() == bag.getLastItem()) { // Bag is empty if first item = last item startItemToSequence.remove(firstBeforeItem); var removedBreak = startItemToPreviousBreak.remove(firstBeforeItem); var extendedBreakEntry = startItemToPreviousBreak.higherEntry(firstBeforeItem); if (extendedBreakEntry != null) { if (removedBreak != null) { var extendedBreak = extendedBreakEntry.getValue(); extendedBreak.setPreviousSequence(removedBreak.previousSequence); } else { startItemToPreviousBreak.remove(extendedBreakEntry.getKey()); } } } else { // Bag is not empty. removeItemFromBag(bag, removingItem, firstBeforeItem, bag.lastItem); } return true; } // Protected API private void removeItemFromBag(SequenceImpl<Value_, Point_, Difference_> bag, ComparableValue<Value_, Point_> item, ComparableValue<Value_, Point_> sequenceStart, ComparableValue<Value_, Point_> sequenceEnd) { if (item.equals(sequenceStart)) { // Change start key to the item after this one bag.setStart(itemMap.higherKey(item)); startItemToSequence.remove(sequenceStart); var extendedBreak = startItemToPreviousBreak.remove(sequenceStart); var firstItem = bag.firstItem; startItemToSequence.put(firstItem, bag); if (extendedBreak != null) { extendedBreak.updateLength(); startItemToPreviousBreak.put(firstItem, extendedBreak); } return; } if (item.equals(sequenceEnd)) { // Set end key to the item before this one bag.setEnd(itemMap.lowerKey(item)); var extendedBreakEntry = startItemToPreviousBreak.higherEntry(item); if (extendedBreakEntry != null) { var extendedBreak = extendedBreakEntry.getValue(); extendedBreak.updateLength(); } return; } var firstAfterItem = bag.getComparableItems().higherKey(item); var firstBeforeItem = bag.getComparableItems().lowerKey(item); if (isFirstSuccessorOfSecond(firstAfterItem, firstBeforeItem)) { // Bag is not split since the next two items are still close enough return; } // Need to split bag into two halves // Both halves are not empty as the item was not an endpoint // Additional, the breaks before and after the broken sequence // are not affected since an endpoint was not removed var splitBag = bag.split(item); var firstSplitItem = splitBag.firstItem; startItemToSequence.put(firstSplitItem, splitBag); startItemToPreviousBreak.put(firstSplitItem, new BreakImpl<>(splitBag, bag)); var maybeNextBreak = startItemToPreviousBreak.higherEntry(firstAfterItem); if (maybeNextBreak != null) { maybeNextBreak.getValue().setPreviousSequence(splitBag); } } Break<Value_, Difference_> getBreakBefore(ComparableValue<Value_, Point_> item) { return startItemToPreviousBreak.get(item); } Break<Value_, Difference_> getBreakAfter(ComparableValue<Value_, Point_> item) { var entry = startItemToPreviousBreak.higherEntry(item); if (entry != null) { return entry.getValue(); } return null; } NavigableMap<ComparableValue<Value_, Point_>, Value_> getComparableItems(ComparableValue<Value_, Point_> firstKey, ComparableValue<Value_, Point_> lastKey) { return itemMap.subMap(firstKey, true, lastKey, true); } ComparableValue<Value_, Point_> getFirstItem() { return firstItem; } ComparableValue<Value_, Point_> getLastItem() { return lastItem; } private boolean isFirstSuccessorOfSecond(ComparableValue<Value_, Point_> first, ComparableValue<Value_, Point_> second) { var difference = differenceFunction.apply(second.index(), first.index()); return isInNaturalOrderAndHashOrderIfEqual(zeroDifference, second.value(), difference, first.value()) && difference.compareTo(maxDifference) <= 0; } @Override public String toString() { return "Sequences {" + "sequenceList=" + getConsecutiveSequences() + ", breakList=" + getBreaks() + '}'; } private final static class ValueCount<Value_> { private final Value_ value; private int count; public ValueCount(Value_ value) { this.value = value; count = 1; } } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/CustomCollectionUndoableActionable.java
package ai.timefold.solver.core.impl.score.stream; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.IntFunction; public final class CustomCollectionUndoableActionable<Mapped_, Result_ extends Collection<Mapped_>> implements UndoableActionable<Mapped_, Result_> { private final IntFunction<Result_> collectionFunction; private final List<Mapped_> resultList = new ArrayList<>(); public CustomCollectionUndoableActionable(IntFunction<Result_> collectionFunction) { this.collectionFunction = collectionFunction; } @Override public Runnable insert(Mapped_ result) { resultList.add(result); return () -> resultList.remove(result); } @Override public Result_ result() { Result_ out = collectionFunction.apply(resultList.size()); if (resultList.isEmpty()) { // Avoid exception if out is an immutable collection return out; } out.addAll(resultList); return out; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/IntAverageCalculator.java
package ai.timefold.solver.core.impl.score.stream; public final class IntAverageCalculator implements IntCalculator<Double> { int count = 0; int sum = 0; @Override public void insert(int input) { count++; sum += input; } @Override public void retract(int input) { count--; sum -= input; } @Override public Double result() { if (count == 0) { return null; } return sum / (double) count; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/IntCalculator.java
package ai.timefold.solver.core.impl.score.stream; public sealed interface IntCalculator<Output_> permits IntAverageCalculator, IntSumCalculator { void insert(int input); void retract(int input); Output_ result(); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/IntCounter.java
package ai.timefold.solver.core.impl.score.stream; public final class IntCounter { private int count; public void increment() { count++; } public void decrement() { count--; } public int result() { return count; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/IntDistinctCountCalculator.java
package ai.timefold.solver.core.impl.score.stream; import java.util.HashMap; import java.util.Map; import ai.timefold.solver.core.impl.util.MutableInt; public final class IntDistinctCountCalculator<Input_> implements ObjectCalculator<Input_, Integer> { private final Map<Input_, MutableInt> countMap = new HashMap<>(); @Override public void insert(Input_ input) { countMap.computeIfAbsent(input, ignored -> new MutableInt()).increment(); } @Override public void retract(Input_ input) { if (countMap.get(input).decrement() == 0) { countMap.remove(input); } } @Override public Integer result() { return countMap.size(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/IntSumCalculator.java
package ai.timefold.solver.core.impl.score.stream; public final class IntSumCalculator implements IntCalculator<Integer> { int sum = 0; @Override public void insert(int input) { sum += input; } @Override public void retract(int input) { sum -= input; } @Override public Integer result() { return sum; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/JoinerService.java
package ai.timefold.solver.core.impl.score.stream; import java.util.ServiceLoader; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Function; import ai.timefold.solver.core.api.function.PentaPredicate; import ai.timefold.solver.core.api.function.QuadFunction; import ai.timefold.solver.core.api.function.QuadPredicate; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.api.function.TriPredicate; import ai.timefold.solver.core.api.score.stream.bi.BiJoiner; import ai.timefold.solver.core.api.score.stream.penta.PentaJoiner; import ai.timefold.solver.core.api.score.stream.quad.QuadJoiner; import ai.timefold.solver.core.api.score.stream.tri.TriJoiner; /** * Used via {@link ServiceLoader} so that the constraint streams implementation can be fully split from its API, * without getting split packages or breaking backwards compatibility. */ public interface JoinerService { /* * TODO In 9.x, bring API and impl to the same JAR, avoiding split packages. * This will make this SPI unnecessary. */ <A, B> BiJoiner<A, B> newBiJoiner(BiPredicate<A, B> filter); <A, B, Property_> BiJoiner<A, B> newBiJoiner(Function<A, Property_> leftMapping, JoinerType joinerType, Function<B, Property_> rightMapping); <A, B, C> TriJoiner<A, B, C> newTriJoiner(TriPredicate<A, B, C> filter); <A, B, C, Property_> TriJoiner<A, B, C> newTriJoiner(BiFunction<A, B, Property_> leftMapping, JoinerType joinerType, Function<C, Property_> rightMapping); <A, B, C, D> QuadJoiner<A, B, C, D> newQuadJoiner(QuadPredicate<A, B, C, D> filter); <A, B, C, D, Property_> QuadJoiner<A, B, C, D> newQuadJoiner(TriFunction<A, B, C, Property_> leftMapping, JoinerType joinerType, Function<D, Property_> rightMapping); <A, B, C, D, E> PentaJoiner<A, B, C, D, E> newPentaJoiner(PentaPredicate<A, B, C, D, E> filter); <A, B, C, D, E, Property_> PentaJoiner<A, B, C, D, E> newPentaJoiner(QuadFunction<A, B, C, D, Property_> leftMapping, JoinerType joinerType, Function<E, Property_> rightMapping); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/JoinerSupport.java
package ai.timefold.solver.core.impl.score.stream; import java.util.Iterator; import java.util.ServiceLoader; public final class JoinerSupport { private static volatile JoinerService INSTANCE; public static JoinerService getJoinerService() { if (INSTANCE == null) { synchronized (JoinerSupport.class) { if (INSTANCE == null) { Iterator<JoinerService> servicesIterator = ServiceLoader.load(JoinerService.class).iterator(); if (!servicesIterator.hasNext()) { throw new IllegalStateException("Joiners not found.\n" + "Maybe include ai.timefold.solver:timefold-solver-constraint-streams dependency in your project?\n" + "Maybe ensure your uberjar bundles META-INF/services from included JAR files?"); } else { INSTANCE = servicesIterator.next(); } } } } return INSTANCE; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/JoinerType.java
package ai.timefold.solver.core.impl.score.stream; import java.util.Collection; import java.util.Objects; import java.util.function.BiPredicate; public enum JoinerType { EQUAL(Objects::equals), LESS_THAN((a, b) -> ((Comparable) a).compareTo(b) < 0), LESS_THAN_OR_EQUAL((a, b) -> ((Comparable) a).compareTo(b) <= 0), GREATER_THAN((a, b) -> ((Comparable) a).compareTo(b) > 0), GREATER_THAN_OR_EQUAL((a, b) -> ((Comparable) a).compareTo(b) >= 0), CONTAINING((a, b) -> ((Collection) a).contains(b)), INTERSECTING((a, b) -> intersecting((Collection) a, (Collection) b)), DISJOINT((a, b) -> disjoint((Collection) a, (Collection) b)); private final BiPredicate<Object, Object> matcher; JoinerType(BiPredicate<Object, Object> matcher) { this.matcher = matcher; } public JoinerType flip() { switch (this) { case LESS_THAN: return GREATER_THAN; case LESS_THAN_OR_EQUAL: return GREATER_THAN_OR_EQUAL; case GREATER_THAN: return LESS_THAN; case GREATER_THAN_OR_EQUAL: return LESS_THAN_OR_EQUAL; default: throw new IllegalStateException("The joinerType (" + this + ") cannot be flipped."); } } public boolean matches(Object left, Object right) { try { return matcher.test(left, right); } catch (Exception e) { // For easier debugging, in the absence of pointing to a specific constraint. throw new IllegalStateException( "Joiner (" + this + ") threw an exception matching left (" + left + ") and right (" + right + ") objects.", e); } } private static boolean disjoint(Collection<?> leftCollection, Collection<?> rightCollection) { return leftCollection.stream().noneMatch(rightCollection::contains) && rightCollection.stream().noneMatch(leftCollection::contains); } private static boolean intersecting(Collection<?> leftCollection, Collection<?> rightCollection) { return leftCollection.stream().anyMatch(rightCollection::contains) || rightCollection.stream().anyMatch(leftCollection::contains); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/ListUndoableActionable.java
package ai.timefold.solver.core.impl.score.stream; import java.util.ArrayList; import java.util.List; public final class ListUndoableActionable<Mapped_> implements UndoableActionable<Mapped_, List<Mapped_>> { private final List<Mapped_> resultList = new ArrayList<>(); @Override public Runnable insert(Mapped_ result) { resultList.add(result); return () -> resultList.remove(result); } @Override public List<Mapped_> result() { return resultList; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/LongAverageCalculator.java
package ai.timefold.solver.core.impl.score.stream; public final class LongAverageCalculator implements LongCalculator<Double> { long count = 0; long sum = 0; @Override public void insert(long input) { count++; sum += input; } @Override public void retract(long input) { count--; sum -= input; } @Override public Double result() { if (count == 0) { return null; } return sum / (double) count; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/LongCalculator.java
package ai.timefold.solver.core.impl.score.stream; public sealed interface LongCalculator<Output_> permits LongAverageCalculator, LongSumCalculator { void insert(long input); void retract(long input); Output_ result(); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/LongCounter.java
package ai.timefold.solver.core.impl.score.stream; public final class LongCounter { private long count; public void increment() { count++; } public void decrement() { count--; } public long result() { return count; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/LongDistinctCountCalculator.java
package ai.timefold.solver.core.impl.score.stream; import java.util.HashMap; import java.util.Map; import ai.timefold.solver.core.impl.util.MutableInt; public final class LongDistinctCountCalculator<Input_> implements ObjectCalculator<Input_, Long> { private final Map<Input_, MutableInt> countMap = new HashMap<>(); @Override public void insert(Input_ input) { countMap.computeIfAbsent(input, ignored -> new MutableInt()).increment(); } @Override public void retract(Input_ input) { if (countMap.get(input).decrement() == 0) { countMap.remove(input); } } @Override public Long result() { return (long) countMap.size(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/LongSumCalculator.java
package ai.timefold.solver.core.impl.score.stream; public final class LongSumCalculator implements LongCalculator<Long> { long sum = 0; @Override public void insert(long input) { sum += input; } @Override public void retract(long input) { sum -= input; } @Override public Long result() { return sum; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/MapUndoableActionable.java
package ai.timefold.solver.core.impl.score.stream; import java.util.Map; import java.util.Set; import java.util.function.BinaryOperator; import java.util.function.IntFunction; import java.util.function.Supplier; import ai.timefold.solver.core.impl.util.Pair; public final class MapUndoableActionable<Key_, Value_, ResultValue_, Result_ extends Map<Key_, ResultValue_>> implements UndoableActionable<Pair<Key_, Value_>, Result_> { ToMapResultContainer<Key_, Value_, ResultValue_, Result_> container; private MapUndoableActionable(ToMapResultContainer<Key_, Value_, ResultValue_, Result_> container) { this.container = container; } public static <Key_, Value_, Set_ extends Set<Value_>, Result_ extends Map<Key_, Set_>> MapUndoableActionable<Key_, Value_, Set_, Result_> multiMap( Supplier<Result_> resultSupplier, IntFunction<Set_> setFunction) { return new MapUndoableActionable<>(new ToMultiMapResultContainer<>(resultSupplier, setFunction)); } public static <Key_, Value_, Result_ extends Map<Key_, Value_>> MapUndoableActionable<Key_, Value_, Value_, Result_> mergeMap( Supplier<Result_> resultSupplier, BinaryOperator<Value_> mergeFunction) { return new MapUndoableActionable<>(new ToSimpleMapResultContainer<>(resultSupplier, mergeFunction)); } @Override public Runnable insert(Pair<Key_, Value_> entry) { container.add(entry.key(), entry.value()); return () -> container.remove(entry.key(), entry.value()); } @Override public Result_ result() { return container.getResult(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/MinMaxUndoableActionable.java
package ai.timefold.solver.core.impl.score.stream; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.Map; import java.util.NavigableMap; import java.util.TreeMap; import java.util.function.Function; import ai.timefold.solver.core.impl.util.ConstantLambdaUtils; import ai.timefold.solver.core.impl.util.MutableInt; public final class MinMaxUndoableActionable<Result_, Property_> implements UndoableActionable<Result_, Result_> { private final boolean isMin; private final NavigableMap<Property_, Map<Result_, MutableInt>> propertyToItemCountMap; private final Function<? super Result_, ? extends Property_> propertyFunction; private MinMaxUndoableActionable(boolean isMin, NavigableMap<Property_, Map<Result_, MutableInt>> propertyToItemCountMap, Function<? super Result_, ? extends Property_> propertyFunction) { this.isMin = isMin; this.propertyToItemCountMap = propertyToItemCountMap; this.propertyFunction = propertyFunction; } public static <Result extends Comparable<? super Result>> MinMaxUndoableActionable<Result, Result> minCalculator() { return new MinMaxUndoableActionable<>(true, new TreeMap<>(), ConstantLambdaUtils.identity()); } public static <Result extends Comparable<? super Result>> MinMaxUndoableActionable<Result, Result> maxCalculator() { return new MinMaxUndoableActionable<>(false, new TreeMap<>(), ConstantLambdaUtils.identity()); } public static <Result> MinMaxUndoableActionable<Result, Result> minCalculator(Comparator<? super Result> comparator) { return new MinMaxUndoableActionable<>(true, new TreeMap<>(comparator), ConstantLambdaUtils.identity()); } public static <Result> MinMaxUndoableActionable<Result, Result> maxCalculator(Comparator<? super Result> comparator) { return new MinMaxUndoableActionable<>(false, new TreeMap<>(comparator), ConstantLambdaUtils.identity()); } public static <Result, Property extends Comparable<? super Property>> MinMaxUndoableActionable<Result, Property> minCalculator( Function<? super Result, ? extends Property> propertyMapper) { return new MinMaxUndoableActionable<>(true, new TreeMap<>(), propertyMapper); } public static <Result, Property extends Comparable<? super Property>> MinMaxUndoableActionable<Result, Property> maxCalculator( Function<? super Result, ? extends Property> propertyMapper) { return new MinMaxUndoableActionable<>(false, new TreeMap<>(), propertyMapper); } @Override public Runnable insert(Result_ item) { Property_ key = propertyFunction.apply(item); Map<Result_, MutableInt> itemCountMap = propertyToItemCountMap.computeIfAbsent(key, ignored -> new LinkedHashMap<>()); MutableInt count = itemCountMap.computeIfAbsent(item, ignored -> new MutableInt()); count.increment(); return () -> { if (count.decrement() == 0) { itemCountMap.remove(item); if (itemCountMap.isEmpty()) { propertyToItemCountMap.remove(key); } } }; } @Override public Result_ result() { if (propertyToItemCountMap.isEmpty()) { return null; } return isMin ? getFirstKey(propertyToItemCountMap.firstEntry().getValue()) : getFirstKey(propertyToItemCountMap.lastEntry().getValue()); } private static <Key_> Key_ getFirstKey(Map<Key_, ?> map) { return map.keySet().iterator().next(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/ObjectCalculator.java
package ai.timefold.solver.core.impl.score.stream; public sealed interface ObjectCalculator<Input_, Output_> permits IntDistinctCountCalculator, LongDistinctCountCalculator, ReferenceAverageCalculator, ReferenceSumCalculator, SequenceCalculator { void insert(Input_ input); void retract(Input_ input); Output_ result(); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/ReferenceAverageCalculator.java
package ai.timefold.solver.core.impl.score.stream; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.time.Duration; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Supplier; public final class ReferenceAverageCalculator<Input_, Output_> implements ObjectCalculator<Input_, Output_> { int count = 0; Input_ sum; final BinaryOperator<Input_> adder; final BinaryOperator<Input_> subtractor; final BiFunction<Input_, Integer, Output_> divider; private final static Supplier<ReferenceAverageCalculator<BigDecimal, BigDecimal>> BIG_DECIMAL = () -> new ReferenceAverageCalculator<>(BigDecimal.ZERO, BigDecimal::add, BigDecimal::subtract, (sum, count) -> sum.divide(BigDecimal.valueOf(count), RoundingMode.HALF_EVEN)); private final static Supplier<ReferenceAverageCalculator<BigInteger, BigDecimal>> BIG_INTEGER = () -> new ReferenceAverageCalculator<>(BigInteger.ZERO, BigInteger::add, BigInteger::subtract, (sum, count) -> new BigDecimal(sum).divide(BigDecimal.valueOf(count), RoundingMode.HALF_EVEN)); private final static Supplier<ReferenceAverageCalculator<Duration, Duration>> DURATION = () -> new ReferenceAverageCalculator<>(Duration.ZERO, Duration::plus, Duration::minus, (sum, count) -> { long nanos = sum.toNanos(); return Duration.ofNanos(nanos / count); }); public ReferenceAverageCalculator(Input_ zero, BinaryOperator<Input_> adder, BinaryOperator<Input_> subtractor, BiFunction<Input_, Integer, Output_> divider) { this.sum = zero; this.adder = adder; this.subtractor = subtractor; this.divider = divider; } public static Supplier<ReferenceAverageCalculator<BigDecimal, BigDecimal>> bigDecimal() { return BIG_DECIMAL; } public static Supplier<ReferenceAverageCalculator<BigInteger, BigDecimal>> bigInteger() { return BIG_INTEGER; } public static Supplier<ReferenceAverageCalculator<Duration, Duration>> duration() { return DURATION; } @Override public void insert(Input_ input) { count++; sum = adder.apply(sum, input); } @Override public void retract(Input_ input) { count--; sum = subtractor.apply(sum, input); } @Override public Output_ result() { if (count == 0) { return null; } return divider.apply(sum, count); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/ReferenceSumCalculator.java
package ai.timefold.solver.core.impl.score.stream; import java.util.function.BinaryOperator; public final class ReferenceSumCalculator<Result_> implements ObjectCalculator<Result_, Result_> { private Result_ current; private final BinaryOperator<Result_> adder; private final BinaryOperator<Result_> subtractor; public ReferenceSumCalculator(Result_ current, BinaryOperator<Result_> adder, BinaryOperator<Result_> subtractor) { this.current = current; this.adder = adder; this.subtractor = subtractor; } @Override public void insert(Result_ input) { current = adder.apply(current, input); } @Override public void retract(Result_ input) { current = subtractor.apply(current, input); } @Override public Result_ result() { return current; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/SequenceCalculator.java
package ai.timefold.solver.core.impl.score.stream; import java.util.Objects; import java.util.function.ToIntFunction; import ai.timefold.solver.core.api.score.stream.common.SequenceChain; public final class SequenceCalculator<Result_> implements ObjectCalculator<Result_, SequenceChain<Result_, Integer>> { private final ConsecutiveSetTree<Result_, Integer, Integer> context = new ConsecutiveSetTree<>( (Integer a, Integer b) -> b - a, Integer::sum, 1, 0); private final ToIntFunction<Result_> indexMap; public SequenceCalculator(ToIntFunction<Result_> indexMap) { this.indexMap = Objects.requireNonNull(indexMap); } @Override public void insert(Result_ result) { var value = indexMap.applyAsInt(result); context.add(result, value); } @Override public void retract(Result_ result) { context.remove(result); } @Override public ConsecutiveSetTree<Result_, Integer, Integer> result() { return context; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/SequenceImpl.java
package ai.timefold.solver.core.impl.score.stream; import java.util.Collection; import java.util.Collections; import java.util.NavigableMap; import java.util.stream.Collectors; import ai.timefold.solver.core.api.score.stream.common.Break; import ai.timefold.solver.core.api.score.stream.common.Sequence; /** * When adding fields, remember to add them to the JSON serialization code as well, if you want them exposed. * * @param <Value_> * @param <Point_> * @param <Difference_> */ final class SequenceImpl<Value_, Point_ extends Comparable<Point_>, Difference_ extends Comparable<Difference_>> implements Sequence<Value_, Difference_> { private final ConsecutiveSetTree<Value_, Point_, Difference_> sourceTree; ComparableValue<Value_, Point_> firstItem; ComparableValue<Value_, Point_> lastItem; // Memorized calculations private Difference_ length; private NavigableMap<ComparableValue<Value_, Point_>, Value_> comparableItems; private Collection<Value_> items; SequenceImpl(ConsecutiveSetTree<Value_, Point_, Difference_> sourceTree, ComparableValue<Value_, Point_> item) { this(sourceTree, item, item); } SequenceImpl(ConsecutiveSetTree<Value_, Point_, Difference_> sourceTree, ComparableValue<Value_, Point_> firstItem, ComparableValue<Value_, Point_> lastItem) { this.sourceTree = sourceTree; this.firstItem = firstItem; this.lastItem = lastItem; length = null; comparableItems = null; items = null; } @Override public Value_ getFirstItem() { return firstItem.value(); } @Override public Value_ getLastItem() { return lastItem.value(); } @Override public Break<Value_, Difference_> getPreviousBreak() { return sourceTree.getBreakBefore(firstItem); } @Override public Break<Value_, Difference_> getNextBreak() { return sourceTree.getBreakAfter(lastItem); } @Override public boolean isFirst() { return firstItem == sourceTree.getFirstItem(); } @Override public boolean isLast() { return lastItem == sourceTree.getLastItem(); } @Override public Collection<Value_> getItems() { if (items == null) { return items = getComparableItems().values(); } return Collections.unmodifiableCollection(items); } NavigableMap<ComparableValue<Value_, Point_>, Value_> getComparableItems() { if (comparableItems == null) { return comparableItems = sourceTree.getComparableItems(firstItem, lastItem); } return comparableItems; } @Override public int getCount() { return getComparableItems().size(); } @Override public Difference_ getLength() { if (length == null) { // memoize length for later calls // (assignment returns the right hand side) return length = sourceTree.sequenceLengthFunction.apply(firstItem.index(), lastItem.index()); } return length; } Difference_ computeDifference(SequenceImpl<Value_, Point_, Difference_> to) { return sourceTree.differenceFunction.apply(this.lastItem.index(), to.firstItem.index()); } void setStart(ComparableValue<Value_, Point_> item) { firstItem = item; invalidate(); } void setEnd(ComparableValue<Value_, Point_> item) { lastItem = item; invalidate(); } // Called when start or end are removed; length // need to be invalidated void invalidate() { length = null; comparableItems = null; items = null; } SequenceImpl<Value_, Point_, Difference_> split(ComparableValue<Value_, Point_> fromElement) { var itemSet = getComparableItems(); var newSequenceStart = itemSet.higherKey(fromElement); var newSequenceEnd = lastItem; setEnd(itemSet.lowerKey(fromElement)); return new SequenceImpl<>(sourceTree, newSequenceStart, newSequenceEnd); } // This Sequence is ALWAYS before other Sequence void merge(SequenceImpl<Value_, Point_, Difference_> other) { lastItem = other.lastItem; invalidate(); } @Override public String toString() { return getItems().stream() .map(Object::toString) .collect(Collectors.joining(", ", "Sequence [", "]")); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/SetUndoableActionable.java
package ai.timefold.solver.core.impl.score.stream; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import ai.timefold.solver.core.impl.util.MutableInt; public final class SetUndoableActionable<Mapped_> implements UndoableActionable<Mapped_, Set<Mapped_>> { final Map<Mapped_, MutableInt> itemToCount = new LinkedHashMap<>(); @Override public Runnable insert(Mapped_ result) { MutableInt count = itemToCount.computeIfAbsent(result, ignored -> new MutableInt()); count.increment(); return () -> { if (count.decrement() == 0) { itemToCount.remove(result); } }; } @Override public Set<Mapped_> result() { return itemToCount.keySet(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/SortedSetUndoableActionable.java
package ai.timefold.solver.core.impl.score.stream; import java.util.Comparator; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.SortedSet; import java.util.TreeMap; import ai.timefold.solver.core.impl.util.MutableInt; public final class SortedSetUndoableActionable<Mapped_> implements UndoableActionable<Mapped_, SortedSet<Mapped_>> { private final NavigableMap<Mapped_, MutableInt> itemToCount; private SortedSetUndoableActionable(NavigableMap<Mapped_, MutableInt> itemToCount) { this.itemToCount = itemToCount; } public static <Result> SortedSetUndoableActionable<Result> orderBy(Comparator<? super Result> comparator) { return new SortedSetUndoableActionable<>(new TreeMap<>(comparator)); } @Override public Runnable insert(Mapped_ result) { MutableInt count = itemToCount.computeIfAbsent(result, ignored -> new MutableInt()); count.increment(); return () -> { if (count.decrement() == 0) { itemToCount.remove(result); } }; } @Override public NavigableSet<Mapped_> result() { return itemToCount.navigableKeySet(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/ToMapPerKeyCounter.java
package ai.timefold.solver.core.impl.score.stream; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.BinaryOperator; import java.util.stream.Stream; public final class ToMapPerKeyCounter<Value_> { private final Map<Value_, Long> counts = new LinkedHashMap<>(0); public long add(Value_ value) { return counts.compute(value, (k, currentCount) -> { if (currentCount == null) { return 1L; } else { return currentCount + 1; } }); } public long remove(Value_ value) { Long newCount = counts.compute(value, (k, currentCount) -> { if (currentCount > 1L) { return currentCount - 1; } else { return null; } }); return newCount == null ? 0L : newCount; } public Value_ merge(BinaryOperator<Value_> mergeFunction) { // Rebuilding the value from the collection is not incremental. // The impact is negligible, assuming there are not too many values for the same key. return counts.entrySet() .stream() .flatMap(e -> Stream.generate(e::getKey).limit(e.getValue())) .reduce(mergeFunction) .orElseThrow(() -> new IllegalStateException("Impossible state: Should have had at least one value.")); } public boolean isEmpty() { return counts.isEmpty(); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/ToMapResultContainer.java
package ai.timefold.solver.core.impl.score.stream; import java.util.Map; public sealed interface ToMapResultContainer<Key_, Value_, ResultValue_, Result_ extends Map<Key_, ResultValue_>> permits ToMultiMapResultContainer, ToSimpleMapResultContainer { void add(Key_ key, Value_ value); void remove(Key_ key, Value_ value); Result_ getResult(); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/ToMultiMapResultContainer.java
package ai.timefold.solver.core.impl.score.stream; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.IntFunction; import java.util.function.Supplier; public final class ToMultiMapResultContainer<Key_, Value_, Set_ extends Set<Value_>, Result_ extends Map<Key_, Set_>> implements ToMapResultContainer<Key_, Value_, Set_, Result_> { private final Supplier<Set_> setSupplier; private final Result_ result; private final Map<Key_, ToMapPerKeyCounter<Value_>> valueCounts = new HashMap<>(0); public ToMultiMapResultContainer(Supplier<Result_> resultSupplier, IntFunction<Set_> setFunction) { IntFunction<Set_> nonNullSetFunction = Objects.requireNonNull(setFunction); this.setSupplier = () -> nonNullSetFunction.apply(0); this.result = Objects.requireNonNull(resultSupplier).get(); } public ToMultiMapResultContainer(IntFunction<Result_> resultFunction, IntFunction<Set_> setFunction) { IntFunction<Set_> nonNullSetFunction = Objects.requireNonNull(setFunction); this.setSupplier = () -> nonNullSetFunction.apply(0); this.result = Objects.requireNonNull(resultFunction).apply(0); } @Override public void add(Key_ key, Value_ value) { ToMapPerKeyCounter<Value_> counter = valueCounts.computeIfAbsent(key, k -> new ToMapPerKeyCounter<>()); counter.add(value); result.computeIfAbsent(key, k -> setSupplier.get()) .add(value); } @Override public void remove(Key_ key, Value_ value) { ToMapPerKeyCounter<Value_> counter = valueCounts.get(key); long newCount = counter.remove(value); if (newCount == 0) { result.get(key).remove(value); } if (counter.isEmpty()) { valueCounts.remove(key); result.remove(key); } } @Override public Result_ getResult() { return result; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/ToSimpleMapResultContainer.java
package ai.timefold.solver.core.impl.score.stream; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.function.BinaryOperator; import java.util.function.IntFunction; import java.util.function.Supplier; public final class ToSimpleMapResultContainer<Key_, Value_, Result_ extends Map<Key_, Value_>> implements ToMapResultContainer<Key_, Value_, Value_, Result_> { private final BinaryOperator<Value_> mergeFunction; private final Result_ result; private final Map<Key_, ToMapPerKeyCounter<Value_>> valueCounts = new HashMap<>(0); public ToSimpleMapResultContainer(Supplier<Result_> resultSupplier, BinaryOperator<Value_> mergeFunction) { this.mergeFunction = Objects.requireNonNull(mergeFunction); this.result = Objects.requireNonNull(resultSupplier).get(); } public ToSimpleMapResultContainer(IntFunction<Result_> resultSupplier, BinaryOperator<Value_> mergeFunction) { this.mergeFunction = Objects.requireNonNull(mergeFunction); this.result = Objects.requireNonNull(resultSupplier).apply(0); } @Override public void add(Key_ key, Value_ value) { ToMapPerKeyCounter<Value_> counter = valueCounts.computeIfAbsent(key, k -> new ToMapPerKeyCounter<>()); long newCount = counter.add(value); if (newCount == 1L) { result.put(key, value); } else { result.put(key, counter.merge(mergeFunction)); } } @Override public void remove(Key_ key, Value_ value) { ToMapPerKeyCounter<Value_> counter = valueCounts.get(key); long newCount = counter.remove(value); if (newCount == 0L) { result.remove(key); } else { result.put(key, counter.merge(mergeFunction)); } if (counter.isEmpty()) { valueCounts.remove(key); } } @Override public Result_ getResult() { return result; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/UndoableActionable.java
package ai.timefold.solver.core.impl.score.stream; public sealed interface UndoableActionable<Input_, Output_> permits CustomCollectionUndoableActionable, ListUndoableActionable, MapUndoableActionable, MinMaxUndoableActionable, SetUndoableActionable, SortedSetUndoableActionable { Runnable insert(Input_ input); Output_ result(); }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/AndThenBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Objects; import java.util.function.Function; import java.util.function.Supplier; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.api.score.stream.bi.BiConstraintCollector; final class AndThenBiCollector<A, B, ResultContainer_, Intermediate_, Result_> implements BiConstraintCollector<A, B, ResultContainer_, Result_> { private final BiConstraintCollector<A, B, ResultContainer_, Intermediate_> delegate; private final Function<Intermediate_, Result_> mappingFunction; AndThenBiCollector(BiConstraintCollector<A, B, ResultContainer_, Intermediate_> delegate, Function<Intermediate_, Result_> mappingFunction) { this.delegate = Objects.requireNonNull(delegate); this.mappingFunction = Objects.requireNonNull(mappingFunction); } @Override public Supplier<ResultContainer_> supplier() { return delegate.supplier(); } @Override public TriFunction<ResultContainer_, A, B, Runnable> accumulator() { return delegate.accumulator(); } @Override public Function<ResultContainer_, Result_> finisher() { var finisher = delegate.finisher(); return container -> mappingFunction.apply(finisher.apply(container)); } @Override public boolean equals(Object o) { if (o instanceof AndThenBiCollector<?, ?, ?, ?, ?> other) { return Objects.equals(delegate, other.delegate) && Objects.equals(mappingFunction, other.mappingFunction); } return false; } @Override public int hashCode() { return Objects.hash(delegate, mappingFunction); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/AverageIntBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.function.Supplier; import java.util.function.ToIntBiFunction; import ai.timefold.solver.core.impl.score.stream.IntAverageCalculator; final class AverageIntBiCollector<A, B> extends IntCalculatorBiCollector<A, B, Double, IntAverageCalculator> { AverageIntBiCollector(ToIntBiFunction<? super A, ? super B> mapper) { super(mapper); } @Override public Supplier<IntAverageCalculator> supplier() { return IntAverageCalculator::new; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/AverageLongBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.function.Supplier; import java.util.function.ToLongBiFunction; import ai.timefold.solver.core.impl.score.stream.LongAverageCalculator; final class AverageLongBiCollector<A, B> extends LongCalculatorBiCollector<A, B, Double, LongAverageCalculator> { AverageLongBiCollector(ToLongBiFunction<? super A, ? super B> mapper) { super(mapper); } @Override public Supplier<LongAverageCalculator> supplier() { return LongAverageCalculator::new; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/AverageReferenceBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Supplier; import ai.timefold.solver.core.impl.score.stream.ReferenceAverageCalculator; final class AverageReferenceBiCollector<A, B, Mapped_, Average_> extends ObjectCalculatorBiCollector<A, B, Mapped_, Average_, ReferenceAverageCalculator<Mapped_, Average_>> { private final Supplier<ReferenceAverageCalculator<Mapped_, Average_>> calculatorSupplier; AverageReferenceBiCollector(BiFunction<? super A, ? super B, ? extends Mapped_> mapper, Supplier<ReferenceAverageCalculator<Mapped_, Average_>> calculatorSupplier) { super(mapper); this.calculatorSupplier = calculatorSupplier; } @Override public Supplier<ReferenceAverageCalculator<Mapped_, Average_>> supplier() { return calculatorSupplier; } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; AverageReferenceBiCollector<?, ?, ?, ?> that = (AverageReferenceBiCollector<?, ?, ?, ?>) object; return Objects.equals(calculatorSupplier, that.calculatorSupplier); } @Override public int hashCode() { return Objects.hash(super.hashCode(), calculatorSupplier); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/ComposeFourBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Objects; import java.util.function.Function; import java.util.function.Supplier; import ai.timefold.solver.core.api.function.QuadFunction; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.api.score.stream.bi.BiConstraintCollector; import ai.timefold.solver.core.impl.util.Quadruple; final class ComposeFourBiCollector<A, B, ResultHolder1_, ResultHolder2_, ResultHolder3_, ResultHolder4_, Result1_, Result2_, Result3_, Result4_, Result_> implements BiConstraintCollector<A, B, Quadruple<ResultHolder1_, ResultHolder2_, ResultHolder3_, ResultHolder4_>, Result_> { private final BiConstraintCollector<A, B, ResultHolder1_, Result1_> first; private final BiConstraintCollector<A, B, ResultHolder2_, Result2_> second; private final BiConstraintCollector<A, B, ResultHolder3_, Result3_> third; private final BiConstraintCollector<A, B, ResultHolder4_, Result4_> fourth; private final QuadFunction<Result1_, Result2_, Result3_, Result4_, Result_> composeFunction; private final Supplier<ResultHolder1_> firstSupplier; private final Supplier<ResultHolder2_> secondSupplier; private final Supplier<ResultHolder3_> thirdSupplier; private final Supplier<ResultHolder4_> fourthSupplier; private final TriFunction<ResultHolder1_, A, B, Runnable> firstAccumulator; private final TriFunction<ResultHolder2_, A, B, Runnable> secondAccumulator; private final TriFunction<ResultHolder3_, A, B, Runnable> thirdAccumulator; private final TriFunction<ResultHolder4_, A, B, Runnable> fourthAccumulator; private final Function<ResultHolder1_, Result1_> firstFinisher; private final Function<ResultHolder2_, Result2_> secondFinisher; private final Function<ResultHolder3_, Result3_> thirdFinisher; private final Function<ResultHolder4_, Result4_> fourthFinisher; ComposeFourBiCollector(BiConstraintCollector<A, B, ResultHolder1_, Result1_> first, BiConstraintCollector<A, B, ResultHolder2_, Result2_> second, BiConstraintCollector<A, B, ResultHolder3_, Result3_> third, BiConstraintCollector<A, B, ResultHolder4_, Result4_> fourth, QuadFunction<Result1_, Result2_, Result3_, Result4_, Result_> composeFunction) { this.first = first; this.second = second; this.third = third; this.fourth = fourth; this.composeFunction = composeFunction; this.firstSupplier = first.supplier(); this.secondSupplier = second.supplier(); this.thirdSupplier = third.supplier(); this.fourthSupplier = fourth.supplier(); this.firstAccumulator = first.accumulator(); this.secondAccumulator = second.accumulator(); this.thirdAccumulator = third.accumulator(); this.fourthAccumulator = fourth.accumulator(); this.firstFinisher = first.finisher(); this.secondFinisher = second.finisher(); this.thirdFinisher = third.finisher(); this.fourthFinisher = fourth.finisher(); } @Override public Supplier<Quadruple<ResultHolder1_, ResultHolder2_, ResultHolder3_, ResultHolder4_>> supplier() { return () -> { ResultHolder1_ a = firstSupplier.get(); ResultHolder2_ b = secondSupplier.get(); ResultHolder3_ c = thirdSupplier.get(); return new Quadruple<>(a, b, c, fourthSupplier.get()); }; } @Override public TriFunction<Quadruple<ResultHolder1_, ResultHolder2_, ResultHolder3_, ResultHolder4_>, A, B, Runnable> accumulator() { return (resultHolder, a, b) -> composeUndo(firstAccumulator.apply(resultHolder.a(), a, b), secondAccumulator.apply(resultHolder.b(), a, b), thirdAccumulator.apply(resultHolder.c(), a, b), fourthAccumulator.apply(resultHolder.d(), a, b)); } private static Runnable composeUndo(Runnable first, Runnable second, Runnable third, Runnable fourth) { return () -> { first.run(); second.run(); third.run(); fourth.run(); }; } @Override public Function<Quadruple<ResultHolder1_, ResultHolder2_, ResultHolder3_, ResultHolder4_>, Result_> finisher() { return resultHolder -> composeFunction.apply(firstFinisher.apply(resultHolder.a()), secondFinisher.apply(resultHolder.b()), thirdFinisher.apply(resultHolder.c()), fourthFinisher.apply(resultHolder.d())); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; var that = (ComposeFourBiCollector<?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?>) object; return Objects.equals(first, that.first) && Objects.equals(second, that.second) && Objects.equals(third, that.third) && Objects.equals(fourth, that.fourth) && Objects.equals(composeFunction, that.composeFunction); } @Override public int hashCode() { return Objects.hash(first, second, third, fourth, composeFunction); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/ComposeThreeBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Objects; import java.util.function.Function; import java.util.function.Supplier; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.api.score.stream.bi.BiConstraintCollector; import ai.timefold.solver.core.impl.util.Triple; final class ComposeThreeBiCollector<A, B, ResultHolder1_, ResultHolder2_, ResultHolder3_, Result1_, Result2_, Result3_, Result_> implements BiConstraintCollector<A, B, Triple<ResultHolder1_, ResultHolder2_, ResultHolder3_>, Result_> { private final BiConstraintCollector<A, B, ResultHolder1_, Result1_> first; private final BiConstraintCollector<A, B, ResultHolder2_, Result2_> second; private final BiConstraintCollector<A, B, ResultHolder3_, Result3_> third; private final TriFunction<Result1_, Result2_, Result3_, Result_> composeFunction; private final Supplier<ResultHolder1_> firstSupplier; private final Supplier<ResultHolder2_> secondSupplier; private final Supplier<ResultHolder3_> thirdSupplier; private final TriFunction<ResultHolder1_, A, B, Runnable> firstAccumulator; private final TriFunction<ResultHolder2_, A, B, Runnable> secondAccumulator; private final TriFunction<ResultHolder3_, A, B, Runnable> thirdAccumulator; private final Function<ResultHolder1_, Result1_> firstFinisher; private final Function<ResultHolder2_, Result2_> secondFinisher; private final Function<ResultHolder3_, Result3_> thirdFinisher; ComposeThreeBiCollector(BiConstraintCollector<A, B, ResultHolder1_, Result1_> first, BiConstraintCollector<A, B, ResultHolder2_, Result2_> second, BiConstraintCollector<A, B, ResultHolder3_, Result3_> third, TriFunction<Result1_, Result2_, Result3_, Result_> composeFunction) { this.first = first; this.second = second; this.third = third; this.composeFunction = composeFunction; this.firstSupplier = first.supplier(); this.secondSupplier = second.supplier(); this.thirdSupplier = third.supplier(); this.firstAccumulator = first.accumulator(); this.secondAccumulator = second.accumulator(); this.thirdAccumulator = third.accumulator(); this.firstFinisher = first.finisher(); this.secondFinisher = second.finisher(); this.thirdFinisher = third.finisher(); } @Override public Supplier<Triple<ResultHolder1_, ResultHolder2_, ResultHolder3_>> supplier() { return () -> { ResultHolder1_ a = firstSupplier.get(); ResultHolder2_ b = secondSupplier.get(); return new Triple<>(a, b, thirdSupplier.get()); }; } @Override public TriFunction<Triple<ResultHolder1_, ResultHolder2_, ResultHolder3_>, A, B, Runnable> accumulator() { return (resultHolder, a, b) -> composeUndo(firstAccumulator.apply(resultHolder.a(), a, b), secondAccumulator.apply(resultHolder.b(), a, b), thirdAccumulator.apply(resultHolder.c(), a, b)); } private static Runnable composeUndo(Runnable first, Runnable second, Runnable third) { return () -> { first.run(); second.run(); third.run(); }; } @Override public Function<Triple<ResultHolder1_, ResultHolder2_, ResultHolder3_>, Result_> finisher() { return resultHolder -> composeFunction.apply(firstFinisher.apply(resultHolder.a()), secondFinisher.apply(resultHolder.b()), thirdFinisher.apply(resultHolder.c())); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; var that = (ComposeThreeBiCollector<?, ?, ?, ?, ?, ?, ?, ?, ?>) object; return Objects.equals(first, that.first) && Objects.equals(second, that.second) && Objects.equals(third, that.third) && Objects.equals(composeFunction, that.composeFunction); } @Override public int hashCode() { return Objects.hash(first, second, third, composeFunction); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/ComposeTwoBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.api.score.stream.bi.BiConstraintCollector; import ai.timefold.solver.core.impl.util.Pair; final class ComposeTwoBiCollector<A, B, ResultHolder1_, ResultHolder2_, Result1_, Result2_, Result_> implements BiConstraintCollector<A, B, Pair<ResultHolder1_, ResultHolder2_>, Result_> { private final BiConstraintCollector<A, B, ResultHolder1_, Result1_> first; private final BiConstraintCollector<A, B, ResultHolder2_, Result2_> second; private final BiFunction<Result1_, Result2_, Result_> composeFunction; private final Supplier<ResultHolder1_> firstSupplier; private final Supplier<ResultHolder2_> secondSupplier; private final TriFunction<ResultHolder1_, A, B, Runnable> firstAccumulator; private final TriFunction<ResultHolder2_, A, B, Runnable> secondAccumulator; private final Function<ResultHolder1_, Result1_> firstFinisher; private final Function<ResultHolder2_, Result2_> secondFinisher; ComposeTwoBiCollector(BiConstraintCollector<A, B, ResultHolder1_, Result1_> first, BiConstraintCollector<A, B, ResultHolder2_, Result2_> second, BiFunction<Result1_, Result2_, Result_> composeFunction) { this.first = first; this.second = second; this.composeFunction = composeFunction; this.firstSupplier = first.supplier(); this.secondSupplier = second.supplier(); this.firstAccumulator = first.accumulator(); this.secondAccumulator = second.accumulator(); this.firstFinisher = first.finisher(); this.secondFinisher = second.finisher(); } @Override public Supplier<Pair<ResultHolder1_, ResultHolder2_>> supplier() { return () -> new Pair<>(firstSupplier.get(), secondSupplier.get()); } @Override public TriFunction<Pair<ResultHolder1_, ResultHolder2_>, A, B, Runnable> accumulator() { return (resultHolder, a, b) -> composeUndo(firstAccumulator.apply(resultHolder.key(), a, b), secondAccumulator.apply(resultHolder.value(), a, b)); } private static Runnable composeUndo(Runnable first, Runnable second) { return () -> { first.run(); second.run(); }; } @Override public Function<Pair<ResultHolder1_, ResultHolder2_>, Result_> finisher() { return resultHolder -> composeFunction.apply(firstFinisher.apply(resultHolder.key()), secondFinisher.apply(resultHolder.value())); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; var that = (ComposeTwoBiCollector<?, ?, ?, ?, ?, ?, ?>) object; return Objects.equals(first, that.first) && Objects.equals(second, that.second) && Objects.equals(composeFunction, that.composeFunction); } @Override public int hashCode() { return Objects.hash(first, second, composeFunction); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/ConditionalBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Objects; import java.util.function.BiPredicate; import java.util.function.Function; import java.util.function.Supplier; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.api.score.stream.bi.BiConstraintCollector; import ai.timefold.solver.core.impl.util.ConstantLambdaUtils; final class ConditionalBiCollector<A, B, ResultContainer_, Result_> implements BiConstraintCollector<A, B, ResultContainer_, Result_> { private final BiPredicate<A, B> predicate; private final BiConstraintCollector<A, B, ResultContainer_, Result_> delegate; private final TriFunction<ResultContainer_, A, B, Runnable> innerAccumulator; ConditionalBiCollector(BiPredicate<A, B> predicate, BiConstraintCollector<A, B, ResultContainer_, Result_> delegate) { this.predicate = predicate; this.delegate = delegate; this.innerAccumulator = delegate.accumulator(); } @Override public Supplier<ResultContainer_> supplier() { return delegate.supplier(); } @Override public TriFunction<ResultContainer_, A, B, Runnable> accumulator() { return (resultContainer, a, b) -> { if (predicate.test(a, b)) { return innerAccumulator.apply(resultContainer, a, b); } else { return ConstantLambdaUtils.noop(); } }; } @Override public Function<ResultContainer_, Result_> finisher() { return delegate.finisher(); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; var that = (ConditionalBiCollector<?, ?, ?, ?>) object; return Objects.equals(predicate, that.predicate) && Objects.equals(delegate, that.delegate); } @Override public int hashCode() { return Objects.hash(predicate, delegate); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/ConsecutiveSequencesBiConstraintCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Supplier; import java.util.function.ToIntFunction; import ai.timefold.solver.core.api.score.stream.common.SequenceChain; import ai.timefold.solver.core.impl.score.stream.SequenceCalculator; final class ConsecutiveSequencesBiConstraintCollector<A, B, Result_> extends ObjectCalculatorBiCollector<A, B, Result_, SequenceChain<Result_, Integer>, SequenceCalculator<Result_>> { private final ToIntFunction<Result_> indexMap; public ConsecutiveSequencesBiConstraintCollector(BiFunction<A, B, Result_> resultMap, ToIntFunction<Result_> indexMap) { super(resultMap); this.indexMap = Objects.requireNonNull(indexMap); } @Override public Supplier<SequenceCalculator<Result_>> supplier() { return () -> new SequenceCalculator<>(indexMap); } @Override public boolean equals(Object o) { if (o instanceof ConsecutiveSequencesBiConstraintCollector<?, ?, ?> other) { return Objects.equals(mapper, other.mapper) && Objects.equals(indexMap, other.indexMap); } return false; } @Override public int hashCode() { return Objects.hash(mapper, indexMap); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/CountDistinctIntBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.function.BiFunction; import java.util.function.Supplier; import ai.timefold.solver.core.impl.score.stream.IntDistinctCountCalculator; final class CountDistinctIntBiCollector<A, B, Mapped_> extends ObjectCalculatorBiCollector<A, B, Mapped_, Integer, IntDistinctCountCalculator<Mapped_>> { CountDistinctIntBiCollector(BiFunction<? super A, ? super B, ? extends Mapped_> mapper) { super(mapper); } @Override public Supplier<IntDistinctCountCalculator<Mapped_>> supplier() { return IntDistinctCountCalculator::new; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/CountDistinctLongBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.function.BiFunction; import java.util.function.Supplier; import ai.timefold.solver.core.impl.score.stream.LongDistinctCountCalculator; final class CountDistinctLongBiCollector<A, B, Mapped_> extends ObjectCalculatorBiCollector<A, B, Mapped_, Long, LongDistinctCountCalculator<Mapped_>> { CountDistinctLongBiCollector(BiFunction<? super A, ? super B, ? extends Mapped_> mapper) { super(mapper); } @Override public Supplier<LongDistinctCountCalculator<Mapped_>> supplier() { return LongDistinctCountCalculator::new; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/CountIntBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.function.Function; import java.util.function.Supplier; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.api.score.stream.bi.BiConstraintCollector; import ai.timefold.solver.core.impl.score.stream.IntCounter; final class CountIntBiCollector<A, B> implements BiConstraintCollector<A, B, IntCounter, Integer> { private final static CountIntBiCollector<?, ?> INSTANCE = new CountIntBiCollector<>(); private CountIntBiCollector() { } @SuppressWarnings("unchecked") static <A, B> CountIntBiCollector<A, B> getInstance() { return (CountIntBiCollector<A, B>) INSTANCE; } @Override public Supplier<IntCounter> supplier() { return IntCounter::new; } @Override public TriFunction<IntCounter, A, B, Runnable> accumulator() { return (counter, a, b) -> { counter.increment(); return counter::decrement; }; } @Override public Function<IntCounter, Integer> finisher() { return IntCounter::result; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/CountLongBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.function.Function; import java.util.function.Supplier; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.api.score.stream.bi.BiConstraintCollector; import ai.timefold.solver.core.impl.score.stream.LongCounter; final class CountLongBiCollector<A, B> implements BiConstraintCollector<A, B, LongCounter, Long> { private final static CountLongBiCollector<?, ?> INSTANCE = new CountLongBiCollector<>(); private CountLongBiCollector() { } @SuppressWarnings("unchecked") static <A, B> CountLongBiCollector<A, B> getInstance() { return (CountLongBiCollector<A, B>) INSTANCE; } @Override public Supplier<LongCounter> supplier() { return LongCounter::new; } @Override public TriFunction<LongCounter, A, B, Runnable> accumulator() { return (counter, a, b) -> { counter.increment(); return counter::decrement; }; } @Override public Function<LongCounter, Long> finisher() { return LongCounter::result; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/InnerBiConstraintCollectors.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.math.BigDecimal; import java.math.BigInteger; import java.time.Duration; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.Supplier; import java.util.function.ToIntBiFunction; import java.util.function.ToIntFunction; import java.util.function.ToLongBiFunction; import ai.timefold.solver.core.api.function.QuadFunction; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.api.score.stream.bi.BiConstraintCollector; import ai.timefold.solver.core.api.score.stream.common.SequenceChain; import ai.timefold.solver.core.impl.score.stream.ReferenceAverageCalculator; public class InnerBiConstraintCollectors { public static <A, B> BiConstraintCollector<A, B, ?, Double> average(ToIntBiFunction<? super A, ? super B> mapper) { return new AverageIntBiCollector<>(mapper); } public static <A, B> BiConstraintCollector<A, B, ?, Double> average(ToLongBiFunction<? super A, ? super B> mapper) { return new AverageLongBiCollector<>(mapper); } static <A, B, Mapped_, Average_> BiConstraintCollector<A, B, ?, Average_> average( BiFunction<? super A, ? super B, ? extends Mapped_> mapper, Supplier<ReferenceAverageCalculator<Mapped_, Average_>> calculatorSupplier) { return new AverageReferenceBiCollector<>(mapper, calculatorSupplier); } public static <A, B> BiConstraintCollector<A, B, ?, BigDecimal> averageBigDecimal( BiFunction<? super A, ? super B, ? extends BigDecimal> mapper) { return average(mapper, ReferenceAverageCalculator.bigDecimal()); } public static <A, B> BiConstraintCollector<A, B, ?, Duration> averageDuration( BiFunction<? super A, ? super B, ? extends Duration> mapper) { return average(mapper, ReferenceAverageCalculator.duration()); } public static <A, B> BiConstraintCollector<A, B, ?, BigDecimal> averageBigInteger( BiFunction<? super A, ? super B, ? extends BigInteger> mapper) { return average(mapper, ReferenceAverageCalculator.bigInteger()); } public static <A, B, ResultHolder1_, ResultHolder2_, ResultHolder3_, ResultHolder4_, Result1_, Result2_, Result3_, Result4_, Result_> BiConstraintCollector<A, B, ?, Result_> compose( BiConstraintCollector<A, B, ResultHolder1_, Result1_> first, BiConstraintCollector<A, B, ResultHolder2_, Result2_> second, BiConstraintCollector<A, B, ResultHolder3_, Result3_> third, BiConstraintCollector<A, B, ResultHolder4_, Result4_> fourth, QuadFunction<Result1_, Result2_, Result3_, Result4_, Result_> composeFunction) { return new ComposeFourBiCollector<>( first, second, third, fourth, composeFunction); } public static <A, B, ResultHolder1_, ResultHolder2_, ResultHolder3_, Result1_, Result2_, Result3_, Result_> BiConstraintCollector<A, B, ?, Result_> compose( BiConstraintCollector<A, B, ResultHolder1_, Result1_> first, BiConstraintCollector<A, B, ResultHolder2_, Result2_> second, BiConstraintCollector<A, B, ResultHolder3_, Result3_> third, TriFunction<Result1_, Result2_, Result3_, Result_> composeFunction) { return new ComposeThreeBiCollector<>( first, second, third, composeFunction); } public static <A, B, ResultHolder1_, ResultHolder2_, Result1_, Result2_, Result_> BiConstraintCollector<A, B, ?, Result_> compose( BiConstraintCollector<A, B, ResultHolder1_, Result1_> first, BiConstraintCollector<A, B, ResultHolder2_, Result2_> second, BiFunction<Result1_, Result2_, Result_> composeFunction) { return new ComposeTwoBiCollector<>(first, second, composeFunction); } public static <A, B, ResultContainer_, Result_> BiConstraintCollector<A, B, ResultContainer_, Result_> conditionally( BiPredicate<A, B> predicate, BiConstraintCollector<A, B, ResultContainer_, Result_> delegate) { return new ConditionalBiCollector<>(predicate, delegate); } public static <A, B> BiConstraintCollector<A, B, ?, Integer> count() { return CountIntBiCollector.getInstance(); } public static <A, B, Mapped_> BiConstraintCollector<A, B, ?, Integer> countDistinct( BiFunction<? super A, ? super B, ? extends Mapped_> mapper) { return new CountDistinctIntBiCollector<>(mapper); } public static <A, B, Mapped_> BiConstraintCollector<A, B, ?, Long> countDistinctLong( BiFunction<? super A, ? super B, ? extends Mapped_> mapper) { return new CountDistinctLongBiCollector<>(mapper); } public static <A, B> BiConstraintCollector<A, B, ?, Long> countLong() { return CountLongBiCollector.getInstance(); } public static <A, B, Result_ extends Comparable<? super Result_>> BiConstraintCollector<A, B, ?, Result_> max( BiFunction<? super A, ? super B, ? extends Result_> mapper) { return new MaxComparableBiCollector<>(mapper); } public static <A, B, Result_> BiConstraintCollector<A, B, ?, Result_> max( BiFunction<? super A, ? super B, ? extends Result_> mapper, Comparator<? super Result_> comparator) { return new MaxComparatorBiCollector<>(mapper, comparator); } public static <A, B, Result_, Property_ extends Comparable<? super Property_>> BiConstraintCollector<A, B, ?, Result_> max( BiFunction<? super A, ? super B, ? extends Result_> mapper, Function<? super Result_, ? extends Property_> propertyMapper) { return new MaxPropertyBiCollector<>(mapper, propertyMapper); } public static <A, B, Result_ extends Comparable<? super Result_>> BiConstraintCollector<A, B, ?, Result_> min( BiFunction<? super A, ? super B, ? extends Result_> mapper) { return new MinComparableBiCollector<>(mapper); } public static <A, B, Result_> BiConstraintCollector<A, B, ?, Result_> min( BiFunction<? super A, ? super B, ? extends Result_> mapper, Comparator<? super Result_> comparator) { return new MinComparatorBiCollector<>(mapper, comparator); } public static <A, B, Result_, Property_ extends Comparable<? super Property_>> BiConstraintCollector<A, B, ?, Result_> min( BiFunction<? super A, ? super B, ? extends Result_> mapper, Function<? super Result_, ? extends Property_> propertyMapper) { return new MinPropertyBiCollector<>(mapper, propertyMapper); } public static <A, B> BiConstraintCollector<A, B, ?, Integer> sum(ToIntBiFunction<? super A, ? super B> mapper) { return new SumIntBiCollector<>(mapper); } public static <A, B> BiConstraintCollector<A, B, ?, Long> sum(ToLongBiFunction<? super A, ? super B> mapper) { return new SumLongBiCollector<>(mapper); } public static <A, B, Result_> BiConstraintCollector<A, B, ?, Result_> sum( BiFunction<? super A, ? super B, ? extends Result_> mapper, Result_ zero, BinaryOperator<Result_> adder, BinaryOperator<Result_> subtractor) { return new SumReferenceBiCollector<>(mapper, zero, adder, subtractor); } public static <A, B, Mapped_, Result_ extends Collection<Mapped_>> BiConstraintCollector<A, B, ?, Result_> toCollection( BiFunction<? super A, ? super B, ? extends Mapped_> mapper, IntFunction<Result_> collectionFunction) { return new ToCollectionBiCollector<>(mapper, collectionFunction); } public static <A, B, Mapped_> BiConstraintCollector<A, B, ?, List<Mapped_>> toList( BiFunction<? super A, ? super B, ? extends Mapped_> mapper) { return new ToListBiCollector<>(mapper); } public static <A, B, Key_, Value_, Set_ extends Set<Value_>, Result_ extends Map<Key_, Set_>> BiConstraintCollector<A, B, ?, Result_> toMap( BiFunction<? super A, ? super B, ? extends Key_> keyFunction, BiFunction<? super A, ? super B, ? extends Value_> valueFunction, Supplier<Result_> mapSupplier, IntFunction<Set_> setFunction) { return new ToMultiMapBiCollector<>(keyFunction, valueFunction, mapSupplier, setFunction); } public static <A, B, Key_, Value_, Result_ extends Map<Key_, Value_>> BiConstraintCollector<A, B, ?, Result_> toMap( BiFunction<? super A, ? super B, ? extends Key_> keyFunction, BiFunction<? super A, ? super B, ? extends Value_> valueFunction, Supplier<Result_> mapSupplier, BinaryOperator<Value_> mergeFunction) { return new ToSimpleMapBiCollector<>(keyFunction, valueFunction, mapSupplier, mergeFunction); } public static <A, B, Mapped_> BiConstraintCollector<A, B, ?, Set<Mapped_>> toSet( BiFunction<? super A, ? super B, ? extends Mapped_> mapper) { return new ToSetBiCollector<>(mapper); } public static <A, B, Mapped_> BiConstraintCollector<A, B, ?, SortedSet<Mapped_>> toSortedSet( BiFunction<? super A, ? super B, ? extends Mapped_> mapper, Comparator<? super Mapped_> comparator) { return new ToSortedSetComparatorBiCollector<>(mapper, comparator); } public static <A, B, Result_> BiConstraintCollector<A, B, ?, SequenceChain<Result_, Integer>> toConsecutiveSequences(BiFunction<A, B, Result_> resultMap, ToIntFunction<Result_> indexMap) { return new ConsecutiveSequencesBiConstraintCollector<>(resultMap, indexMap); } public static <A, B, Intermediate_, Result_> BiConstraintCollector<A, B, ?, Result_> collectAndThen(BiConstraintCollector<A, B, ?, Intermediate_> delegate, Function<Intermediate_, Result_> mappingFunction) { return new AndThenBiCollector<>(delegate, mappingFunction); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/IntCalculatorBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Objects; import java.util.function.Function; import java.util.function.ToIntBiFunction; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.api.score.stream.bi.BiConstraintCollector; import ai.timefold.solver.core.impl.score.stream.IntCalculator; abstract sealed class IntCalculatorBiCollector<A, B, Output_, Calculator_ extends IntCalculator<Output_>> implements BiConstraintCollector<A, B, Calculator_, Output_> permits AverageIntBiCollector, SumIntBiCollector { private final ToIntBiFunction<? super A, ? super B> mapper; public IntCalculatorBiCollector(ToIntBiFunction<? super A, ? super B> mapper) { this.mapper = mapper; } @Override public TriFunction<Calculator_, A, B, Runnable> accumulator() { return (calculator, a, b) -> { final int mapped = mapper.applyAsInt(a, b); calculator.insert(mapped); return () -> calculator.retract(mapped); }; } @Override public Function<Calculator_, Output_> finisher() { return IntCalculator::result; } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; var that = (IntCalculatorBiCollector<?, ?, ?, ?>) object; return Objects.equals(mapper, that.mapper); } @Override public int hashCode() { return Objects.hash(mapper); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/LongCalculatorBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Objects; import java.util.function.Function; import java.util.function.ToLongBiFunction; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.api.score.stream.bi.BiConstraintCollector; import ai.timefold.solver.core.impl.score.stream.LongCalculator; abstract sealed class LongCalculatorBiCollector<A, B, Output_, Calculator_ extends LongCalculator<Output_>> implements BiConstraintCollector<A, B, Calculator_, Output_> permits AverageLongBiCollector, SumLongBiCollector { private final ToLongBiFunction<? super A, ? super B> mapper; public LongCalculatorBiCollector(ToLongBiFunction<? super A, ? super B> mapper) { this.mapper = mapper; } @Override public TriFunction<Calculator_, A, B, Runnable> accumulator() { return (calculator, a, b) -> { final long mapped = mapper.applyAsLong(a, b); calculator.insert(mapped); return () -> calculator.retract(mapped); }; } @Override public Function<Calculator_, Output_> finisher() { return LongCalculator::result; } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; var that = (LongCalculatorBiCollector<?, ?, ?, ?>) object; return Objects.equals(mapper, that.mapper); } @Override public int hashCode() { return Objects.hash(mapper); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/MaxComparableBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.function.BiFunction; import java.util.function.Supplier; import ai.timefold.solver.core.impl.score.stream.MinMaxUndoableActionable; final class MaxComparableBiCollector<A, B, Result_ extends Comparable<? super Result_>> extends UndoableActionableBiCollector<A, B, Result_, Result_, MinMaxUndoableActionable<Result_, Result_>> { MaxComparableBiCollector(BiFunction<? super A, ? super B, ? extends Result_> mapper) { super(mapper); } @Override public Supplier<MinMaxUndoableActionable<Result_, Result_>> supplier() { return MinMaxUndoableActionable::maxCalculator; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/MaxComparatorBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Comparator; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Supplier; import ai.timefold.solver.core.impl.score.stream.MinMaxUndoableActionable; final class MaxComparatorBiCollector<A, B, Result_> extends UndoableActionableBiCollector<A, B, Result_, Result_, MinMaxUndoableActionable<Result_, Result_>> { private final Comparator<? super Result_> comparator; MaxComparatorBiCollector(BiFunction<? super A, ? super B, ? extends Result_> mapper, Comparator<? super Result_> comparator) { super(mapper); this.comparator = comparator; } @Override public Supplier<MinMaxUndoableActionable<Result_, Result_>> supplier() { return () -> MinMaxUndoableActionable.maxCalculator(comparator); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; MaxComparatorBiCollector<?, ?, ?> that = (MaxComparatorBiCollector<?, ?, ?>) object; return Objects.equals(comparator, that.comparator); } @Override public int hashCode() { return Objects.hash(super.hashCode(), comparator); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/MaxPropertyBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import ai.timefold.solver.core.impl.score.stream.MinMaxUndoableActionable; final class MaxPropertyBiCollector<A, B, Result_, Property_ extends Comparable<? super Property_>> extends UndoableActionableBiCollector<A, B, Result_, Result_, MinMaxUndoableActionable<Result_, Property_>> { private final Function<? super Result_, ? extends Property_> propertyMapper; MaxPropertyBiCollector(BiFunction<? super A, ? super B, ? extends Result_> mapper, Function<? super Result_, ? extends Property_> propertyMapper) { super(mapper); this.propertyMapper = propertyMapper; } @Override public Supplier<MinMaxUndoableActionable<Result_, Property_>> supplier() { return () -> MinMaxUndoableActionable.maxCalculator(propertyMapper); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; MaxPropertyBiCollector<?, ?, ?, ?> that = (MaxPropertyBiCollector<?, ?, ?, ?>) object; return Objects.equals(propertyMapper, that.propertyMapper); } @Override public int hashCode() { return Objects.hash(super.hashCode(), propertyMapper); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/MinComparableBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.function.BiFunction; import java.util.function.Supplier; import ai.timefold.solver.core.impl.score.stream.MinMaxUndoableActionable; final class MinComparableBiCollector<A, B, Result_ extends Comparable<? super Result_>> extends UndoableActionableBiCollector<A, B, Result_, Result_, MinMaxUndoableActionable<Result_, Result_>> { MinComparableBiCollector(BiFunction<? super A, ? super B, ? extends Result_> mapper) { super(mapper); } @Override public Supplier<MinMaxUndoableActionable<Result_, Result_>> supplier() { return MinMaxUndoableActionable::minCalculator; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/MinComparatorBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Comparator; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Supplier; import ai.timefold.solver.core.impl.score.stream.MinMaxUndoableActionable; final class MinComparatorBiCollector<A, B, Result_> extends UndoableActionableBiCollector<A, B, Result_, Result_, MinMaxUndoableActionable<Result_, Result_>> { private final Comparator<? super Result_> comparator; MinComparatorBiCollector(BiFunction<? super A, ? super B, ? extends Result_> mapper, Comparator<? super Result_> comparator) { super(mapper); this.comparator = comparator; } @Override public Supplier<MinMaxUndoableActionable<Result_, Result_>> supplier() { return () -> MinMaxUndoableActionable.minCalculator(comparator); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; MinComparatorBiCollector<?, ?, ?> that = (MinComparatorBiCollector<?, ?, ?>) object; return Objects.equals(comparator, that.comparator); } @Override public int hashCode() { return Objects.hash(super.hashCode(), comparator); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/MinPropertyBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import ai.timefold.solver.core.impl.score.stream.MinMaxUndoableActionable; final class MinPropertyBiCollector<A, B, Result_, Property_ extends Comparable<? super Property_>> extends UndoableActionableBiCollector<A, B, Result_, Result_, MinMaxUndoableActionable<Result_, Property_>> { private final Function<? super Result_, ? extends Property_> propertyMapper; MinPropertyBiCollector(BiFunction<? super A, ? super B, ? extends Result_> mapper, Function<? super Result_, ? extends Property_> propertyMapper) { super(mapper); this.propertyMapper = propertyMapper; } @Override public Supplier<MinMaxUndoableActionable<Result_, Property_>> supplier() { return () -> MinMaxUndoableActionable.minCalculator(propertyMapper); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; MinPropertyBiCollector<?, ?, ?, ?> that = (MinPropertyBiCollector<?, ?, ?, ?>) object; return Objects.equals(propertyMapper, that.propertyMapper); } @Override public int hashCode() { return Objects.hash(super.hashCode(), propertyMapper); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/ObjectCalculatorBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Function; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.api.score.stream.bi.BiConstraintCollector; import ai.timefold.solver.core.impl.score.stream.ObjectCalculator; abstract sealed class ObjectCalculatorBiCollector<A, B, Input_, Output_, Calculator_ extends ObjectCalculator<Input_, Output_>> implements BiConstraintCollector<A, B, Calculator_, Output_> permits AverageReferenceBiCollector, ConsecutiveSequencesBiConstraintCollector, CountDistinctIntBiCollector, CountDistinctLongBiCollector, SumReferenceBiCollector { protected final BiFunction<? super A, ? super B, ? extends Input_> mapper; public ObjectCalculatorBiCollector(BiFunction<? super A, ? super B, ? extends Input_> mapper) { this.mapper = mapper; } @Override public TriFunction<Calculator_, A, B, Runnable> accumulator() { return (calculator, a, b) -> { final Input_ mapped = mapper.apply(a, b); calculator.insert(mapped); return () -> calculator.retract(mapped); }; } @Override public Function<Calculator_, Output_> finisher() { return ObjectCalculator::result; } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; var that = (ObjectCalculatorBiCollector<?, ?, ?, ?, ?>) object; return Objects.equals(mapper, that.mapper); } @Override public int hashCode() { return Objects.hash(mapper); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/SumIntBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.function.Supplier; import java.util.function.ToIntBiFunction; import ai.timefold.solver.core.impl.score.stream.IntSumCalculator; final class SumIntBiCollector<A, B> extends IntCalculatorBiCollector<A, B, Integer, IntSumCalculator> { SumIntBiCollector(ToIntBiFunction<? super A, ? super B> mapper) { super(mapper); } @Override public Supplier<IntSumCalculator> supplier() { return IntSumCalculator::new; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/SumLongBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.function.Supplier; import java.util.function.ToLongBiFunction; import ai.timefold.solver.core.impl.score.stream.LongSumCalculator; final class SumLongBiCollector<A, B> extends LongCalculatorBiCollector<A, B, Long, LongSumCalculator> { SumLongBiCollector(ToLongBiFunction<? super A, ? super B> mapper) { super(mapper); } @Override public Supplier<LongSumCalculator> supplier() { return LongSumCalculator::new; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/SumReferenceBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Supplier; import ai.timefold.solver.core.impl.score.stream.ReferenceSumCalculator; final class SumReferenceBiCollector<A, B, Result_> extends ObjectCalculatorBiCollector<A, B, Result_, Result_, ReferenceSumCalculator<Result_>> { private final Result_ zero; private final BinaryOperator<Result_> adder; private final BinaryOperator<Result_> subtractor; SumReferenceBiCollector(BiFunction<? super A, ? super B, ? extends Result_> mapper, Result_ zero, BinaryOperator<Result_> adder, BinaryOperator<Result_> subtractor) { super(mapper); this.zero = zero; this.adder = adder; this.subtractor = subtractor; } @Override public Supplier<ReferenceSumCalculator<Result_>> supplier() { return () -> new ReferenceSumCalculator<>(zero, adder, subtractor); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; SumReferenceBiCollector<?, ?, ?> that = (SumReferenceBiCollector<?, ?, ?>) object; return Objects.equals(zero, that.zero) && Objects.equals(adder, that.adder) && Objects.equals( subtractor, that.subtractor); } @Override public int hashCode() { return Objects.hash(super.hashCode(), zero, adder, subtractor); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/ToCollectionBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Collection; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.IntFunction; import java.util.function.Supplier; import ai.timefold.solver.core.impl.score.stream.CustomCollectionUndoableActionable; final class ToCollectionBiCollector<A, B, Mapped_, Result_ extends Collection<Mapped_>> extends UndoableActionableBiCollector<A, B, Mapped_, Result_, CustomCollectionUndoableActionable<Mapped_, Result_>> { private final IntFunction<Result_> collectionFunction; ToCollectionBiCollector(BiFunction<? super A, ? super B, ? extends Mapped_> mapper, IntFunction<Result_> collectionFunction) { super(mapper); this.collectionFunction = collectionFunction; } @Override public Supplier<CustomCollectionUndoableActionable<Mapped_, Result_>> supplier() { return () -> new CustomCollectionUndoableActionable<>(collectionFunction); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; ToCollectionBiCollector<?, ?, ?, ?> that = (ToCollectionBiCollector<?, ?, ?, ?>) object; return Objects.equals(collectionFunction, that.collectionFunction); } @Override public int hashCode() { return Objects.hash(super.hashCode(), collectionFunction); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/ToListBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.List; import java.util.function.BiFunction; import java.util.function.Supplier; import ai.timefold.solver.core.impl.score.stream.ListUndoableActionable; final class ToListBiCollector<A, B, Mapped_> extends UndoableActionableBiCollector<A, B, Mapped_, List<Mapped_>, ListUndoableActionable<Mapped_>> { ToListBiCollector(BiFunction<? super A, ? super B, ? extends Mapped_> mapper) { super(mapper); } @Override public Supplier<ListUndoableActionable<Mapped_>> supplier() { return ListUndoableActionable::new; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/ToMultiMapBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.BiFunction; import java.util.function.IntFunction; import java.util.function.Supplier; import ai.timefold.solver.core.impl.score.stream.MapUndoableActionable; import ai.timefold.solver.core.impl.util.Pair; final class ToMultiMapBiCollector<A, B, Key_, Value_, Set_ extends Set<Value_>, Result_ extends Map<Key_, Set_>> extends UndoableActionableBiCollector<A, B, Pair<Key_, Value_>, Result_, MapUndoableActionable<Key_, Value_, Set_, Result_>> { private final BiFunction<? super A, ? super B, ? extends Key_> keyFunction; private final BiFunction<? super A, ? super B, ? extends Value_> valueFunction; private final Supplier<Result_> mapSupplier; private final IntFunction<Set_> setFunction; ToMultiMapBiCollector(BiFunction<? super A, ? super B, ? extends Key_> keyFunction, BiFunction<? super A, ? super B, ? extends Value_> valueFunction, Supplier<Result_> mapSupplier, IntFunction<Set_> setFunction) { super((a, b) -> new Pair<>(keyFunction.apply(a, b), valueFunction.apply(a, b))); this.keyFunction = keyFunction; this.valueFunction = valueFunction; this.mapSupplier = mapSupplier; this.setFunction = setFunction; } @Override public Supplier<MapUndoableActionable<Key_, Value_, Set_, Result_>> supplier() { return () -> MapUndoableActionable.multiMap(mapSupplier, setFunction); } // Don't call super equals/hashCode; the groupingFunction is calculated from keyFunction // and valueFunction @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; var that = (ToMultiMapBiCollector<?, ?, ?, ?, ?, ?>) object; return Objects.equals(keyFunction, that.keyFunction) && Objects.equals(valueFunction, that.valueFunction) && Objects.equals(mapSupplier, that.mapSupplier) && Objects.equals( setFunction, that.setFunction); } @Override public int hashCode() { return Objects.hash(keyFunction, valueFunction, mapSupplier, setFunction); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/ToSetBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Supplier; import ai.timefold.solver.core.impl.score.stream.SetUndoableActionable; final class ToSetBiCollector<A, B, Mapped_> extends UndoableActionableBiCollector<A, B, Mapped_, Set<Mapped_>, SetUndoableActionable<Mapped_>> { ToSetBiCollector(BiFunction<? super A, ? super B, ? extends Mapped_> mapper) { super(mapper); } @Override public Supplier<SetUndoableActionable<Mapped_>> supplier() { return SetUndoableActionable::new; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/ToSimpleMapBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Map; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Supplier; import ai.timefold.solver.core.impl.score.stream.MapUndoableActionable; import ai.timefold.solver.core.impl.util.Pair; final class ToSimpleMapBiCollector<A, B, Key_, Value_, Result_ extends Map<Key_, Value_>> extends UndoableActionableBiCollector<A, B, Pair<Key_, Value_>, Result_, MapUndoableActionable<Key_, Value_, Value_, Result_>> { private final BiFunction<? super A, ? super B, ? extends Key_> keyFunction; private final BiFunction<? super A, ? super B, ? extends Value_> valueFunction; private final Supplier<Result_> mapSupplier; private final BinaryOperator<Value_> mergeFunction; ToSimpleMapBiCollector(BiFunction<? super A, ? super B, ? extends Key_> keyFunction, BiFunction<? super A, ? super B, ? extends Value_> valueFunction, Supplier<Result_> mapSupplier, BinaryOperator<Value_> mergeFunction) { super((a, b) -> new Pair<>(keyFunction.apply(a, b), valueFunction.apply(a, b))); this.keyFunction = keyFunction; this.valueFunction = valueFunction; this.mapSupplier = mapSupplier; this.mergeFunction = mergeFunction; } @Override public Supplier<MapUndoableActionable<Key_, Value_, Value_, Result_>> supplier() { return () -> MapUndoableActionable.mergeMap(mapSupplier, mergeFunction); } // Don't call super equals/hashCode; the groupingFunction is calculated from keyFunction // and valueFunction @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; var that = (ToSimpleMapBiCollector<?, ?, ?, ?, ?>) object; return Objects.equals(keyFunction, that.keyFunction) && Objects.equals(valueFunction, that.valueFunction) && Objects.equals(mapSupplier, that.mapSupplier) && Objects.equals( mergeFunction, that.mergeFunction); } @Override public int hashCode() { return Objects.hash(keyFunction, valueFunction, mapSupplier, mergeFunction); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/ToSortedSetComparatorBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Comparator; import java.util.Objects; import java.util.SortedSet; import java.util.function.BiFunction; import java.util.function.Supplier; import ai.timefold.solver.core.impl.score.stream.SortedSetUndoableActionable; final class ToSortedSetComparatorBiCollector<A, B, Mapped_> extends UndoableActionableBiCollector<A, B, Mapped_, SortedSet<Mapped_>, SortedSetUndoableActionable<Mapped_>> { private final Comparator<? super Mapped_> comparator; ToSortedSetComparatorBiCollector(BiFunction<? super A, ? super B, ? extends Mapped_> mapper, Comparator<? super Mapped_> comparator) { super(mapper); this.comparator = comparator; } @Override public Supplier<SortedSetUndoableActionable<Mapped_>> supplier() { return () -> SortedSetUndoableActionable.orderBy(comparator); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; ToSortedSetComparatorBiCollector<?, ?, ?> that = (ToSortedSetComparatorBiCollector<?, ?, ?>) object; return Objects.equals(comparator, that.comparator); } @Override public int hashCode() { return Objects.hash(super.hashCode(), comparator); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/bi/UndoableActionableBiCollector.java
package ai.timefold.solver.core.impl.score.stream.bi; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Function; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.api.score.stream.bi.BiConstraintCollector; import ai.timefold.solver.core.impl.score.stream.UndoableActionable; abstract sealed class UndoableActionableBiCollector<A, B, Input_, Output_, Calculator_ extends UndoableActionable<Input_, Output_>> implements BiConstraintCollector<A, B, Calculator_, Output_> permits MaxComparableBiCollector, MaxComparatorBiCollector, MaxPropertyBiCollector, MinComparableBiCollector, MinComparatorBiCollector, MinPropertyBiCollector, ToCollectionBiCollector, ToListBiCollector, ToMultiMapBiCollector, ToSetBiCollector, ToSimpleMapBiCollector, ToSortedSetComparatorBiCollector { private final BiFunction<? super A, ? super B, ? extends Input_> mapper; public UndoableActionableBiCollector(BiFunction<? super A, ? super B, ? extends Input_> mapper) { this.mapper = mapper; } @Override public TriFunction<Calculator_, A, B, Runnable> accumulator() { return (calculator, a, b) -> { final Input_ mapped = mapper.apply(a, b); return calculator.insert(mapped); }; } @Override public Function<Calculator_, Output_> finisher() { return UndoableActionable::result; } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; var that = (UndoableActionableBiCollector<?, ?, ?, ?, ?>) object; return Objects.equals(mapper, that.mapper); } @Override public int hashCode() { return Objects.hash(mapper); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/quad/AndThenQuadCollector.java
package ai.timefold.solver.core.impl.score.stream.quad; import java.util.Objects; import java.util.function.Function; import java.util.function.Supplier; import ai.timefold.solver.core.api.function.PentaFunction; import ai.timefold.solver.core.api.score.stream.quad.QuadConstraintCollector; final class AndThenQuadCollector<A, B, C, D, ResultContainer_, Intermediate_, Result_> implements QuadConstraintCollector<A, B, C, D, ResultContainer_, Result_> { private final QuadConstraintCollector<A, B, C, D, ResultContainer_, Intermediate_> delegate; private final Function<Intermediate_, Result_> mappingFunction; AndThenQuadCollector(QuadConstraintCollector<A, B, C, D, ResultContainer_, Intermediate_> delegate, Function<Intermediate_, Result_> mappingFunction) { this.delegate = Objects.requireNonNull(delegate); this.mappingFunction = Objects.requireNonNull(mappingFunction); } @Override public Supplier<ResultContainer_> supplier() { return delegate.supplier(); } @Override public PentaFunction<ResultContainer_, A, B, C, D, Runnable> accumulator() { return delegate.accumulator(); } @Override public Function<ResultContainer_, Result_> finisher() { var finisher = delegate.finisher(); return container -> mappingFunction.apply(finisher.apply(container)); } @Override public boolean equals(Object o) { if (o instanceof AndThenQuadCollector<?, ?, ?, ?, ?, ?, ?> other) { return Objects.equals(delegate, other.delegate) && Objects.equals(mappingFunction, other.mappingFunction); } return false; } @Override public int hashCode() { return Objects.hash(delegate, mappingFunction); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/quad/AverageIntQuadCollector.java
package ai.timefold.solver.core.impl.score.stream.quad; import java.util.function.Supplier; import ai.timefold.solver.core.api.function.ToIntQuadFunction; import ai.timefold.solver.core.impl.score.stream.IntAverageCalculator; final class AverageIntQuadCollector<A, B, C, D> extends IntCalculatorQuadCollector<A, B, C, D, Double, IntAverageCalculator> { AverageIntQuadCollector(ToIntQuadFunction<? super A, ? super B, ? super C, ? super D> mapper) { super(mapper); } @Override public Supplier<IntAverageCalculator> supplier() { return IntAverageCalculator::new; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/quad/AverageLongQuadCollector.java
package ai.timefold.solver.core.impl.score.stream.quad; import java.util.function.Supplier; import ai.timefold.solver.core.api.function.ToLongQuadFunction; import ai.timefold.solver.core.impl.score.stream.LongAverageCalculator; final class AverageLongQuadCollector<A, B, C, D> extends LongCalculatorQuadCollector<A, B, C, D, Double, LongAverageCalculator> { AverageLongQuadCollector(ToLongQuadFunction<? super A, ? super B, ? super C, ? super D> mapper) { super(mapper); } @Override public Supplier<LongAverageCalculator> supplier() { return LongAverageCalculator::new; } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/quad/AverageReferenceQuadCollector.java
package ai.timefold.solver.core.impl.score.stream.quad; import java.util.Objects; import java.util.function.Supplier; import ai.timefold.solver.core.api.function.QuadFunction; import ai.timefold.solver.core.impl.score.stream.ReferenceAverageCalculator; final class AverageReferenceQuadCollector<A, B, C, D, Mapped_, Average_> extends ObjectCalculatorQuadCollector<A, B, C, D, Mapped_, Average_, ReferenceAverageCalculator<Mapped_, Average_>> { private final Supplier<ReferenceAverageCalculator<Mapped_, Average_>> calculatorSupplier; AverageReferenceQuadCollector(QuadFunction<? super A, ? super B, ? super C, ? super D, ? extends Mapped_> mapper, Supplier<ReferenceAverageCalculator<Mapped_, Average_>> calculatorSupplier) { super(mapper); this.calculatorSupplier = calculatorSupplier; } @Override public Supplier<ReferenceAverageCalculator<Mapped_, Average_>> supplier() { return calculatorSupplier; } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; AverageReferenceQuadCollector<?, ?, ?, ?, ?, ?> that = (AverageReferenceQuadCollector<?, ?, ?, ?, ?, ?>) object; return Objects.equals(calculatorSupplier, that.calculatorSupplier); } @Override public int hashCode() { return Objects.hash(super.hashCode(), calculatorSupplier); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/quad/ComposeFourQuadCollector.java
package ai.timefold.solver.core.impl.score.stream.quad; import java.util.Objects; import java.util.function.Function; import java.util.function.Supplier; import ai.timefold.solver.core.api.function.PentaFunction; import ai.timefold.solver.core.api.function.QuadFunction; import ai.timefold.solver.core.api.score.stream.quad.QuadConstraintCollector; import ai.timefold.solver.core.impl.util.Quadruple; final class ComposeFourQuadCollector<A, B, C, D, ResultHolder1_, ResultHolder2_, ResultHolder3_, ResultHolder4_, Result1_, Result2_, Result3_, Result4_, Result_> implements QuadConstraintCollector<A, B, C, D, Quadruple<ResultHolder1_, ResultHolder2_, ResultHolder3_, ResultHolder4_>, Result_> { private final QuadConstraintCollector<A, B, C, D, ResultHolder1_, Result1_> first; private final QuadConstraintCollector<A, B, C, D, ResultHolder2_, Result2_> second; private final QuadConstraintCollector<A, B, C, D, ResultHolder3_, Result3_> third; private final QuadConstraintCollector<A, B, C, D, ResultHolder4_, Result4_> fourth; private final QuadFunction<Result1_, Result2_, Result3_, Result4_, Result_> composeFunction; private final Supplier<ResultHolder1_> firstSupplier; private final Supplier<ResultHolder2_> secondSupplier; private final Supplier<ResultHolder3_> thirdSupplier; private final Supplier<ResultHolder4_> fourthSupplier; private final PentaFunction<ResultHolder1_, A, B, C, D, Runnable> firstAccumulator; private final PentaFunction<ResultHolder2_, A, B, C, D, Runnable> secondAccumulator; private final PentaFunction<ResultHolder3_, A, B, C, D, Runnable> thirdAccumulator; private final PentaFunction<ResultHolder4_, A, B, C, D, Runnable> fourthAccumulator; private final Function<ResultHolder1_, Result1_> firstFinisher; private final Function<ResultHolder2_, Result2_> secondFinisher; private final Function<ResultHolder3_, Result3_> thirdFinisher; private final Function<ResultHolder4_, Result4_> fourthFinisher; ComposeFourQuadCollector(QuadConstraintCollector<A, B, C, D, ResultHolder1_, Result1_> first, QuadConstraintCollector<A, B, C, D, ResultHolder2_, Result2_> second, QuadConstraintCollector<A, B, C, D, ResultHolder3_, Result3_> third, QuadConstraintCollector<A, B, C, D, ResultHolder4_, Result4_> fourth, QuadFunction<Result1_, Result2_, Result3_, Result4_, Result_> composeFunction) { this.first = first; this.second = second; this.third = third; this.fourth = fourth; this.composeFunction = composeFunction; this.firstSupplier = first.supplier(); this.secondSupplier = second.supplier(); this.thirdSupplier = third.supplier(); this.fourthSupplier = fourth.supplier(); this.firstAccumulator = first.accumulator(); this.secondAccumulator = second.accumulator(); this.thirdAccumulator = third.accumulator(); this.fourthAccumulator = fourth.accumulator(); this.firstFinisher = first.finisher(); this.secondFinisher = second.finisher(); this.thirdFinisher = third.finisher(); this.fourthFinisher = fourth.finisher(); } @Override public Supplier<Quadruple<ResultHolder1_, ResultHolder2_, ResultHolder3_, ResultHolder4_>> supplier() { return () -> { ResultHolder1_ a = firstSupplier.get(); ResultHolder2_ b = secondSupplier.get(); ResultHolder3_ c = thirdSupplier.get(); return new Quadruple<>(a, b, c, fourthSupplier.get()); }; } @Override public PentaFunction<Quadruple<ResultHolder1_, ResultHolder2_, ResultHolder3_, ResultHolder4_>, A, B, C, D, Runnable> accumulator() { return (resultHolder, a, b, c, d) -> composeUndo(firstAccumulator.apply(resultHolder.a(), a, b, c, d), secondAccumulator.apply(resultHolder.b(), a, b, c, d), thirdAccumulator.apply(resultHolder.c(), a, b, c, d), fourthAccumulator.apply(resultHolder.d(), a, b, c, d)); } private static Runnable composeUndo(Runnable first, Runnable second, Runnable third, Runnable fourth) { return () -> { first.run(); second.run(); third.run(); fourth.run(); }; } @Override public Function<Quadruple<ResultHolder1_, ResultHolder2_, ResultHolder3_, ResultHolder4_>, Result_> finisher() { return resultHolder -> composeFunction.apply(firstFinisher.apply(resultHolder.a()), secondFinisher.apply(resultHolder.b()), thirdFinisher.apply(resultHolder.c()), fourthFinisher.apply(resultHolder.d())); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; var that = (ComposeFourQuadCollector<?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?>) object; return Objects.equals(first, that.first) && Objects.equals(second, that.second) && Objects.equals(third, that.third) && Objects.equals(fourth, that.fourth) && Objects.equals(composeFunction, that.composeFunction); } @Override public int hashCode() { return Objects.hash(first, second, third, fourth, composeFunction); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/quad/ComposeThreeQuadCollector.java
package ai.timefold.solver.core.impl.score.stream.quad; import java.util.Objects; import java.util.function.Function; import java.util.function.Supplier; import ai.timefold.solver.core.api.function.PentaFunction; import ai.timefold.solver.core.api.function.TriFunction; import ai.timefold.solver.core.api.score.stream.quad.QuadConstraintCollector; import ai.timefold.solver.core.impl.util.Triple; final class ComposeThreeQuadCollector<A, B, C, D, ResultHolder1_, ResultHolder2_, ResultHolder3_, Result1_, Result2_, Result3_, Result_> implements QuadConstraintCollector<A, B, C, D, Triple<ResultHolder1_, ResultHolder2_, ResultHolder3_>, Result_> { private final QuadConstraintCollector<A, B, C, D, ResultHolder1_, Result1_> first; private final QuadConstraintCollector<A, B, C, D, ResultHolder2_, Result2_> second; private final QuadConstraintCollector<A, B, C, D, ResultHolder3_, Result3_> third; private final TriFunction<Result1_, Result2_, Result3_, Result_> composeFunction; private final Supplier<ResultHolder1_> firstSupplier; private final Supplier<ResultHolder2_> secondSupplier; private final Supplier<ResultHolder3_> thirdSupplier; private final PentaFunction<ResultHolder1_, A, B, C, D, Runnable> firstAccumulator; private final PentaFunction<ResultHolder2_, A, B, C, D, Runnable> secondAccumulator; private final PentaFunction<ResultHolder3_, A, B, C, D, Runnable> thirdAccumulator; private final Function<ResultHolder1_, Result1_> firstFinisher; private final Function<ResultHolder2_, Result2_> secondFinisher; private final Function<ResultHolder3_, Result3_> thirdFinisher; ComposeThreeQuadCollector(QuadConstraintCollector<A, B, C, D, ResultHolder1_, Result1_> first, QuadConstraintCollector<A, B, C, D, ResultHolder2_, Result2_> second, QuadConstraintCollector<A, B, C, D, ResultHolder3_, Result3_> third, TriFunction<Result1_, Result2_, Result3_, Result_> composeFunction) { this.first = first; this.second = second; this.third = third; this.composeFunction = composeFunction; this.firstSupplier = first.supplier(); this.secondSupplier = second.supplier(); this.thirdSupplier = third.supplier(); this.firstAccumulator = first.accumulator(); this.secondAccumulator = second.accumulator(); this.thirdAccumulator = third.accumulator(); this.firstFinisher = first.finisher(); this.secondFinisher = second.finisher(); this.thirdFinisher = third.finisher(); } @Override public Supplier<Triple<ResultHolder1_, ResultHolder2_, ResultHolder3_>> supplier() { return () -> { ResultHolder1_ a = firstSupplier.get(); ResultHolder2_ b = secondSupplier.get(); return new Triple<>(a, b, thirdSupplier.get()); }; } @Override public PentaFunction<Triple<ResultHolder1_, ResultHolder2_, ResultHolder3_>, A, B, C, D, Runnable> accumulator() { return (resultHolder, a, b, c, d) -> composeUndo(firstAccumulator.apply(resultHolder.a(), a, b, c, d), secondAccumulator.apply(resultHolder.b(), a, b, c, d), thirdAccumulator.apply(resultHolder.c(), a, b, c, d)); } private static Runnable composeUndo(Runnable first, Runnable second, Runnable third) { return () -> { first.run(); second.run(); third.run(); }; } @Override public Function<Triple<ResultHolder1_, ResultHolder2_, ResultHolder3_>, Result_> finisher() { return resultHolder -> composeFunction.apply(firstFinisher.apply(resultHolder.a()), secondFinisher.apply(resultHolder.b()), thirdFinisher.apply(resultHolder.c())); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; var that = (ComposeThreeQuadCollector<?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?>) object; return Objects.equals(first, that.first) && Objects.equals(second, that.second) && Objects.equals(third, that.third) && Objects.equals(composeFunction, that.composeFunction); } @Override public int hashCode() { return Objects.hash(first, second, third, composeFunction); } }
0
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream
java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/score/stream/quad/ComposeTwoQuadCollector.java
package ai.timefold.solver.core.impl.score.stream.quad; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import ai.timefold.solver.core.api.function.PentaFunction; import ai.timefold.solver.core.api.score.stream.quad.QuadConstraintCollector; import ai.timefold.solver.core.impl.util.Pair; final class ComposeTwoQuadCollector<A, B, C, D, ResultHolder1_, ResultHolder2_, Result1_, Result2_, Result_> implements QuadConstraintCollector<A, B, C, D, Pair<ResultHolder1_, ResultHolder2_>, Result_> { private final QuadConstraintCollector<A, B, C, D, ResultHolder1_, Result1_> first; private final QuadConstraintCollector<A, B, C, D, ResultHolder2_, Result2_> second; private final BiFunction<Result1_, Result2_, Result_> composeFunction; private final Supplier<ResultHolder1_> firstSupplier; private final Supplier<ResultHolder2_> secondSupplier; private final PentaFunction<ResultHolder1_, A, B, C, D, Runnable> firstAccumulator; private final PentaFunction<ResultHolder2_, A, B, C, D, Runnable> secondAccumulator; private final Function<ResultHolder1_, Result1_> firstFinisher; private final Function<ResultHolder2_, Result2_> secondFinisher; ComposeTwoQuadCollector(QuadConstraintCollector<A, B, C, D, ResultHolder1_, Result1_> first, QuadConstraintCollector<A, B, C, D, ResultHolder2_, Result2_> second, BiFunction<Result1_, Result2_, Result_> composeFunction) { this.first = first; this.second = second; this.composeFunction = composeFunction; this.firstSupplier = first.supplier(); this.secondSupplier = second.supplier(); this.firstAccumulator = first.accumulator(); this.secondAccumulator = second.accumulator(); this.firstFinisher = first.finisher(); this.secondFinisher = second.finisher(); } @Override public Supplier<Pair<ResultHolder1_, ResultHolder2_>> supplier() { return () -> new Pair<>(firstSupplier.get(), secondSupplier.get()); } @Override public PentaFunction<Pair<ResultHolder1_, ResultHolder2_>, A, B, C, D, Runnable> accumulator() { return (resultHolder, a, b, c, d) -> composeUndo(firstAccumulator.apply(resultHolder.key(), a, b, c, d), secondAccumulator.apply(resultHolder.value(), a, b, c, d)); } private static Runnable composeUndo(Runnable first, Runnable second) { return () -> { first.run(); second.run(); }; } @Override public Function<Pair<ResultHolder1_, ResultHolder2_>, Result_> finisher() { return resultHolder -> composeFunction.apply(firstFinisher.apply(resultHolder.key()), secondFinisher.apply(resultHolder.value())); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; var that = (ComposeTwoQuadCollector<?, ?, ?, ?, ?, ?, ?, ?, ?>) object; return Objects.equals(first, that.first) && Objects.equals(second, that.second) && Objects.equals(composeFunction, that.composeFunction); } @Override public int hashCode() { return Objects.hash(first, second, composeFunction); } }