repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
timefold-solver | github_2023 | java | 415 | TimefoldAI | rsynek | @@ -98,6 +98,10 @@ public double getAngle(Location location) {
return Math.atan2(latitudeDifference, longitudeDifference);
}
+ protected static long adjust(double distance) {
+ return (long) (distance + 0.5); // +0.5 to avoid floating point rounding errors | Is it any different from `Math.round()` ? |
timefold-solver | github_2023 | java | 411 | TimefoldAI | rsynek | @@ -179,7 +179,8 @@ private ConstructionHeuristicDecider<Solution_> buildDecider(HeuristicConfigPoli
if (moveThreadCount == null) {
decider = new ConstructionHeuristicDecider<>(configPolicy.getLogIndentation(), termination, forager);
} else {
- decider = MultithreadedSolvingEnterpriseService.load(moveThreadCount)
+ decider = TimefoldSolverEnterpriseService
+ .loadOrFail("Multi-threader solving", "remove moveThreadCount from solver configuration") | (soft suggestion) These pairs of a feature and a workaround could be an `enum`. |
timefold-solver | github_2023 | others | 404 | TimefoldAI | rsynek | @@ -0,0 +1,707 @@
+= Enterprise Edition
+:doctype: book
+:sectnums:
+:icons: font
+
+Timefold Solver Enterprise Edition is a commercial product that offers additional features,
+such as <<nearbySelection,nearby selection>> and <<multithreadedSolving,multi-threaded solving>>.
+These features are essential to scale out to very large datasets.
+
+Unlike Timefold Solver Community Edition,
+the Enterprise Edition is not open-source.
+To use Timefold Solver Enterprise Edition in production,
+you need to https://timefold.ai/company/contact/[purchase a license]. | Should we explicitly say that Enterprise Edition can still be used for an evaluation/development purposes? |
timefold-solver | github_2023 | java | 401 | TimefoldAI | triceo | @@ -7,17 +7,138 @@
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.stream.ConstraintStream;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
+import ai.timefold.solver.core.impl.util.Pair;
+import ai.timefold.solver.core.impl.util.Quadruple;
+import ai.timefold.solver.core.impl.util.Triple;
public interface GroupNodeConstructor<Tuple_ extends AbstractTuple> {
- static <Tuple_ extends AbstractTuple> GroupNodeConstructor<Tuple_>
- of(NodeConstructorWithAccumulate<Tuple_> nodeConstructorWithAccumulate) {
- return new GroupNodeConstructorWithAccumulate<>(nodeConstructorWithAccumulate);
+ static <CollectorA_, Tuple_ extends AbstractTuple> GroupNodeConstructor<Tuple_>
+ zeroKeysGroupBy(CollectorA_ collector, NoKeysOneCollectorGroupByBuilder<CollectorA_, Tuple_> builder) {
+ return new GroupNodeConstructorWithAccumulate<>(collector,
+ (groupStoreIndex, undoStoreIndex, nextNodesTupleLifecycle, outputStoreSize, environmentMode) -> builder.build(
+ groupStoreIndex, undoStoreIndex, collector, nextNodesTupleLifecycle, outputStoreSize,
+ environmentMode));
}
- static <Tuple_ extends AbstractTuple> GroupNodeConstructor<Tuple_>
- of(NodeConstructorWithoutAccumulate<Tuple_> nodeConstructorWithoutAccumulate) {
- return new GroupNodeConstructorWithoutAccumulate<>(nodeConstructorWithoutAccumulate);
+ static <CollectorA_, CollectorB_, Tuple_ extends AbstractTuple> GroupNodeConstructor<Tuple_>
+ zeroKeysGroupBy(CollectorA_ collectorA, CollectorB_ collectorB,
+ NoKeysTwoCollectorsGroupByBuilder<CollectorA_, CollectorB_, Tuple_> builder) {
+ return new GroupNodeConstructorWithAccumulate<>(Pair.of(collectorA, collectorB),
+ (groupStoreIndex, undoStoreIndex, nextNodesTupleLifecycle, outputStoreSize, environmentMode) -> builder.build(
+ groupStoreIndex, undoStoreIndex, collectorA, collectorB, nextNodesTupleLifecycle,
+ outputStoreSize, environmentMode));
+ }
+
+ static <CollectorA_, CollectorB_, CollectorC_, Tuple_ extends AbstractTuple> GroupNodeConstructor<Tuple_>
+ zeroKeysGroupBy(CollectorA_ collectorA, CollectorB_ collectorB, CollectorC_ collectorC,
+ NoKeysThreeCollectorsGroupByBuilder<CollectorA_, CollectorB_, CollectorC_, Tuple_> builder) {
+ return new GroupNodeConstructorWithAccumulate<>(Triple.of(collectorA, collectorB, collectorC),
+ (groupStoreIndex, undoStoreIndex, nextNodesTupleLifecycle, outputStoreSize, environmentMode) -> builder.build(
+ groupStoreIndex, undoStoreIndex, collectorA, collectorB, collectorC,
+ nextNodesTupleLifecycle, outputStoreSize, environmentMode));
+ } | This confused me at first.
- `CollectorA_` et al. are not `...ConstraintCollector` subtypes. (Because that would cause further explosion in the number of interfaces you'd have to create for this.)
- `NoKeysThreeCollectorsGroupByBuilder` also doesn't reference constraint collectors.
- But then the builder itself is `Group...Node::new`, which *requires* a collector implementation. `CollectorA_` is not a collector subtype.
How does this compile?
It compiles because `Group...Node::new` is covariant with `build(int groupStoreIndex, int undoStoreIndex, CollectorA_ collectorA, CollectorB_ collectorB, CollectorC_ collectorC, TupleLifecycle<Tuple_> nextNodesTupleLifecycle, int outputStoreSize, EnvironmentMode environmentMode)`. The compiler is fooled and if the generic type in the end doesn't match the expected collector type, we'll get a cast error at runtime.
This is not at all obvious. |
timefold-solver | github_2023 | java | 401 | TimefoldAI | triceo | @@ -7,17 +7,138 @@
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.stream.ConstraintStream;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
+import ai.timefold.solver.core.impl.util.Pair;
+import ai.timefold.solver.core.impl.util.Quadruple;
+import ai.timefold.solver.core.impl.util.Triple;
public interface GroupNodeConstructor<Tuple_ extends AbstractTuple> { | It appears we no longer need the tuple here.
(Which also means we can now replace all declarations of `GroupNodeConstructor` variables with `var`.)
Actually, I checked the history and this was the case on `main` already.
Please make the changes anyway - it's a good thing to leave the code in a better shape than the one we found it in. |
timefold-solver | github_2023 | java | 401 | TimefoldAI | triceo | @@ -36,6 +157,128 @@ AbstractNode apply(int groupStoreIndex, TupleLifecycle<Tuple_> nextNodesTupleLif
}
+ @FunctionalInterface
+ interface NoKeysOneCollectorGroupByBuilder<CollectorA_, Tuple_ extends AbstractTuple> {
+ AbstractNode build(int groupStoreIndex, int undoStoreIndex,
+ CollectorA_ collector,
+ TupleLifecycle<Tuple_> nextNodesTupleLifecycle, int outputStoreSize, EnvironmentMode environmentMode);
+ }
+
+ @FunctionalInterface
+ interface NoKeysTwoCollectorsGroupByBuilder<CollectorA_, CollectorB_, Tuple_ extends AbstractTuple> {
+ AbstractNode build(int groupStoreIndex, int undoStoreIndex,
+ CollectorA_ collectorA,
+ CollectorB_ collectorB,
+ TupleLifecycle<Tuple_> nextNodesTupleLifecycle, int outputStoreSize, EnvironmentMode environmentMode);
+ }
+
+ @FunctionalInterface
+ interface NoKeysThreeCollectorsGroupByBuilder<CollectorA_, CollectorB_, CollectorC_, Tuple_ extends AbstractTuple> {
+ AbstractNode build(int groupStoreIndex, int undoStoreIndex,
+ CollectorA_ collectorA,
+ CollectorB_ collectorB,
+ CollectorC_ collectorC,
+ TupleLifecycle<Tuple_> nextNodesTupleLifecycle, int outputStoreSize, EnvironmentMode environmentMode);
+ }
+
+ @FunctionalInterface
+ interface NoKeysFourCollectorsGroupByBuilder<CollectorA_, CollectorB_, CollectorC_, CollectorD_, Tuple_ extends AbstractTuple> {
+ AbstractNode build(int groupStoreIndex, int undoStoreIndex,
+ CollectorA_ collectorA,
+ CollectorB_ collectorB,
+ CollectorC_ collectorC,
+ CollectorD_ collectorD,
+ TupleLifecycle<Tuple_> nextNodesTupleLifecycle, int outputStoreSize, EnvironmentMode environmentMode);
+ }
+
+ @FunctionalInterface
+ interface OneKeyNoCollectorsGroupByBuilder<KeyA_, Tuple_ extends AbstractTuple> {
+ AbstractNode build(KeyA_ keyMapping,
+ int groupStoreIndex,
+ TupleLifecycle<Tuple_> nextNodesTupleLifecycle, int outputStoreSize, EnvironmentMode environmentMode);
+ }
+
+ @FunctionalInterface
+ interface TwoKeysNoCollectorsGroupByBuilder<KeyA_, KeyB_, Tuple_ extends AbstractTuple> {
+ AbstractNode build(KeyA_ keyMappingA,
+ KeyB_ keyMappingB, int groupStoreIndex,
+ TupleLifecycle<Tuple_> nextNodesTupleLifecycle, int outputStoreSize, EnvironmentMode environmentMode);
+ }
+
+ @FunctionalInterface
+ interface ThreeKeysNoCollectorsGroupByBuilder<KeyA_, KeyB_, KeyC_, Tuple_ extends AbstractTuple> {
+ AbstractNode build(KeyA_ keyMappingA,
+ KeyB_ keyMappingB,
+ KeyC_ keyMappingC,
+ int groupStoreIndex,
+ TupleLifecycle<Tuple_> nextNodesTupleLifecycle, int outputStoreSize, EnvironmentMode environmentMode);
+ }
+
+ @FunctionalInterface
+ interface FourKeysNoCollectorsGroupByBuilder<KeyA_, KeyB_, KeyC_, KeyD_, Tuple_ extends AbstractTuple> {
+ AbstractNode build(KeyA_ keyMappingA,
+ KeyB_ keyMappingB,
+ KeyC_ keyMappingC,
+ KeyD_ keyMappingD,
+ int groupStoreIndex,
+ TupleLifecycle<Tuple_> nextNodesTupleLifecycle, int outputStoreSize, EnvironmentMode environmentMode);
+ }
+
+ @FunctionalInterface
+ interface OneKeyOneCollectorGroupByBuilder<KeyA_, CollectorB_, Tuple_ extends AbstractTuple> {
+ AbstractNode build(KeyA_ keyMapping,
+ int groupStoreIndex, int undoStoreIndex,
+ CollectorB_ collector,
+ TupleLifecycle<Tuple_> nextNodesTupleLifecycle, int outputStoreSize, EnvironmentMode environmentMode);
+ }
+
+ @FunctionalInterface
+ interface OneKeyTwoCollectorsGroupByBuilder<KeyA_, CollectorB_, CollectorC_, Tuple_ extends AbstractTuple> {
+ AbstractNode build(KeyA_ keyMapping,
+ int groupStoreIndex, int undoStoreIndex,
+ CollectorB_ collectorA,
+ CollectorC_ collectorB,
+ TupleLifecycle<Tuple_> nextNodesTupleLifecycle, int outputStoreSize, EnvironmentMode environmentMode);
+ }
+
+ @FunctionalInterface
+ interface OneKeyThreeCollectorsGroupByBuilder<KeyA_, CollectorB_, CollectorC_, CollectorD_, Tuple_ extends AbstractTuple> {
+ AbstractNode build(KeyA_ keyMapping,
+ int groupStoreIndex, int undoStoreIndex,
+ CollectorB_ collectorA,
+ CollectorC_ collectorB,
+ CollectorD_ collectorC,
+ TupleLifecycle<Tuple_> nextNodesTupleLifecycle, int outputStoreSize, EnvironmentMode environmentMode);
+ }
+
+ @FunctionalInterface
+ interface TwoKeysOneCollectorGroupByBuilder<KeyA_, KeyB_, CollectorC_, Tuple_ extends AbstractTuple> { | Let's stay consistent with the node naming and use the `GroupByXMappingYCollectorNodeBuilder` pattern in these names. |
timefold-solver | github_2023 | java | 401 | TimefoldAI | triceo | @@ -36,6 +180,128 @@ AbstractNode apply(int groupStoreIndex, TupleLifecycle<Tuple_> nextNodesTupleLif
}
+ @FunctionalInterface
+ interface GroupBy0Mapping1CollectorNodeBuilder<CollectorA_, Tuple_ extends AbstractTuple> {
+ AbstractNode build(int groupStoreIndex, int undoStoreIndex,
+ CollectorA_ collector,
+ TupleLifecycle<Tuple_> nextNodesTupleLifecycle, int outputStoreSize, EnvironmentMode environmentMode);
+ }
+
+ @FunctionalInterface
+ interface GroupBy0Mapping2CollectorNodeBuilder<CollectorA_, CollectorB_, Tuple_ extends AbstractTuple> {
+ AbstractNode build(int groupStoreIndex, int undoStoreIndex,
+ CollectorA_ collectorA,
+ CollectorB_ collectorB,
+ TupleLifecycle<Tuple_> nextNodesTupleLifecycle, int outputStoreSize, EnvironmentMode environmentMode);
+ }
+
+ @FunctionalInterface
+ interface GroupBy0Mapping3CollectorNodeBuilder<CollectorA_, CollectorB_, CollectorC_, Tuple_ extends AbstractTuple> {
+ AbstractNode build(int groupStoreIndex, int undoStoreIndex,
+ CollectorA_ collectorA,
+ CollectorB_ collectorB,
+ CollectorC_ collectorC,
+ TupleLifecycle<Tuple_> nextNodesTupleLifecycle, int outputStoreSize, EnvironmentMode environmentMode);
+ }
+
+ @FunctionalInterface
+ interface GroupBy0Mapping4CollectorNodeBuilder<CollectorA_, CollectorB_, CollectorC_, CollectorD_, Tuple_ extends AbstractTuple> { | One thing just crossed my mind... if we don't need `Collector_` to extend `...ConstraintCollector`, do we need `Tuple_` to extend `AbstractTuple`?
If not, even more boilerplate to remove right here. |
timefold-solver | github_2023 | java | 392 | TimefoldAI | triceo | @@ -80,90 +167,56 @@ public final class ConstraintCollectors {
* @return never null
*/
public static <A> UniConstraintCollector<A, ?, Integer> count() {
- return new DefaultUniConstraintCollector<>(
- MutableInt::new,
- (resultContainer, a) -> innerCount(resultContainer),
- MutableInt::intValue);
- }
-
- private static Runnable innerCount(MutableInt resultContainer) {
- resultContainer.increment();
- return resultContainer::decrement;
+ return new IntCountUniCollector<>(); | We didn't do this before, but now that I see it like this, why not make these argless collectors a singleton? Works nicely with the factory idea below. |
timefold-solver | github_2023 | java | 392 | TimefoldAI | triceo | @@ -47,23 +40,117 @@
import ai.timefold.solver.core.api.score.stream.tri.TriConstraintCollector;
import ai.timefold.solver.core.api.score.stream.uni.UniConstraintCollector;
import ai.timefold.solver.core.api.score.stream.uni.UniConstraintStream;
-import ai.timefold.solver.core.impl.util.MutableInt;
-import ai.timefold.solver.core.impl.util.MutableLong;
-import ai.timefold.solver.core.impl.util.MutableReference;
-import ai.timefold.solver.core.impl.util.Pair;
-import ai.timefold.solver.core.impl.util.Quadruple;
-import ai.timefold.solver.core.impl.util.Triple;
+import ai.timefold.solver.core.impl.score.stream.bi.BiComposeFourCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.BiComposeThreeCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.BiComposeTwoCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.ComparableMaxBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.ComparableMinBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.ComparatorMaxBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.ComparatorMinBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.ComparatorSortedSetBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.ConditionalBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.CustomCollectionBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.IntAverageBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.IntCountBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.IntDistinctCountBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.IntSumBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.ListBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.LongAverageBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.LongCountBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.LongDistinctCountBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.LongSumBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.MultiMapBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.PropertyMaxBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.PropertyMinBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.ReferenceAverageBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.ReferenceSumBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.SetBiCollector;
+import ai.timefold.solver.core.impl.score.stream.bi.SimpleMapBiCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.ComparableMaxQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.ComparableMinQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.ComparatorMaxQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.ComparatorMinQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.ComparatorSortedSetQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.ConditionalQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.CustomCollectionQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.IntAverageQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.IntCountQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.IntDistinctCountQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.IntSumQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.ListQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.LongAverageQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.LongCountQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.LongDistinctCountQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.LongSumQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.MultiMapQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.PropertyMaxQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.PropertyMinQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.QuadComposeFourCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.QuadComposeThreeCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.QuadComposeTwoCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.ReferenceAverageQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.ReferenceSumQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.SetQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.quad.SimpleMapQuadCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.ComparableMaxTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.ComparableMinTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.ComparatorMaxTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.ComparatorMinTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.ComparatorSortedSetTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.ConditionalTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.CustomCollectionTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.IntAverageTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.IntCountTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.IntDistinctCountTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.IntSumTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.ListTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.LongAverageTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.LongCountTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.LongDistinctCountTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.LongSumTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.MultiMapTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.PropertyMaxTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.PropertyMinTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.ReferenceAverageTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.ReferenceSumTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.SetTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.SimpleMapTriCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.TriComposeFourCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.TriComposeThreeCollector;
+import ai.timefold.solver.core.impl.score.stream.tri.TriComposeTwoCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.ComparableMaxUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.ComparableMinUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.ComparatorMaxUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.ComparatorMinUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.ComparatorSortedSetUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.ConditionalUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.CustomCollectionUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.IntAverageUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.IntCountUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.IntDistinctCountUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.IntSumUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.ListUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.LongAverageUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.LongCountUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.LongDistinctCountUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.LongSumUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.MultiMapUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.PropertyMaxUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.PropertyMinUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.ReferenceAverageUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.ReferenceSumUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.SetUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.SimpleMapUniCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.UniComposeFourCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.UniComposeThreeCollector;
+import ai.timefold.solver.core.impl.score.stream.uni.UniComposeTwoCollector;
+import ai.timefold.solver.core.impl.util.ConstantLambdaUtils;
/**
* Creates an {@link UniConstraintCollector}, {@link BiConstraintCollector}, ... instance
* for use in {@link UniConstraintStream#groupBy(Function, UniConstraintCollector)}, ...
*/
public final class ConstraintCollectors { | General comment: please make it so that the collector implementations aren't public. I do not want them to show up in IDEs. If there needs to be a public factory for them, so be it. Let's call it `InnerConstraintCollectors`, to follow the `Inner...` convention we already use elsewhere.
You may think it's boilerplate but trust me, people will find and use anything that is public. By not hiding things, you are inviting people to use your internal stuff. And in this case, when the IDE offers people a thousand different implementations of collectors, it will do nothing but confuse them. (Remember: the IDE doesn't know that these implementations aren't public API. It *will* show them as options when people add collectors to their streams.)
I understand that doing this will require putting all uni/bi/... impls of the collectors into the same package. It's not nice, but I believe it needs to be done. Nothing in the `...impl.score.stream` package should be public, other than the factory.
EDIT: As I think about it more, I find another option, as I like the new hierarchy you introduced and I think it would be a shame if it went away:
- Let's make the factories per cardinality, so `Uni...`, `Bi...`, ... That way, you don't need to put all the collectors into the same package; the factory would be the only public thing in the `uni`, `bi`... package.
- The fact that the common stuff will be public, I don't mind that - those are not collectors, so they won't normally be suggested to people in auto-complete.
- Wouldn't it be nice if all these impls moved to the `constraint-streams` module? The factories would have to be exposed as services, so that the `ConstraintCollectors` class can reach out into the other module, but maybe worth it? Don't know, just thinking out loud. Probably, this would finally be too much boilerplate. |
timefold-solver | github_2023 | java | 392 | TimefoldAI | triceo | @@ -0,0 +1,9 @@
+package ai.timefold.solver.core.impl.score.stream;
+
+public interface IntCalculator<Output_> { | Let's start getting used to `sealed` types. Let's seal every interface in the collector impl hierarchy. |
timefold-solver | github_2023 | java | 392 | TimefoldAI | triceo | @@ -0,0 +1,33 @@
+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>> | Let's follow the convention that generic type arguments end with `_`, so that we can easily distinguish them from non-generic ones.
I know we didn't do it in `ConstraintCollectors`, because the class already started like that and we kept it internally consistent throughout the years. But now that this is new code, let's make sure it honors the conventions. Please apply throughout the hierarchy.
(A, B, C and D are the exception to the rule.) |
timefold-solver | github_2023 | java | 392 | TimefoldAI | triceo | @@ -1547,14 +1121,14 @@ private static <A, B, C, D, Mapped> QuadConstraintCollector<A, B, C, D, SortedMa
* @return never null
*/
public static <A extends Comparable<A>> UniConstraintCollector<A, ?, SortedSet<A>> toSortedSet() {
- return toSortedSet(a -> a);
+ return toSortedSet(ConstantLambdaUtils.<A> identity());
}
/**
* As defined by {@link #toSortedSet()}, only with a custom {@link Comparator}.
*/
public static <A> UniConstraintCollector<A, ?, SortedSet<A>> toSortedSet(Comparator<? super A> comparator) { | No deprecation after all? |
timefold-solver | github_2023 | java | 392 | TimefoldAI | triceo | @@ -80,90 +167,56 @@ public final class ConstraintCollectors {
* @return never null
*/
public static <A> UniConstraintCollector<A, ?, Integer> count() {
- return new DefaultUniConstraintCollector<>(
- MutableInt::new,
- (resultContainer, a) -> innerCount(resultContainer),
- MutableInt::intValue);
- }
-
- private static Runnable innerCount(MutableInt resultContainer) {
- resultContainer.increment();
- return resultContainer::decrement;
+ return new IntCountUniCollector<>();
}
/**
* As defined by {@link #count()}.
*/
public static <A> UniConstraintCollector<A, ?, Long> countLong() {
- return new DefaultUniConstraintCollector<>( | And because these are no longer used and they are not public, we can delete the `Default...` implementations. Nice! |
timefold-solver | github_2023 | java | 392 | TimefoldAI | triceo | @@ -0,0 +1,17 @@
+package ai.timefold.solver.core.impl.score.stream;
+
+public final class IntCounter {
+ private int count;
+
+ public void increment() {
+ count++;
+ }
+
+ public void decrement() {
+ count--;
+ }
+
+ public Integer result() { | Since there are no generics here, can we return `int`? Let's return what we have, and deal with boxing elsewhere. |
timefold-solver | github_2023 | java | 392 | TimefoldAI | triceo | @@ -0,0 +1,17 @@
+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() { | `long` instead of `Long`? |
timefold-solver | github_2023 | java | 392 | TimefoldAI | triceo | @@ -0,0 +1,47 @@
+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("Programming error: Should have had at least one value.")); | ```suggestion
.orElseThrow(() -> new IllegalStateException("Impossible state: Should have had at least one value."));
```
"Impossible state" seems to be the convention for this. |
timefold-solver | github_2023 | java | 392 | TimefoldAI | triceo | @@ -0,0 +1,114 @@
+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 () -> Quadruple.of(firstSupplier.get(), secondSupplier.get(), thirdSupplier.get(), fourthSupplier.get());
+ }
+
+ @Override
+ public TriFunction<Quadruple<ResultHolder1_, ResultHolder2_, ResultHolder3_, ResultHolder4_>, A, B, Runnable>
+ accumulator() {
+ return (resultHolder, a, b) -> composeUndo(firstAccumulator.apply(resultHolder.getA(), a, b),
+ secondAccumulator.apply(resultHolder.getB(), a, b),
+ thirdAccumulator.apply(resultHolder.getC(), a, b),
+ fourthAccumulator.apply(resultHolder.getD(), 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.getA()),
+ secondFinisher.apply(resultHolder.getB()),
+ thirdFinisher.apply(resultHolder.getC()),
+ fourthFinisher.apply(resultHolder.getD()));
+ }
+
+ @Override
+ public boolean equals(Object object) {
+ if (this == object)
+ return true;
+ if (object == null || getClass() != object.getClass())
+ return false;
+ ComposeFourBiCollector<?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?> that = | I'd argue we can avoid this craziness with `var`.
The type is already on the right-hand side of the assignment, no need to duplicate it.
Let's try to apply it consistently. |
timefold-solver | github_2023 | java | 392 | TimefoldAI | triceo | @@ -0,0 +1,42 @@
+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> {
+
+ CountLongBiCollector() {
+ }
+
+ @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;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return o instanceof CountLongBiCollector;
+ }
+
+ @Override
+ public int hashCode() {
+ return 0;
+ } | If you make argless `count...()` a singleton, you get to avoid this, and also needless instances.
(Not that it'd ever be a problem.) |
timefold-solver | github_2023 | java | 336 | TimefoldAI | rsynek | @@ -0,0 +1,84 @@
+package ai.timefold.solver.core.api.score.constraint;
+
+import java.util.Objects;
+
+import ai.timefold.solver.core.api.domain.constraintweight.ConstraintConfiguration;
+import ai.timefold.solver.core.api.domain.constraintweight.ConstraintWeight;
+
+/**
+ * Represents a unique identifier of a constraint.
+ * <p>
+ * Users should have no need to create instances of this record.
+ * If necessary, use {@link ConstraintRef#of(String, String)} and not the record's constructors.
+ *
+ * @param packageName The constraint package is the namespace of the constraint.
+ * When using a {@link ConstraintConfiguration},
+ * it is equal to the {@link ConstraintWeight#constraintPackage()}.
+ * @param constraintName The constraint name.
+ * It might not be unique, but {@link #constraintId()} is unique.
+ * When using a {@link ConstraintConfiguration},
+ * it is equal to the {@link ConstraintWeight#value()}.
+ * @param constraintId Always derived from {@code packageName} and {@code constraintName}.
+ */
+public record ConstraintRef(String packageName, String constraintName, String constraintId)
+ implements
+ Comparable<ConstraintRef> {
+
+ private static final char PACKAGE_SEPARATOR = '/';
+
+ public static ConstraintRef of(String packageName, String constraintName) {
+ return new ConstraintRef(packageName, constraintName, null);
+ }
+
+ public static ConstraintRef parseId(String constraintId) { | nitpick: `parseConstraintId` as there is already the method `composeConstraintId`. By using the same name we make sure the user understands it's the same concept. |
timefold-solver | github_2023 | java | 336 | TimefoldAI | rsynek | @@ -174,22 +174,40 @@ public boolean isConstraintMatchEnabled() {
public final Map<String, ConstraintMatchTotal<Score_>> getConstraintMatchTotalMap() {
if (constraintMatchTotalMap == null) {
- rebuildConstraintMatchTotalsAndIndictments();
+ rebuildConstraintMatchTotals();
}
return constraintMatchTotalMap;
}
- private void rebuildConstraintMatchTotalsAndIndictments() {
- Map<String, ConstraintMatchTotal<Score_>> workingConstraintMatchTotalMap = new TreeMap<>();
- Map<Object, Indictment<Score_>> workingIndictmentMap = new LinkedHashMap<>();
- for (Map.Entry<Constraint, ElementAwareList<ConstraintMatchCarrier<Score_>>> entry : constraintMatchMap.entrySet()) {
+ private void rebuildConstraintMatchTotals() {
+ var workingConstraintMatchTotalMap = new TreeMap<String, ConstraintMatchTotal<Score_>>(); | nitpick: `constraintIdToConstraintMatchTotalMap` gives an idea what the key is. |
timefold-solver | github_2023 | java | 336 | TimefoldAI | rsynek | @@ -2,13 +2,16 @@
import java.util.List;
-public class TimefoldDevUIProperties {
+import ai.timefold.solver.core.api.score.constraint.ConstraintRef;
+
+public class TimefoldDevUIProperties { // TODO make record? | Is it a leftover or a suggestion for some next PR (just checking)? |
timefold-solver | github_2023 | java | 336 | TimefoldAI | rsynek | @@ -0,0 +1,134 @@
+package ai.timefold.solver.core.api.score.analysis;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import ai.timefold.solver.core.api.score.Score;
+import ai.timefold.solver.core.api.score.constraint.ConstraintRef;
+import ai.timefold.solver.core.api.score.stream.ConstraintJustification;
+import ai.timefold.solver.core.api.solver.SolutionManager;
+import ai.timefold.solver.core.impl.util.CollectionUtils;
+
+/**
+ * Note: Users should never create instances of this type directly. | (relevant to all records in this package): Not sure if we should take it that far, but instead of this note, we could expose just interfaces with getters and move these records implementing them to the `impl` package. That way, we make instantiation impossible. |
timefold-solver | github_2023 | java | 336 | TimefoldAI | rsynek | @@ -1,19 +1,47 @@
package ai.timefold.solver.core.api.score.stream;
+import java.util.UUID;
+
+import ai.timefold.solver.core.api.score.Score;
+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.stream.uni.UniConstraintStream;
+import ai.timefold.solver.core.api.solver.SolutionManager;
/**
* Marker interface for constraint justifications.
* All classes used as constraint justifications must implement this interface.
*
* <p>
- * No two instances of such implementing class should be equal,
- * as it is possible for the same constraint to be justified twice by the same facts.
- * (Such as in the case of a non-distinct {@link ConstraintStream}.)
+ * Implementing classes ("implementations") may decide to implement {@link Comparable}
+ * to preserve order of instances when displayed in user interfaces, logs etc.
+ * This is entirely optional.
*
* <p>
- * Implementing classes may decide to implement {@link Comparable}
- * to preserve order of instances when displayed in user interfaces, logs etc.
+ * If two instances of this class are {@link Object#equals(Object) equal},
+ * they are considered to be the same justification.
+ * This matters in case of {@link SolutionManager#analyze(Object)} score analysis
+ * where such justifications are grouped together.
+ * This situation is likely to occur in case a {@link ConstraintStream} produces duplicate tuples,
+ * which can be avoided by using {@link UniConstraintStream#distinct()} or its bi, tri and quad counterparts.
+ * Alternatively, some random ID (such as {@link UUID#randomUUID()}) can be used to distinguish between instances. | nitpicking: "random" does not necessarily imply the ID is unique; I would rather use "unique ID" |
timefold-solver | github_2023 | java | 336 | TimefoldAI | rsynek | @@ -86,4 +78,85 @@ private <Result_> Result_ callScoreDirector(Solution_ solution,
return function.apply(scoreDirector);
}
}
+
+ @Override
+ public ScoreExplanation<Solution_, Score_> explain(Solution_ solution, SolutionUpdatePolicy solutionUpdatePolicy) {
+ var currentScore = (Score_) scoreDirectorFactory.getSolutionDescriptor().getScore(solution);
+ var explanation = callScoreDirector(solution, solutionUpdatePolicy, DefaultScoreExplanation::new, true);
+ assertFreshScore(solution, currentScore, explanation.getScore(), solutionUpdatePolicy);
+ return explanation;
+ }
+
+ private void assertFreshScore(Solution_ solution, Score_ currentScore, Score_ calculatedScore,
+ SolutionUpdatePolicy solutionUpdatePolicy) {
+ if (!solutionUpdatePolicy.isScoreUpdateEnabled() && currentScore != null) {
+ // Score update is not enabled and score is not null; this means the score is supposed to be valid.
+ // Yet it is different from a freshly calculated score, suggesting previous score corruption.
+ if (!calculatedScore.equals(currentScore)) {
+ throw new IllegalStateException("""
+ Current score (%s) and freshly calculated score (%s) for solution (%s) do not match.
+ Maybe run %s environment mode to check for score corruptions.
+ Otherwise enable %s.%s to update the stale score.
+ """
+ .formatted(currentScore, calculatedScore, solution, EnvironmentMode.FULL_ASSERT,
+ SolutionUpdatePolicy.class.getSimpleName(),
+ SolutionUpdatePolicy.UPDATE_ALL));
+ }
+ }
+ }
+
+ @Override
+ public ScoreAnalysis<Score_> analyze(Solution_ solution, ScoreAnalysisFetchPolicy fetchPolicy,
+ SolutionUpdatePolicy solutionUpdatePolicy) {
+ Objects.requireNonNull(fetchPolicy, "fetchPolicy");
+ var currentScore = (Score_) scoreDirectorFactory.getSolutionDescriptor().getScore(solution);
+ var analysis = callScoreDirector(solution, solutionUpdatePolicy, scoreDirector -> {
+ var score = scoreDirector.calculateScore();
+ if (!score.isSolutionInitialized()) {
+ throw new IllegalArgumentException("""
+ Cannot analyze solution (%s) as it is not initialized (%s).
+ Maybe run the solver first?"""
+ .formatted(solution, score));
+ }
+ var constraintAnalysisMap = new TreeMap<ConstraintRef, ConstraintAnalysis<Score_>>();
+ for (var constraintMatchTotal : scoreDirector.getConstraintMatchTotalMap().values()) {
+ var constraintAnalysis =
+ getConstraintAnalysis(constraintMatchTotal, fetchPolicy == ScoreAnalysisFetchPolicy.FETCH_ALL);
+ constraintAnalysisMap.put(constraintMatchTotal.getConstraintRef(), constraintAnalysis);
+ }
+ return new ScoreAnalysis<>(score, constraintAnalysisMap);
+ }, true);
+ assertFreshScore(solution, currentScore, analysis.score(), solutionUpdatePolicy);
+ return analysis;
+ }
+
+ public static <Score_ extends Score<Score_>> ConstraintAnalysis<Score_> | Is there a reason for having this method public on the implementation class? |
timefold-solver | github_2023 | java | 336 | TimefoldAI | rsynek | @@ -41,6 +57,126 @@ void polymorphicScore() {
.isEqualTo(BendableScore.of(new int[] { -1, -20 }, new int[] { -300, -4000, -50000 }));
}
+ @Test
+ void scoreAnalysisWithoutMatches() throws JsonProcessingException {
+ ObjectMapper objectMapper = new ObjectMapper();
+ objectMapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
+ objectMapper.registerModule(TimefoldJacksonModule.createModule());
+
+ var constraintRef1 = ConstraintRef.of("package1", "constraint1");
+ var constraintRef2 = ConstraintRef.of("package2", "constraint2");
+ var constraintAnalysis1 = new ConstraintAnalysis<>(HardSoftScore.ofHard(1), 0, null);
+ var constraintAnalysis2 = new ConstraintAnalysis<>(HardSoftScore.ofSoft(2), 0, null);
+ var originalScoreAnalysis = new ScoreAnalysis<>(HardSoftScore.of(1, 2),
+ Map.of(constraintRef1, constraintAnalysis1,
+ constraintRef2, constraintAnalysis2));
+
+ var serialized = objectMapper.writeValueAsString(originalScoreAnalysis);
+ Assertions.assertThat(serialized)
+ .isEqualToIgnoringWhitespace("""
+ {
+ "score" : "1hard/2soft",
+ "constraints" : [ {
+ "id" : "package1/constraint1",
+ "score" : "1hard/0soft"
+ }, {
+ "id" : "package2/constraint2",
+ "score" : "0hard/2soft"
+ } ]
+ }""");
+
+ objectMapper.registerModule(new CustomJacksonModule());
+ ScoreAnalysis<HardSoftScore> deserialized = objectMapper.readValue(serialized, ScoreAnalysis.class);
+ Assertions.assertThat(deserialized).isEqualTo(originalScoreAnalysis);
+ }
+
+ @Test
+ void scoreAnalysisWithMatches() throws JsonProcessingException {
+ ObjectMapper objectMapper = new ObjectMapper();
+ objectMapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
+ objectMapper.registerModule(TimefoldJacksonModule.createModule());
+
+ var constraintRef1 = ConstraintRef.of("package1", "constraint1");
+ var constraintRef2 = ConstraintRef.of("package2", "constraint2");
+ var matchAnalysis1 = new MatchAnalysis<>(HardSoftScore.ofHard(1),
+ DefaultConstraintJustification.of(HardSoftScore.ofHard(1), "A", "B"));
+ var matchAnalysis2 = new MatchAnalysis<>(HardSoftScore.ofHard(1),
+ DefaultConstraintJustification.of(HardSoftScore.ofHard(1), "B", "C", "D"));
+ var matchAnalysis3 = new MatchAnalysis<>(HardSoftScore.ofSoft(1),
+ DefaultConstraintJustification.of(HardSoftScore.ofSoft(1), "D"));
+ var matchAnalysis4 = new MatchAnalysis<>(HardSoftScore.ofSoft(3),
+ DefaultConstraintJustification.of(HardSoftScore.ofSoft(3), "A", "C"));
+ var constraintAnalysis1 = new ConstraintAnalysis<>(HardSoftScore.ofHard(2), 2, List.of(matchAnalysis1, matchAnalysis2));
+ var constraintAnalysis2 = new ConstraintAnalysis<>(HardSoftScore.ofSoft(4), 2, List.of(matchAnalysis3, matchAnalysis4));
+ var originalScoreAnalysis = new ScoreAnalysis<>(HardSoftScore.of(2, 4),
+ Map.of(constraintRef1, constraintAnalysis1,
+ constraintRef2, constraintAnalysis2));
+
+ var serialized = objectMapper.writeValueAsString(originalScoreAnalysis);
+ Assertions.assertThat(serialized)
+ .isEqualToIgnoringWhitespace("""
+ {
+ "score" : "2hard/4soft",
+ "constraints" : [ {
+ "id" : "package1/constraint1",
+ "score" : "2hard/0soft",
+ "matches" : [ {
+ "score" : "1hard/0soft",
+ "justification" : [ "A", "B" ]
+ }, {
+ "score" : "1hard/0soft",
+ "justification" : [ "B", "C", "D" ]
+ } ]
+ }, {
+ "id" : "package2/constraint2",
+ "score" : "0hard/4soft",
+ "matches" : [ {
+ "score" : "0hard/1soft",
+ "justification" : [ "D" ]
+ }, {
+ "score" : "0hard/3soft",
+ "justification" : [ "A", "C" ]
+ } ]
+ } ]
+ }""");
+
+ objectMapper.registerModule(new CustomJacksonModule());
+ ScoreAnalysis<HardSoftScore> deserialized = objectMapper.readValue(serialized, ScoreAnalysis.class);
+ Assertions.assertThat(deserialized).isEqualTo(originalScoreAnalysis);
+ }
+
+ public static final class CustomJacksonModule extends SimpleModule {
+
+ public CustomJacksonModule() {
+ super("Timefold Custom");
+ addDeserializer(ScoreAnalysis.class, new CustomScoreAnalysisJacksonDeserializer());
+ }
+
+ }
+
+ public static final class CustomScoreAnalysisJacksonDeserializer
+ extends AbstractScoreAnalysisJacksonDeserializer<HardSoftScore> {
+
+ @Override
+ protected HardSoftScore parseScore(String scoreString) {
+ return HardSoftScore.parseScore(scoreString);
+ }
+
+ @Override
+ protected <ConstraintJustification_ extends ConstraintJustification> ConstraintJustification_
+ parseConstraintJustification(ConstraintRef constraintRef, String constraintJustificationString,
+ HardSoftScore score) {
+ List<Object> justificationList = Arrays.stream(constraintJustificationString.split(","))
+ .map(s -> s.replace("[", "")
+ .replace("]", "")
+ .replace("\"", "")
+ .strip())
+ .collect(Collectors.toList());
+ return (ConstraintJustification_) DefaultConstraintJustification.of(score, justificationList); | Can the justification be just any object and it's a list just in this example, or is it always a list? |
timefold-solver | github_2023 | java | 374 | TimefoldAI | triceo | @@ -252,4 +252,12 @@ default void expandToQuad() {
void impactNegativeBigDecimalCustomJustifications();
+ // ************************************************************************ | Let's start a new `NodeSharingTest` for this. |
timefold-solver | github_2023 | java | 374 | TimefoldAI | triceo | @@ -3000,4 +3008,190 @@ public void joinerEqualsAndSameness() {
assertMatch(entity3, entity2));
}
+ // ************************************************************************
+ // Node Sharing
+ // ************************************************************************
+
+ @Override
+ @TestTemplate
+ public void shareNodesWithSameInput() {
+ final List<String> failureList = new ArrayList<>();
+ buildScoreDirector(
+ TestdataSolution.buildSolutionDescriptor(),
+ factory -> {
+ BiConstraintStream<TestdataEntity, TestdataEntity> base =
+ factory.forEach(TestdataEntity.class).join(TestdataEntity.class);
+ Function<TestdataEntity, TestdataEntity> function = a -> a;
+ BiFunction<TestdataEntity, TestdataEntity, TestdataEntity> bifunction = (a, b) -> a;
+ Function<TestdataEntity, Iterable<String>> iterableFunction = a -> Collections.emptyList();
+ BiPredicate<TestdataEntity, TestdataEntity> bipredicate = (a, b) -> true;
+ TriPredicate<TestdataEntity, TestdataEntity, TestdataEntity> tripredicate = (a, b, c) -> true;
+
+ if (base.join(TestdataEntity.class) != base.join(TestdataEntity.class)) {
+ failureList.add("join(no-joiners)");
+ } | This is needlessly complicated. Since you never need to call those constraint streams, you don't need `buildScoreDirector` or `failureList`.
Let's change the test to look like this:
Assertions.assertThat(base.join(...))
.as(...)
.isSameAs(base.join(...)
Maybe you'll need to figure out how to get a ConstraintFactory instance, but it will be better than using this `failureList` hack. It is also part of my reasoning for having this in a new test class, because this will require new approaches and generally be unlike the other tests in the current class. |
timefold-solver | github_2023 | java | 374 | TimefoldAI | triceo | @@ -0,0 +1,216 @@
+package ai.timefold.solver.core.impl.util;
+
+import java.util.Objects;
+import java.util.function.BiFunction;
+import java.util.function.BiPredicate;
+import java.util.function.Function;
+import java.util.function.ToIntBiFunction;
+import java.util.function.ToIntFunction;
+
+import ai.timefold.solver.core.api.function.QuadFunction;
+import ai.timefold.solver.core.api.function.ToIntQuadFunction;
+import ai.timefold.solver.core.api.function.ToIntTriFunction;
+import ai.timefold.solver.core.api.function.TriFunction;
+
+/**
+ * A class that hold common lambdas that are guarantee to be the same across method calls. In most JDK's, stateless lambdas are
+ * bound to a {@link java.lang.invoke.ConstantCallSite} inside the method that define them, but that
+ * {@link java.lang.invoke.ConstantCallSite} is not shared across methods (even for methods in the same class). Thus, when
+ * lambda reference equality is important (such as for node sharing in Constraint Streams), the lambdas in this class should be
+ * used.
+ */
+public final class ConstantLambdaUtils { | Let's add a private constructor to prevent instances. |
timefold-solver | github_2023 | java | 374 | TimefoldAI | triceo | @@ -0,0 +1,216 @@
+package ai.timefold.solver.core.impl.util;
+
+import java.util.Objects;
+import java.util.function.BiFunction;
+import java.util.function.BiPredicate;
+import java.util.function.Function;
+import java.util.function.ToIntBiFunction;
+import java.util.function.ToIntFunction;
+
+import ai.timefold.solver.core.api.function.QuadFunction;
+import ai.timefold.solver.core.api.function.ToIntQuadFunction;
+import ai.timefold.solver.core.api.function.ToIntTriFunction;
+import ai.timefold.solver.core.api.function.TriFunction;
+
+/**
+ * A class that hold common lambdas that are guarantee to be the same across method calls. In most JDK's, stateless lambdas are | ```suggestion
* A class that holds common lambdas that are guaranteed to be the same across method calls. In most JDK's, stateless lambdas are
``` |
timefold-solver | github_2023 | java | 374 | TimefoldAI | triceo | @@ -0,0 +1,216 @@
+package ai.timefold.solver.core.impl.util;
+
+import java.util.Objects;
+import java.util.function.BiFunction;
+import java.util.function.BiPredicate;
+import java.util.function.Function;
+import java.util.function.ToIntBiFunction;
+import java.util.function.ToIntFunction;
+
+import ai.timefold.solver.core.api.function.QuadFunction;
+import ai.timefold.solver.core.api.function.ToIntQuadFunction;
+import ai.timefold.solver.core.api.function.ToIntTriFunction;
+import ai.timefold.solver.core.api.function.TriFunction;
+
+/**
+ * A class that hold common lambdas that are guarantee to be the same across method calls. In most JDK's, stateless lambdas are
+ * bound to a {@link java.lang.invoke.ConstantCallSite} inside the method that define them, but that
+ * {@link java.lang.invoke.ConstantCallSite} is not shared across methods (even for methods in the same class). Thus, when
+ * lambda reference equality is important (such as for node sharing in Constraint Streams), the lambdas in this class should be
+ * used.
+ */
+public final class ConstantLambdaUtils {
+ @SuppressWarnings("rawtypes")
+ private static final Function IDENTITY = Function.identity();
+
+ @SuppressWarnings("rawtypes")
+ private static final BiPredicate NOT_EQUALS = (a, b) -> !Objects.equals(a, b);
+
+ @SuppressWarnings("rawtypes")
+ private static final BiFunction BI_PICK_FIRST = (a, b) -> a;
+
+ @SuppressWarnings("rawtypes")
+ private static final TriFunction TRI_PICK_FIRST = (a, b, c) -> a;
+
+ @SuppressWarnings("rawtypes")
+ private static final QuadFunction QUAD_PICK_FIRST = (a, b, c, d) -> a;
+
+ @SuppressWarnings("rawtypes")
+ private static final BiFunction BI_PICK_SECOND = (a, b) -> b;
+
+ @SuppressWarnings("rawtypes")
+ private static final TriFunction TRI_PICK_SECOND = (a, b, c) -> b;
+
+ @SuppressWarnings("rawtypes")
+ private static final QuadFunction QUAD_PICK_SECOND = (a, b, c, d) -> b;
+
+ @SuppressWarnings("rawtypes")
+ private static final TriFunction TRI_PICK_THIRD = (a, b, c) -> c;
+
+ @SuppressWarnings("rawtypes")
+ private static final QuadFunction QUAD_PICK_THIRD = (a, b, c, d) -> c;
+
+ @SuppressWarnings("rawtypes")
+ private static final QuadFunction QUAD_PICK_FOURTH = (a, b, c, d) -> d;
+
+ @SuppressWarnings("rawtypes")
+ private static final ToIntFunction UNI_CONSTANT_ONE = (a) -> 1;
+ @SuppressWarnings("rawtypes")
+ private static final ToIntBiFunction BI_CONSTANT_ONE = (a, b) -> 1;
+ @SuppressWarnings("rawtypes")
+ private static final ToIntTriFunction TRI_CONSTANT_ONE = (a, b, c) -> 1;
+
+ @SuppressWarnings("rawtypes") | Let's have consistent whitespace. Either use newlines, or don't.
If you want to separate blocks of lambdas, do so, but do it consistently. |
timefold-solver | github_2023 | others | 379 | TimefoldAI | triceo | @@ -66,6 +66,23 @@ $ mvn exec:java
This is an open source project, and you are more than welcome to contribute!
For more, see link:CONTRIBUTING.adoc[Contributing].
+== Editions
+
+There are 2 editions of Timefold Solver:
+
+- Timefold Solver Community Edition (CE) (this repo).
+- Timefold Solver Enterprise Edition (EE), a licensed version of Timefold Solver.
+
+Key Features of Timefold Enterprise Edition (EE) | ```suggestion
=== Key Features of Enterprise Edition (EE)
``` |
timefold-solver | github_2023 | others | 379 | TimefoldAI | triceo | @@ -66,6 +66,23 @@ $ mvn exec:java
This is an open source project, and you are more than welcome to contribute!
For more, see link:CONTRIBUTING.adoc[Contributing].
+== Editions
+
+There are 2 editions of Timefold Solver:
+
+- Timefold Solver Community Edition (CE) (this repo).
+- Timefold Solver Enterprise Edition (EE), a licensed version of Timefold Solver.
+
+Key Features of Timefold Enterprise Edition (EE)
+
+- **Multi-threaded Solving:** Experience enhanced performance with multi-threaded solving capabilities.
+- **Nearby Selection:** Get better solution quicker, especially with spatial problems.
+- **Dedicated Support:** Get direct support from the Timefold team for all your questions and requirements.
+
+Licensing and Usage | ```suggestion
=== Licensing and Usage
``` |
timefold-solver | github_2023 | others | 379 | TimefoldAI | triceo | @@ -66,6 +66,23 @@ $ mvn exec:java
This is an open source project, and you are more than welcome to contribute!
For more, see link:CONTRIBUTING.adoc[Contributing].
+== Editions
+
+There are 2 editions of Timefold Solver:
+
+- Timefold Solver Community Edition (CE) (this repo).
+- Timefold Solver Enterprise Edition (EE), a licensed version of Timefold Solver.
+
+Key Features of Timefold Enterprise Edition (EE)
+
+- **Multi-threaded Solving:** Experience enhanced performance with multi-threaded solving capabilities.
+- **Nearby Selection:** Get better solution quicker, especially with spatial problems. | ```suggestion
- **Nearby Selection:** Get better solutions quicker, especially with spatial problems.
``` |
timefold-solver | github_2023 | others | 379 | TimefoldAI | triceo | @@ -66,6 +66,23 @@ $ mvn exec:java
This is an open source project, and you are more than welcome to contribute!
For more, see link:CONTRIBUTING.adoc[Contributing].
+== Editions
+
+There are 2 editions of Timefold Solver:
+
+- Timefold Solver Community Edition (CE) (this repo).
+- Timefold Solver Enterprise Edition (EE), a licensed version of Timefold Solver.
+
+=== Key Features of Timefold Enterprise Edition (EE) | ```suggestion
=== Key Features of Timefold Solver Enterprise Edition (EE)
``` |
timefold-solver | github_2023 | java | 369 | TimefoldAI | triceo | @@ -0,0 +1,59 @@
+package ai.timefold.solver.core.impl.util;
+
+import java.util.Objects;
+import java.util.function.BiFunction;
+import java.util.function.BiPredicate;
+import java.util.function.Function;
+import java.util.function.ToIntBiFunction;
+import java.util.function.ToIntFunction;
+
+import ai.timefold.solver.core.api.function.QuadFunction;
+import ai.timefold.solver.core.api.function.ToIntQuadFunction;
+import ai.timefold.solver.core.api.function.ToIntTriFunction;
+import ai.timefold.solver.core.api.function.TriFunction;
+
+public final class ConstantLambdaUtils { | If these functions are returned via static methods, you can get the casting done inside the methods, as opposed to plaguing the entire codebase with it.
Example:
public static final <A, B> BiPredicate<A, B> notEquals() {
return (BiPredicate<A, B>) NOT_EQUALS;
} |
timefold-solver | github_2023 | others | 81 | TimefoldAI | rsynek | @@ -0,0 +1,54 @@
+name: Downstream - Timefold Quickstarts
+
+on:
+ pull_request:
+ branches: [main]
+ paths-ignore:
+ - 'LICENSE*'
+ - '.gitignore'
+ - '**.md'
+ - '**.adoc'
+ - '*.txt'
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ concurrency:
+ group: downstream-quickstarts-${{ github.event_name }}-${{ github.head_ref }}
+ cancel-in-progress: true
+ timeout-minutes: 120
+ steps:
+ - name: Checkout timefold-solver
+ uses: actions/checkout@v3
+ with:
+ path: ./timefold-solver
+ - name: Find the proper downstream repo and branch
+ env:
+ DOWNSTREAM_USER: ${{ github.actor }}
+ DOWNSTREAM_BRANCH: ${{ github.head_ref }}
+ DOWNSTREAM_REPO: "timefold-quickstarts"
+ DOWNSTREAM_DEFAULT_BRANCH: "development"
+ shell: bash
+ run: |
+ chmod +x ./timefold-solver/.github/scripts/check_downstream_repo.sh | Can we set the executable flag for the script as a part of this PR instead of doing it each time in the GHA? |
timefold-solver | github_2023 | others | 81 | TimefoldAI | rsynek | @@ -0,0 +1,54 @@
+name: Downstream - Timefold Quickstarts
+
+on:
+ pull_request:
+ branches: [main] | We will eventually have also release branches. |
timefold-solver | github_2023 | others | 81 | TimefoldAI | rsynek | @@ -0,0 +1,54 @@
+name: Downstream - Timefold Quickstarts
+
+on:
+ pull_request: | That's a question. Cloning the PR author repositories without merging with the target repositories does not protected from stale PR, which might, in theory, result in issues only after merging the PR.
If we want to cover this corner case, we have to either A) merge the forks with origin repos before the build or B) set up a GHA that checks the repositories again after merging.
Obviously, A) is more complex, but we get the result before merging the PR, while B) is easier, but also wasteful (we run the tests twice) and comes a bit too late. |
timefold-solver | github_2023 | java | 340 | TimefoldAI | Christopher-Chianelli | @@ -65,7 +65,7 @@ private static RuntimeException createJustificationException(Constraint constrai
private static String factsToString(Object... facts) {
return Arrays.stream(facts)
- .map(Object::toString)
+ .map(s -> s == null ? null : s.toString()) | Maybe `Objects::toString`? https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#toString-java.lang.Object- |
timefold-solver | github_2023 | others | 340 | TimefoldAI | Christopher-Chianelli | @@ -1514,10 +1514,14 @@ See <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,`distinct()`>> fo
[[constraintStreamsConcat]]
==== Concat
-The `concat` building block allows you to create a constraint stream containing tuples of two constraint streams of the same <<constraintStreamsCardinality,cardinality>>.
-If <<constraintStreamsJoin,join>> acts like a cartesian product of two lists, `concat` acts like a concatenation of two lists.
+The `concat` building block allows you to create a constraint stream containing tuples
+of two constraint streams of the same <<constraintStreamsCardinality,cardinality>>. | Inaccurate, since now multiple cardinalities are allowed |
timefold-solver | github_2023 | java | 346 | TimefoldAI | triceo | @@ -52,8 +52,11 @@ public class GizmoSolutionClonerImplementor {
Object.class);
private static final MethodDescriptor PUT_METHOD = MethodDescriptor.ofMethod(Map.class, "put", Object.class,
Object.class, Object.class);
+ private static final String FALLBACK_CLONER = "fallbackCloner";
public static final boolean DEBUG = false;
+ public static boolean IS_QUARKUS = false; | Let's figure out a different way to pass this information. Static mutable fields are fundamentally wrong, and we've seen it numerous times already.
Do we need a Quarkus-specific subtype? So be it.
Quarkus-specific constructor? Sure.
Just not this, please.
In my opinion, the fact that there are ifs for particular situations screams for two distinct implementations with a shared supertype, or the lambda/strategy pattern. |
timefold-solver | github_2023 | java | 346 | TimefoldAI | triceo | @@ -28,7 +28,8 @@ public static <T> SolutionCloner<T> build(SolutionDescriptor<T> solutionDescript
") the classpath or modulepath must contain io.quarkus.gizmo:gizmo.\n" +
"Maybe add a dependency to io.quarkus.gizmo:gizmo.");
}
- return GizmoSolutionClonerImplementor.createClonerFor(solutionDescriptor, gizmoClassLoader);
+ return new GizmoSolutionClonerImplementor().createClonerFor(solutionDescriptor, | Why not:
```suggestion
return GizmoSolutionClonerImplementor.createClonerFor(solutionDescriptor,
```
Seems like the instance creation is just boilerplate, it can happen internally. People need not know what's happening under the covers. |
timefold-solver | github_2023 | java | 346 | TimefoldAI | triceo | @@ -100,14 +101,20 @@ public static Comparator<Class<?>> getInstanceOfComparator(Set<Class<?>> deepClo
.thenComparing(Class::getName).reversed();
}
+ protected void createFields(ClassCreator classCreator) {
+ classCreator.getFieldCreator(FALLBACK_CLONER, FieldAccessingSolutionCloner.class)
+ .setModifiers(Modifier.PRIVATE | Modifier.STATIC);
+ } | Could have stayed static. |
timefold-solver | github_2023 | java | 346 | TimefoldAI | triceo | @@ -417,6 +419,76 @@ public String generateGizmoBeanFactory(ClassOutput classOutput, Set<Class<?>> be
return generatedClassName;
}
+ private static class QuarkusGizmoSolutionClonerImplementor extends GizmoSolutionClonerImplementor { | The class is IMO a big too big to be an inner class. Consider making it a top-level class; it's already static, so you don't need the reference to the outer class. |
timefold-solver | github_2023 | java | 346 | TimefoldAI | triceo | @@ -69,7 +69,7 @@ protected <Solution_> SolutionCloner<Solution_> createSolutionCloner(SolutionDes
generateGizmoSolutionOrEntityDescriptor(solutionDescriptor, clazz));
});
- GizmoSolutionClonerImplementor.defineClonerFor(classCreator, solutionDescriptor,
+ new GizmoSolutionClonerImplementor().defineClonerFor(classCreator, solutionDescriptor, | Same comment as above; I think it could've been made static and hidden the instance. |
timefold-solver | github_2023 | java | 338 | TimefoldAI | triceo | @@ -125,11 +129,26 @@ private Optional<ListVariableDescriptor<?>> findValidListVariableDescriptor(
+ listVariableDescriptors + ").");
}
+ ListVariableDescriptor<Solution_> listVariableDescriptor = listVariableDescriptors.get(0);
+ failIfBasicAndListVariablesAreCombinedOnSingleEntity(listVariableDescriptor);
failIfConfigured(phaseConfig.getConstructionHeuristicType(), "constructionHeuristicType");
failIfConfigured(phaseConfig.getEntityPlacerConfig(), "entityPlacerConfig");
failIfConfigured(phaseConfig.getMoveSelectorConfigList(), "moveSelectorConfigList");
- return Optional.of(listVariableDescriptors.get(0));
+ return Optional.of(listVariableDescriptor);
+ }
+
+ private static void failIfBasicAndListVariablesAreCombinedOnSingleEntity(ListVariableDescriptor<?> listVariableDescriptor) { | I'd argue this needs to happen earlier, before the CH, when the solver config is being processed. |
timefold-solver | github_2023 | java | 338 | TimefoldAI | triceo | @@ -125,11 +129,26 @@ private Optional<ListVariableDescriptor<?>> findValidListVariableDescriptor(
+ listVariableDescriptors + ").");
}
+ ListVariableDescriptor<Solution_> listVariableDescriptor = listVariableDescriptors.get(0);
+ failIfBasicAndListVariablesAreCombinedOnSingleEntity(listVariableDescriptor);
failIfConfigured(phaseConfig.getConstructionHeuristicType(), "constructionHeuristicType");
failIfConfigured(phaseConfig.getEntityPlacerConfig(), "entityPlacerConfig");
failIfConfigured(phaseConfig.getMoveSelectorConfigList(), "moveSelectorConfigList");
- return Optional.of(listVariableDescriptors.get(0));
+ return Optional.of(listVariableDescriptor);
+ }
+
+ private static void failIfBasicAndListVariablesAreCombinedOnSingleEntity(ListVariableDescriptor<?> listVariableDescriptor) {
+ EntityDescriptor<?> listVariableEntityDescriptor = listVariableDescriptor.getEntityDescriptor();
+ if (listVariableEntityDescriptor.getDeclaredGenuineVariableDescriptors().size() > 1) {
+ Collection<GenuineVariableDescriptor<?>> basicVariableDescriptors =
+ new ArrayList<>(listVariableEntityDescriptor.getDeclaredGenuineVariableDescriptors());
+ basicVariableDescriptors.remove(listVariableDescriptor);
+ throw new IllegalArgumentException(
+ "Construction Heuristic phase does not support combination of basic variables ("
+ + basicVariableDescriptors + ") and list variables (" + listVariableDescriptor
+ + ") on a single planning entity (" + listVariableDescriptor.getEntityDescriptor() + ")."); | ```suggestion
throw new UnsupportedOperationException("""
Combining basic variables (%s) with list variables (%) on a single planning entity (%s) is currently not supported.
""".formatted(basicVariableDescriptors, listVariableDescriptor, listVariableDescriptor.getEntityDescriptor()));
```
Arguably, this is not a limitation of CH, this is a limitation of the solver. Basic and list variables simply can not be combined. |
timefold-solver | github_2023 | java | 338 | TimefoldAI | triceo | @@ -221,6 +224,20 @@ void variableWithPlanningIdIsARecord() {
Assertions.assertThatNoException().isThrownBy(() -> solver.solve(solution));
}
+ @Test
+ void entityWithMixedBasicAndListPlanningVariables() {
+ var solverConfig = new SolverConfig()
+ .withSolutionClass(DummySolutionWithMixedSimpleAndListVariableEntity.class)
+ .withEntityClasses(DummyEntityWithMixedSimpleAndListVariable.class)
+ .withEasyScoreCalculatorClass(DummyRecordEasyScoreCalculator.class)
+ .withPhases(new ConstructionHeuristicPhaseConfig()); | This last line shouldn't be necessary. AFAIK phases are auto-configured if not present. |
timefold-solver | github_2023 | java | 338 | TimefoldAI | triceo | @@ -549,6 +551,31 @@ private void determineGlobalShadowOrder() {
}
}
+ private void validateListVariableDescriptors() {
+ if (listVariableDescriptors.isEmpty()) {
+ return;
+ }
+
+ if (listVariableDescriptors.size() > 1) {
+ throw new UnsupportedOperationException(
+ "Defining multiple list variables (%s) across the model is currently not supported."
+ .formatted(listVariableDescriptors));
+ }
+
+ ListVariableDescriptor<Solution_> listVariableDescriptor = listVariableDescriptors.get(0);
+ EntityDescriptor<?> listVariableEntityDescriptor = listVariableDescriptor.getEntityDescriptor();
+ if (listVariableEntityDescriptor.getGenuineVariableDescriptorList().size() > 1) {
+ Collection<GenuineVariableDescriptor<?>> basicVariableDescriptors =
+ new ArrayList<>(listVariableEntityDescriptor.getGenuineVariableDescriptorList());
+ basicVariableDescriptors.remove(listVariableDescriptor);
+ throw new UnsupportedOperationException(
+ ("Combining basic variables (%s) with list variables (%s) on a single planning entity (%s)" +
+ " is currently not supported.") | ```suggestion
"Combining basic variables (%s) with list variables (%s) on a single planning entity (%s)" +
" is currently not supported."
``` |
timefold-solver | github_2023 | java | 338 | TimefoldAI | triceo | @@ -549,6 +551,31 @@ private void determineGlobalShadowOrder() {
}
}
+ private void validateListVariableDescriptors() {
+ if (listVariableDescriptors.isEmpty()) {
+ return;
+ }
+
+ if (listVariableDescriptors.size() > 1) {
+ throw new UnsupportedOperationException(
+ "Defining multiple list variables (%s) across the model is currently not supported."
+ .formatted(listVariableDescriptors));
+ }
+
+ ListVariableDescriptor<Solution_> listVariableDescriptor = listVariableDescriptors.get(0);
+ EntityDescriptor<?> listVariableEntityDescriptor = listVariableDescriptor.getEntityDescriptor();
+ if (listVariableEntityDescriptor.getGenuineVariableDescriptorList().size() > 1) {
+ Collection<GenuineVariableDescriptor<?>> basicVariableDescriptors =
+ new ArrayList<>(listVariableEntityDescriptor.getGenuineVariableDescriptorList());
+ basicVariableDescriptors.remove(listVariableDescriptor);
+ throw new UnsupportedOperationException(
+ "Combining basic variables (%s) with list variables (%s) on a single planning entity (%s)" +
+ " is currently not supported."
+ .formatted(basicVariableDescriptors, listVariableDescriptor,
+ listVariableDescriptor.getEntityDescriptor().getEntityClass().getName())); | ```suggestion
listVariableDescriptor.getEntityDescriptor().getEntityClass().getCanonicalName()));
``` |
timefold-solver | github_2023 | others | 337 | TimefoldAI | triceo | @@ -1030,9 +1030,14 @@ public class StartTimeUpdatingVariableListener implements VariableListener<TaskA
==== Planning value
A planning value is a possible value for a genuine planning variable.
-Usually, a planning value is a problem fact, but it can also be any object, for example a ``double``.
+Usually, a planning value is a problem fact, but it can also be any object, for example a ``Double``. | ```suggestion
Usually, a planning value is a problem fact, but it can also be any object, for example an ``Integer``.
``` |
timefold-solver | github_2023 | others | 337 | TimefoldAI | triceo | @@ -1030,9 +1030,14 @@ public class StartTimeUpdatingVariableListener implements VariableListener<TaskA
==== Planning value
A planning value is a possible value for a genuine planning variable.
-Usually, a planning value is a problem fact, but it can also be any object, for example a ``double``.
+Usually, a planning value is a problem fact, but it can also be any object, for example a ``Double``.
It can even be another planning entity or even an interface implemented by both a planning entity and a problem fact.
+[NOTE]
+====
+Primitive types (such as ``double``) are not allowed. | ```suggestion
Primitive types (such as ``int``) are not allowed.
``` |
timefold-solver | github_2023 | java | 297 | TimefoldAI | triceo | @@ -140,6 +141,13 @@ private long determineLayerIndex(AbstractNode node, NodeBuildHelper<Score_> buil
var leftParentNode = buildHelper.findParentNode(leftParent);
var rightParentNode = buildHelper.findParentNode(rightParent);
return Math.max(leftParentNode.getLayerIndex(), rightParentNode.getLayerIndex()) + 1;
+ } else if (node instanceof AbstractConcatNode<?> concatNode) {
+ var nodeCreator = (BavetJoinConstraintStream<?>) buildHelper.getNodeCreatingStream(concatNode); | Why would concat implement join? The two operations have barely anything in common. |
timefold-solver | github_2023 | java | 297 | TimefoldAI | triceo | @@ -359,6 +359,19 @@ public BiConstraintStream<A, B> distinct() {
}
}
+ @Override
+ public BiConstraintStream<A, B> concat(BiConstraintStream<A, B> otherStream) {
+ var other = (BavetAbstractBiConstraintStream<Solution_, A, B>) otherStream;
+ var leftBridge = new BavetForeBridgeBiConstraintStream<>(constraintFactory, this);
+ var rightBridge = new BavetForeBridgeBiConstraintStream<>(constraintFactory, other);
+ var concatStream = new BavetConcatBiConstraintStream<>(constraintFactory, leftBridge, rightBridge);
+ return constraintFactory.share(concatStream, concatStream_ -> {
+ // Connect the bridges upstream, as it is an actual new join. | This is not a join; let's not call it like that. |
timefold-solver | github_2023 | java | 297 | TimefoldAI | triceo | @@ -0,0 +1,19 @@
+package ai.timefold.solver.constraint.streams.bavet.bi;
+
+import ai.timefold.solver.constraint.streams.bavet.common.AbstractConcatNode;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.BiTuple;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleLifecycle;
+
+public final class BavetBiConcatNode<A, B> extends AbstractConcatNode<BiTuple<A, B>> {
+
+ BavetBiConcatNode(TupleLifecycle<BiTuple<A, B>> nextNodesTupleLifecycle, int inputStoreIndexLeftOutTupleList,
+ int inputStoreIndexRightOutTupleList,
+ int outputStoreSize) {
+ super(nextNodesTupleLifecycle, inputStoreIndexLeftOutTupleList, inputStoreIndexRightOutTupleList, outputStoreSize);
+ }
+
+ @Override
+ protected BiTuple<A, B> getOutTuple(BiTuple<A, B> inTuple) {
+ return new BiTuple<>(inTuple.factA, inTuple.factB, outputStoreSize); | Since concat does not modify the tuples, it doesn't need to create new ones.
I'm betting it will be much more efficient if it's rewritten as a pass-through node, without node creation. |
timefold-solver | github_2023 | java | 297 | TimefoldAI | triceo | @@ -0,0 +1,103 @@
+package ai.timefold.solver.constraint.streams.bavet.common;
+
+import static ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleState.ABORTING;
+import static ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleState.CREATING;
+import static ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleState.DYING;
+
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.AbstractTuple;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.LeftTupleLifecycle;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.RightTupleLifecycle;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleLifecycle;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleState;
+
+public abstract class AbstractConcatNode<Tuple_ extends AbstractTuple>
+ extends AbstractNode
+ implements LeftTupleLifecycle<Tuple_>, RightTupleLifecycle<Tuple_> {
+ private final int inputStoreIndexLeftOutTupleList;
+ private final int inputStoreIndexRightOutTupleList;
+ protected final int outputStoreSize;
+ private final StaticPropagationQueue<Tuple_> propagationQueue;
+
+ protected AbstractConcatNode(TupleLifecycle<Tuple_> nextNodesTupleLifecycle,
+ int inputStoreIndexLeftOutTupleList,
+ int inputStoreIndexRightOutTupleList,
+ int outputStoreSize) {
+ this.propagationQueue = new StaticPropagationQueue<>(nextNodesTupleLifecycle);
+ this.inputStoreIndexLeftOutTupleList = inputStoreIndexLeftOutTupleList;
+ this.inputStoreIndexRightOutTupleList = inputStoreIndexRightOutTupleList;
+ this.outputStoreSize = outputStoreSize;
+ }
+
+ protected abstract Tuple_ getOutTuple(Tuple_ inTuple);
+
+ @Override
+ public final void insertLeft(Tuple_ tuple) {
+ Tuple_ outTuple = getOutTuple(tuple);
+ tuple.setStore(inputStoreIndexLeftOutTupleList, outTuple);
+ propagationQueue.insert(outTuple);
+ }
+
+ @Override
+ public final void updateLeft(Tuple_ tuple) {
+ Tuple_ outTuple = tuple.getStore(inputStoreIndexLeftOutTupleList);
+ if (outTuple != null) {
+ propagationQueue.update(outTuple);
+ } else {
+ insertLeft(tuple);
+ }
+ }
+
+ @Override
+ public final void retractLeft(Tuple_ tuple) {
+ Tuple_ outTuple = tuple.getStore(inputStoreIndexLeftOutTupleList);
+ if (outTuple == null) {
+ return;
+ }
+
+ TupleState state = outTuple.state;
+ if (!state.isActive()) {
+ // Impossible because they shouldn't linger in the indexes. | There aren't any indexes. |
timefold-solver | github_2023 | java | 297 | TimefoldAI | triceo | @@ -0,0 +1,103 @@
+package ai.timefold.solver.constraint.streams.bavet.common;
+
+import static ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleState.ABORTING;
+import static ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleState.CREATING;
+import static ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleState.DYING;
+
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.AbstractTuple;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.LeftTupleLifecycle;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.RightTupleLifecycle;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleLifecycle;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleState;
+
+public abstract class AbstractConcatNode<Tuple_ extends AbstractTuple>
+ extends AbstractNode
+ implements LeftTupleLifecycle<Tuple_>, RightTupleLifecycle<Tuple_> {
+ private final int inputStoreIndexLeftOutTupleList;
+ private final int inputStoreIndexRightOutTupleList; | These vars need better naming, as there are no indexes and no out tuple list. |
timefold-solver | github_2023 | java | 297 | TimefoldAI | triceo | @@ -0,0 +1,103 @@
+package ai.timefold.solver.constraint.streams.bavet.common;
+
+import static ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleState.ABORTING;
+import static ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleState.CREATING;
+import static ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleState.DYING;
+
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.AbstractTuple;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.LeftTupleLifecycle;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.RightTupleLifecycle;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleLifecycle;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleState;
+
+public abstract class AbstractConcatNode<Tuple_ extends AbstractTuple>
+ extends AbstractNode
+ implements LeftTupleLifecycle<Tuple_>, RightTupleLifecycle<Tuple_> {
+ private final int inputStoreIndexLeftOutTupleList;
+ private final int inputStoreIndexRightOutTupleList;
+ protected final int outputStoreSize;
+ private final StaticPropagationQueue<Tuple_> propagationQueue;
+
+ protected AbstractConcatNode(TupleLifecycle<Tuple_> nextNodesTupleLifecycle,
+ int inputStoreIndexLeftOutTupleList,
+ int inputStoreIndexRightOutTupleList,
+ int outputStoreSize) {
+ this.propagationQueue = new StaticPropagationQueue<>(nextNodesTupleLifecycle);
+ this.inputStoreIndexLeftOutTupleList = inputStoreIndexLeftOutTupleList;
+ this.inputStoreIndexRightOutTupleList = inputStoreIndexRightOutTupleList;
+ this.outputStoreSize = outputStoreSize;
+ }
+
+ protected abstract Tuple_ getOutTuple(Tuple_ inTuple);
+
+ @Override
+ public final void insertLeft(Tuple_ tuple) {
+ Tuple_ outTuple = getOutTuple(tuple);
+ tuple.setStore(inputStoreIndexLeftOutTupleList, outTuple); | If you store the node-specific tuple state in the store instead of the outtuple, you won't need to create the outtuple just to store the state. |
timefold-solver | github_2023 | java | 297 | TimefoldAI | triceo | @@ -0,0 +1,104 @@
+package ai.timefold.solver.constraint.streams.bavet.uni;
+
+import java.util.Objects;
+import java.util.Set;
+
+import ai.timefold.solver.constraint.streams.bavet.BavetConstraintFactory;
+import ai.timefold.solver.constraint.streams.bavet.common.BavetAbstractConstraintStream;
+import ai.timefold.solver.constraint.streams.bavet.common.BavetConcatConstraintStream;
+import ai.timefold.solver.constraint.streams.bavet.common.NodeBuildHelper;
+import ai.timefold.solver.constraint.streams.bavet.common.bridge.BavetForeBridgeUniConstraintStream;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleLifecycle;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.UniTuple;
+import ai.timefold.solver.core.api.score.Score;
+
+public final class BavetConcatUniConstraintStream<Solution_, A> extends BavetAbstractUniConstraintStream<Solution_, A>
+ implements BavetConcatConstraintStream<Solution_> {
+
+ private final BavetForeBridgeUniConstraintStream<Solution_, A> leftParent;
+ private final BavetForeBridgeUniConstraintStream<Solution_, A> rightParent;
+
+ public BavetConcatUniConstraintStream(BavetConstraintFactory<Solution_> constraintFactory,
+ BavetForeBridgeUniConstraintStream<Solution_, A> leftParent,
+ BavetForeBridgeUniConstraintStream<Solution_, A> rightParent) {
+ super(constraintFactory, leftParent.getRetrievalSemantics());
+ this.leftParent = leftParent;
+ this.rightParent = rightParent;
+ }
+
+ @Override
+ public boolean guaranteesDistinct() {
+ return false;
+ }
+
+ // ************************************************************************
+ // Node creation
+ // ************************************************************************
+
+ @Override
+ public void collectActiveConstraintStreams(Set<BavetAbstractConstraintStream<Solution_>> constraintStreamSet) {
+ leftParent.collectActiveConstraintStreams(constraintStreamSet);
+ rightParent.collectActiveConstraintStreams(constraintStreamSet);
+ constraintStreamSet.add(this);
+ }
+
+ @Override
+ public <Score_ extends Score<Score_>> void buildNode(NodeBuildHelper<Score_> buildHelper) {
+ TupleLifecycle<UniTuple<A>> downstream = buildHelper.getAggregatedTupleLifecycle(childStreamList);
+ int leftCloneStoreIndex = buildHelper.reserveTupleStoreIndex(leftParent.getTupleSource());
+ int rightCloneStoreIndex = buildHelper.reserveTupleStoreIndex(rightParent.getTupleSource());
+ int outputStoreSize = buildHelper.extractTupleStoreSize(this);
+ var node = new BavetUniConcatNode<>(downstream,
+ leftCloneStoreIndex,
+ rightCloneStoreIndex,
+ outputStoreSize);
+ buildHelper.addNode(node, this, leftParent, rightParent);
+ }
+
+ // ************************************************************************
+ // Equality for node sharing
+ // ************************************************************************
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ BavetConcatUniConstraintStream<?, ?> other = (BavetConcatUniConstraintStream<?, ?>) o;
+ /*
+ * Bridge streams do not implement equality because their equals() would have to point back to this stream,
+ * resulting in StackOverflowError.
+ * Therefore we need to check bridge parents to see where this join node comes from. | Not a join node.
(Same comment also likely in Bi, Tri and Quad.) |
timefold-solver | github_2023 | java | 297 | TimefoldAI | triceo | @@ -140,6 +142,13 @@ private long determineLayerIndex(AbstractNode node, NodeBuildHelper<Score_> buil
var leftParentNode = buildHelper.findParentNode(leftParent);
var rightParentNode = buildHelper.findParentNode(rightParent);
return Math.max(leftParentNode.getLayerIndex(), rightParentNode.getLayerIndex()) + 1;
+ } else if (node instanceof AbstractConcatNode<?> concatNode) {
+ var nodeCreator = (BavetConcatConstraintStream<?>) buildHelper.getNodeCreatingStream(concatNode);
+ var leftParent = nodeCreator.getLeftParent();
+ var rightParent = nodeCreator.getRightParent();
+ var leftParentNode = buildHelper.findParentNode(leftParent);
+ var rightParentNode = buildHelper.findParentNode(rightParent);
+ return Math.max(leftParentNode.getLayerIndex(), rightParentNode.getLayerIndex()) + 1; | This code seems to repeat a lot now. Maybe we extract it? |
timefold-solver | github_2023 | others | 297 | TimefoldAI | triceo | @@ -1511,6 +1511,47 @@ the tuple `(SomePerson, USER)` is sent downstream twice.
See <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,`distinct()`>> for how to deal with duplicate tuples.
====
+[[constraintStreamsConcat]]
+==== Concat
+
+Concat allows you to create a constraint stream containing tuples of two constraint streams of the same <<constraintStreamsCardinality,cardinality>>.
+If <<constraintStreamsJoin,join>> acts like a cartesian product of two lists, concat acts like a concatenation of two lists.
+Unlike union of sets, concatenation of lists repeat duplicated elements. | ```suggestion
Unlike union of sets, concatenation of lists repeats duplicated elements.
``` |
timefold-solver | github_2023 | others | 297 | TimefoldAI | triceo | @@ -1511,6 +1511,47 @@ the tuple `(SomePerson, USER)` is sent downstream twice.
See <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,`distinct()`>> for how to deal with duplicate tuples.
====
+[[constraintStreamsConcat]]
+==== Concat
+
+Concat allows you to create a constraint stream containing tuples of two constraint streams of the same <<constraintStreamsCardinality,cardinality>>.
+If <<constraintStreamsJoin,join>> acts like a cartesian product of two lists, concat acts like a concatenation of two lists.
+Unlike union of sets, concatenation of lists repeat duplicated elements.
+If the two constraint stream parents share tuples, they will be repeated downstream.
+If this is undesired, use <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,distinct>>. | ```suggestion
If this is undesired, use the <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,`distinct` building block>>.
``` |
timefold-solver | github_2023 | others | 297 | TimefoldAI | triceo | @@ -1511,6 +1511,47 @@ the tuple `(SomePerson, USER)` is sent downstream twice.
See <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,`distinct()`>> for how to deal with duplicate tuples.
====
+[[constraintStreamsConcat]]
+==== Concat
+
+Concat allows you to create a constraint stream containing tuples of two constraint streams of the same <<constraintStreamsCardinality,cardinality>>.
+If <<constraintStreamsJoin,join>> acts like a cartesian product of two lists, concat acts like a concatenation of two lists.
+Unlike union of sets, concatenation of lists repeat duplicated elements.
+If the two constraint stream parents share tuples, they will be repeated downstream.
+If this is undesired, use <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,distinct>>.
+
+image::constraints-and-score/constraintStreamConcat.png[align="center"]
+
+For example, to count the total number of cats and dogs:
+
+[source,java,options="nowrap"]
+----
+ private Constraint countCatsAndDogs(ConstraintFactory constraintFactory) {
+ return constraintFactory.forEach(Employee.class)
+ .filter(employee -> employee.hasDog())
+ .concat(constraintFactory.forEach(Employee.class)
+ .filter(employee -> employee.hasCat())) | I am not sure this is a good example. The first question once a smart person sees this is: why not just use a much simple `.filter(hasCat || hasDog)`?
Even though you explain that the single filter approach would actually do something different, I have to ask - why? Why would I want the employee there twice? (It was my original concern regarding duplicates; it often makes no sense to have them.) |
timefold-solver | github_2023 | others | 297 | TimefoldAI | triceo | @@ -1511,6 +1511,47 @@ the tuple `(SomePerson, USER)` is sent downstream twice.
See <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,`distinct()`>> for how to deal with duplicate tuples.
====
+[[constraintStreamsConcat]]
+==== Concat
+
+Concat allows you to create a constraint stream containing tuples of two constraint streams of the same <<constraintStreamsCardinality,cardinality>>.
+If <<constraintStreamsJoin,join>> acts like a cartesian product of two lists, concat acts like a concatenation of two lists.
+Unlike union of sets, concatenation of lists repeat duplicated elements.
+If the two constraint stream parents share tuples, they will be repeated downstream.
+If this is undesired, use <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,distinct>>.
+
+image::constraints-and-score/constraintStreamConcat.png[align="center"]
+
+For example, to count the total number of cats and dogs:
+
+[source,java,options="nowrap"]
+----
+ private Constraint countCatsAndDogs(ConstraintFactory constraintFactory) {
+ return constraintFactory.forEach(Employee.class)
+ .filter(employee -> employee.hasDog())
+ .concat(constraintFactory.forEach(Employee.class)
+ .filter(employee -> employee.hasCat()))
+ .groupBy(ConstraintCollectors.count())
+ .penalize(HardSoftScore.ONE_SOFT, count -> count)
+ .asConstraint("Count cats and dogs");
+ }
+----
+
+This correctly count cats and dogs when an Employee has both a cat and a dog. | ```suggestion
This correctly counts cats and dogs when an Employee has both a cat and a dog.
``` |
timefold-solver | github_2023 | others | 297 | TimefoldAI | triceo | @@ -1511,6 +1511,57 @@ the tuple `(SomePerson, USER)` is sent downstream twice.
See <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,`distinct()`>> for how to deal with duplicate tuples.
====
+[[constraintStreamsConcat]]
+==== Concat
+
+Concat allows you to create a constraint stream containing tuples of two constraint streams of the same <<constraintStreamsCardinality,cardinality>>. | ```suggestion
The `concat` building block allows you to create a constraint stream containing tuples of two constraint streams of the same <<constraintStreamsCardinality,cardinality>>.
``` |
timefold-solver | github_2023 | others | 297 | TimefoldAI | triceo | @@ -1511,6 +1511,57 @@ the tuple `(SomePerson, USER)` is sent downstream twice.
See <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,`distinct()`>> for how to deal with duplicate tuples.
====
+[[constraintStreamsConcat]]
+==== Concat
+
+Concat allows you to create a constraint stream containing tuples of two constraint streams of the same <<constraintStreamsCardinality,cardinality>>.
+If <<constraintStreamsJoin,join>> acts like a cartesian product of two lists, concat acts like a concatenation of two lists. | ```suggestion
If <<constraintStreamsJoin,join>> acts like a cartesian product of two lists, `concat` acts like a concatenation of two lists.
``` |
timefold-solver | github_2023 | others | 297 | TimefoldAI | triceo | @@ -1511,6 +1511,57 @@ the tuple `(SomePerson, USER)` is sent downstream twice.
See <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,`distinct()`>> for how to deal with duplicate tuples.
====
+[[constraintStreamsConcat]]
+==== Concat
+
+Concat allows you to create a constraint stream containing tuples of two constraint streams of the same <<constraintStreamsCardinality,cardinality>>.
+If <<constraintStreamsJoin,join>> acts like a cartesian product of two lists, concat acts like a concatenation of two lists.
+Unlike union of sets, concatenation of lists repeats duplicated elements.
+If the two constraint stream parents share tuples, they will be repeated downstream. | ```suggestion
If the two constraint stream parents share tuples, which happens eg. when the streams being concatenated come from the same source of data, the tuples will be repeated downstream.
``` |
timefold-solver | github_2023 | others | 297 | TimefoldAI | triceo | @@ -1511,6 +1511,57 @@ the tuple `(SomePerson, USER)` is sent downstream twice.
See <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,`distinct()`>> for how to deal with duplicate tuples.
====
+[[constraintStreamsConcat]]
+==== Concat
+
+Concat allows you to create a constraint stream containing tuples of two constraint streams of the same <<constraintStreamsCardinality,cardinality>>.
+If <<constraintStreamsJoin,join>> acts like a cartesian product of two lists, concat acts like a concatenation of two lists.
+Unlike union of sets, concatenation of lists repeats duplicated elements.
+If the two constraint stream parents share tuples, they will be repeated downstream.
+If this is undesired, use the <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,`distinct` building block>>.
+
+image::constraints-and-score/constraintStreamConcat.png[align="center"]
+
+For example, to ensure each employee has a minimum number of assigned shifts:
+
+[source,java,options="nowrap"]
+----
+ private Constraint ensureEachEmployeeHasAtLeastTwoShifts(ConstraintFactory constraintFactory) {
+ return constraintFactory.forEach(Employee.class)
+ .join(Shift.class, equal(Function.identity(), Shift::getEmployee))
+ .concat(
+ constraintFactory.forEach(Employee.class)
+ .ifNotExists(Shift.class, equal(Function.identity(), Shift::getEmployee))
+ .expand(employee -> (Shift) null)
+ )
+ .groupBy((employee, shift) -> employee,
+ conditionally((employee, shift) -> shift != null,
+ countBi())
+ )
+ .filter((employee, shiftCount) -> shiftCount < employee.minimumAssignedShifts)
+ .penalize(HardSoftScore.ONE_SOFT, (employee, shiftCount) -> employee.minimumAssignedShifts - shiftCount)
+ .asConstraint("Minimum number of assigned shifts");
+ }
+----
+
+This correctly count the number of shifts each Employee has, *even when the Employee has no shifts*. | ```suggestion
This correctly counts the number of shifts each Employee has, *even when the Employee has no shifts*.
``` |
timefold-solver | github_2023 | others | 297 | TimefoldAI | triceo | @@ -1511,6 +1511,57 @@ the tuple `(SomePerson, USER)` is sent downstream twice.
See <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,`distinct()`>> for how to deal with duplicate tuples.
====
+[[constraintStreamsConcat]]
+==== Concat
+
+Concat allows you to create a constraint stream containing tuples of two constraint streams of the same <<constraintStreamsCardinality,cardinality>>.
+If <<constraintStreamsJoin,join>> acts like a cartesian product of two lists, concat acts like a concatenation of two lists.
+Unlike union of sets, concatenation of lists repeats duplicated elements.
+If the two constraint stream parents share tuples, they will be repeated downstream.
+If this is undesired, use the <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,`distinct` building block>>.
+
+image::constraints-and-score/constraintStreamConcat.png[align="center"]
+
+For example, to ensure each employee has a minimum number of assigned shifts:
+
+[source,java,options="nowrap"]
+----
+ private Constraint ensureEachEmployeeHasAtLeastTwoShifts(ConstraintFactory constraintFactory) {
+ return constraintFactory.forEach(Employee.class)
+ .join(Shift.class, equal(Function.identity(), Shift::getEmployee))
+ .concat(
+ constraintFactory.forEach(Employee.class)
+ .ifNotExists(Shift.class, equal(Function.identity(), Shift::getEmployee))
+ .expand(employee -> (Shift) null)
+ )
+ .groupBy((employee, shift) -> employee,
+ conditionally((employee, shift) -> shift != null,
+ countBi())
+ )
+ .filter((employee, shiftCount) -> shiftCount < employee.minimumAssignedShifts)
+ .penalize(HardSoftScore.ONE_SOFT, (employee, shiftCount) -> employee.minimumAssignedShifts - shiftCount)
+ .asConstraint("Minimum number of assigned shifts");
+ }
+----
+
+This correctly count the number of shifts each Employee has, *even when the Employee has no shifts*.
+If it was implemented without concat like this: | ```suggestion
If it was implemented without `concat` like this:
``` |
timefold-solver | github_2023 | others | 297 | TimefoldAI | triceo | @@ -1511,6 +1511,57 @@ the tuple `(SomePerson, USER)` is sent downstream twice.
See <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,`distinct()`>> for how to deal with duplicate tuples.
====
+[[constraintStreamsConcat]]
+==== Concat
+
+Concat allows you to create a constraint stream containing tuples of two constraint streams of the same <<constraintStreamsCardinality,cardinality>>.
+If <<constraintStreamsJoin,join>> acts like a cartesian product of two lists, concat acts like a concatenation of two lists.
+Unlike union of sets, concatenation of lists repeats duplicated elements.
+If the two constraint stream parents share tuples, they will be repeated downstream.
+If this is undesired, use the <<constraintStreamsDealingWithDuplicateTuplesUsingDistinct,`distinct` building block>>.
+
+image::constraints-and-score/constraintStreamConcat.png[align="center"]
+
+For example, to ensure each employee has a minimum number of assigned shifts:
+
+[source,java,options="nowrap"]
+----
+ private Constraint ensureEachEmployeeHasAtLeastTwoShifts(ConstraintFactory constraintFactory) {
+ return constraintFactory.forEach(Employee.class)
+ .join(Shift.class, equal(Function.identity(), Shift::getEmployee))
+ .concat(
+ constraintFactory.forEach(Employee.class)
+ .ifNotExists(Shift.class, equal(Function.identity(), Shift::getEmployee))
+ .expand(employee -> (Shift) null)
+ )
+ .groupBy((employee, shift) -> employee,
+ conditionally((employee, shift) -> shift != null,
+ countBi())
+ )
+ .filter((employee, shiftCount) -> shiftCount < employee.minimumAssignedShifts)
+ .penalize(HardSoftScore.ONE_SOFT, (employee, shiftCount) -> employee.minimumAssignedShifts - shiftCount)
+ .asConstraint("Minimum number of assigned shifts");
+ }
+----
+
+This correctly count the number of shifts each Employee has, *even when the Employee has no shifts*.
+If it was implemented without concat like this:
+
+[source,java,options="nowrap"]
+----
+ private Constraint incorrectEnsureEachEmployeeHasAtLeastTwoShifts(ConstraintFactory constraintFactory) {
+ return constraintFactory.forEach(Employee.class)
+ .join(Shift.class, equal(Function.identity(), Shift::getEmployee))
+ .groupBy((employee, shift) -> employee,
+ countBi())
+ )
+ .filter((employee, shiftCount) -> shiftCount < employee.minimumAssignedShifts)
+ .penalize(HardSoftScore.ONE_SOFT, (employee, shiftCount) -> employee.minimumAssignedShifts - shiftCount)
+ .asConstraint("Minimum number of assigned shifts (incorrect)");
+ }
+----
+
+An employee with no assigned shifts _will not be penalized because no tuples were passed to the group by_. | ```suggestion
An employee with no assigned shifts _will not be penalized because no tuples were passed to the `groupBy` building block_.
``` |
timefold-solver | github_2023 | java | 297 | TimefoldAI | triceo | @@ -16,4 +16,10 @@ public final class BavetBiConcatNode<A, B> extends AbstractConcatNode<BiTuple<A,
protected BiTuple<A, B> getOutTuple(BiTuple<A, B> inTuple) {
return new BiTuple<>(inTuple.factA, inTuple.factB, outputStoreSize);
}
+
+ @Override
+ protected void updateOutTuple(BiTuple<A, B> inTuple, BiTuple<A, B> outTuple) {
+ outTuple.factA = inTuple.factA; | Tuples have `updateInDifferent(...)` just for this case.
Turns out it is a common operation, so it was extracted already. |
timefold-solver | github_2023 | java | 308 | TimefoldAI | rsynek | @@ -487,10 +487,28 @@ private static <C> Member getSingleMember(Class<C> clazz, Class<? extends Annota
if (memberList.isEmpty()) {
return null;
}
- if (memberList.size() > 1) {
- throw new IllegalArgumentException("The class (" + clazz
- + ") has " + memberList.size() + " members (" + memberList + ") with a "
- + annotationClass.getSimpleName() + " annotation.");
+ int size = memberList.size();
+ if (clazz.isRecord()) {
+ /*
+ * A record has a field and a getter for each record component.
+ * When the component is annotated with @PlanningId,
+ * the annotation ends up both on the field and on the getter.
+ */
+ if (size == 2) { // The getter is used to retrieve the value of the record component.
+ return memberList.get(1); | Is it guaranteed that the second member in the list is the getter and not the field? |
timefold-solver | github_2023 | others | 284 | TimefoldAI | triceo | @@ -18,7 +18,7 @@
<!-- Code of integration tests should not be a part of test coverage reports. -->
<sonar.coverage.exclusions>**/*</sonar.coverage.exclusions>
<!-- Quarkus 2 and 3 use different context roots. -->
- <dev.ui.root>/q/dev-v1</dev.ui.root>
+ <dev.ui.root>/q/dev-ui</dev.ui.root> | Since `main` only uses Quarkus 3, I think we can go back to hardcoding this and removing the comment. |
timefold-solver | github_2023 | others | 284 | TimefoldAI | triceo | @@ -651,7 +651,8 @@
<profile>
<id>sonarcloud-analysis</id>
<properties>
- <sonar.coverage.jacoco.xmlReportPaths>${project.reporting.outputDirectory}/jacoco/jacoco.xml</sonar.coverage.jacoco.xmlReportPaths>
+ <sonar.coverage.jacoco.xmlReportPaths>${project.reporting.outputDirectory}/jacoco/jacoco.xml
+ </sonar.coverage.jacoco.xmlReportPaths> | Unrelated change? |
timefold-solver | github_2023 | java | 284 | TimefoldAI | triceo | @@ -148,20 +152,48 @@ DetermineIfNativeBuildItem ifNativeBuild() {
}
@BuildStep(onlyIf = IsDevelopment.class)
- public DevConsoleRuntimeTemplateInfoBuildItem getSolverConfig(SolverConfigBuildItem solverConfigBuildItem,
- CurateOutcomeBuildItem curateOutcomeBuildItem) {
+ @Record(STATIC_INIT)
+ public CardPageBuildItem registerDevUICard(
+ TimefoldDevUIRecorder devUIRecorder,
+ SolverConfigBuildItem solverConfigBuildItem,
+ BuildProducer<SyntheticBeanBuildItem> syntheticBeans) {
+ CardPageBuildItem cardPageBuildItem = new CardPageBuildItem();
SolverConfig solverConfig = solverConfigBuildItem.getSolverConfig();
if (solverConfig != null) {
StringWriter effectiveSolverConfigWriter = new StringWriter();
SolverConfigIO solverConfigIO = new SolverConfigIO();
solverConfigIO.write(solverConfig, effectiveSolverConfigWriter);
- return new DevConsoleRuntimeTemplateInfoBuildItem("solverConfigProperties",
- new TimefoldDevUIPropertiesSupplier(effectiveSolverConfigWriter.toString()), this.getClass(),
- curateOutcomeBuildItem);
+ syntheticBeans.produce(SyntheticBeanBuildItem.configure(SolverConfigText.class)
+ .scope(ApplicationScoped.class)
+ .supplier(devUIRecorder.solverConfigTextSupplier(effectiveSolverConfigWriter.toString()))
+ .done());
} else {
- return new DevConsoleRuntimeTemplateInfoBuildItem("solverConfigProperties",
- new TimefoldDevUIPropertiesSupplier(), this.getClass(), curateOutcomeBuildItem);
+ syntheticBeans.produce(SyntheticBeanBuildItem.configure(SolverConfigText.class)
+ .scope(ApplicationScoped.class)
+ .supplier(devUIRecorder.solverConfigTextSupplier(""))
+ .done());
}
+ cardPageBuildItem.addPage(Page.webComponentPageBuilder()
+ .title("Configuration")
+ .icon("font-awesome-solid:wrench")
+ .componentLink("config-component.js"));
+
+ cardPageBuildItem.addPage(Page.webComponentPageBuilder()
+ .title("Model")
+ .icon("font-awesome-solid:wrench")
+ .componentLink("model-component.js"));
+
+ cardPageBuildItem.addPage(Page.webComponentPageBuilder()
+ .title("Constraints")
+ .icon("font-awesome-solid:wrench")
+ .componentLink("constraints-component.js"));
+
+ return cardPageBuildItem;
+ }
+
+ @BuildStep(onlyIf = IsDevelopment.class)
+ public JsonRPCProvidersBuildItem registerRPCService() {
+ return new JsonRPCProvidersBuildItem("Timefold", TimefoldDevUIPropertiesRPCService.class); | Shall we make it "Timefold Solver"? That way, it'd be consistent with what the project is actually called. |
timefold-solver | github_2023 | javascript | 284 | TimefoldAI | triceo | @@ -0,0 +1,61 @@
+import {css, html, LitElement} from 'lit';
+import {JsonRpc} from 'jsonrpc';
+import '@vaadin/icon';
+import '@vaadin/button';
+import {until} from 'lit/directives/until.js';
+import '@vaadin/grid';
+import '@vaadin/grid/vaadin-grid-sort-column.js';
+
+export class ConfigComponent extends LitElement {
+
+ jsonRpc = new JsonRpc("Timefold"); | Timefold Solver? |
timefold-solver | github_2023 | javascript | 284 | TimefoldAI | triceo | @@ -0,0 +1,76 @@
+import {css, html, LitElement} from 'lit';
+import {JsonRpc} from 'jsonrpc';
+import '@vaadin/icon';
+import '@vaadin/button';
+import {until} from 'lit/directives/until.js';
+import '@vaadin/grid';
+import {columnBodyRenderer} from '@vaadin/grid/lit.js';
+import '@vaadin/grid/vaadin-grid-sort-column.js';
+
+export class ConstraintsComponent extends LitElement {
+
+ jsonRpc = new JsonRpc("Timefold"); | Dtto. |
timefold-solver | github_2023 | javascript | 284 | TimefoldAI | triceo | @@ -0,0 +1,104 @@
+import {css, html, LitElement} from 'lit';
+import {JsonRpc} from 'jsonrpc';
+import '@vaadin/icon';
+import '@vaadin/button';
+import {until} from 'lit/directives/until.js';
+import '@vaadin/grid';
+import {columnBodyRenderer} from '@vaadin/grid/lit.js';
+import '@vaadin/grid/vaadin-grid-sort-column.js';
+
+export class ModelComponent extends LitElement {
+
+ jsonRpc = new JsonRpc("Timefold"); | Dtto. |
timefold-solver | github_2023 | java | 284 | TimefoldAI | triceo | @@ -57,51 +46,28 @@ void testSolverConfigPage() throws ParserConfigurationException, SAXException, I
}
@Test
- void testModelPage() throws ParserConfigurationException, SAXException, IOException {
- String body = RestAssured.get(getPage("model"))
- .then()
- .extract()
- .body()
- .asPrettyString();
- XmlParser xmlParser = new XmlParser();
- Node node = xmlParser.parseText(body);
- String model = Objects.requireNonNull(findById("timefold-solver-model", node)).toString();
- assertThat(model)
- .contains("value=[Solution: ai.timefold.solver.quarkus.it.devui.domain.TestdataStringLengthShadowSolution]");
- assertThat(model)
- .contains("value=[Entity: ai.timefold.solver.quarkus.it.devui.domain.TestdataStringLengthShadowEntity]");
- assertThat(model).contains(
- "value=[Genuine Variables]]]]]], tbody[attributes={}; value=[tr[attributes={}; value=[td[attributes={colspan=1, rowspan=1}; value=[value]]");
- assertThat(model).contains(
- "value=[Shadow Variables]]]]]], tbody[attributes={}; value=[tr[attributes={}; value=[td[attributes={colspan=1, rowspan=1}; value=[length]]");
+ void testModelPage() throws Exception {
+ JsonNode modelResponse = super.executeJsonRPCMethod("getModelInfo");
+ assertThat(modelResponse.get("solutionClass").asText())
+ .contains("ai.timefold.solver.quarkus.it.devui.domain.TestdataStringLengthShadowSolution"); | I'd use the `class.getCanonicalName()` throughout this test, to make this safe for refactoring. |
timefold-solver | github_2023 | others | 258 | TimefoldAI | rsynek | @@ -86,25 +91,13 @@ jobs:
out/jreleaser/trace.log
out/jreleaser/output.properties
+ # Pull Request will be created with the changes and a summary of next steps.
- name: Set micro snapshot version on the release branch | ```suggestion
- name: Put back the 999-SNAPSHOT version on the release branch
``` |
timefold-solver | github_2023 | others | 258 | TimefoldAI | rsynek | @@ -86,25 +91,13 @@ jobs:
out/jreleaser/trace.log
out/jreleaser/output.properties
+ # Pull Request will be created with the changes and a summary of next steps.
- name: Set micro snapshot version on the release branch
run: |
git checkout -B ${{ github.event.inputs.releaseBranch }}-bump-to-next-micro-version | ```suggestion
git checkout -B ${{ github.event.inputs.releaseBranch }}-put-back-999-snapshot
``` |
timefold-solver | github_2023 | others | 258 | TimefoldAI | rsynek | @@ -86,25 +91,13 @@ jobs:
out/jreleaser/trace.log
out/jreleaser/output.properties
+ # Pull Request will be created with the changes and a summary of next steps.
- name: Set micro snapshot version on the release branch
run: |
git checkout -B ${{ github.event.inputs.releaseBranch }}-bump-to-next-micro-version
- mvn -Dfull versions:set -DnewVersion=${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT
- git commit -am "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT"
+ mvn -Dfull versions:set -DnewVersion=999-SNAPSHOT
+ git commit -am "build: move back to 999-SNAPSHOT"
git push origin ${{ github.event.inputs.releaseBranch }}-bump-to-next-micro-version | ```suggestion
git push origin ${{ github.event.inputs.releaseBranch }}-put-back-999-snapshot
``` |
timefold-solver | github_2023 | others | 258 | TimefoldAI | rsynek | @@ -86,25 +91,13 @@ jobs:
out/jreleaser/trace.log
out/jreleaser/output.properties
+ # Pull Request will be created with the changes and a summary of next steps.
- name: Set micro snapshot version on the release branch
run: |
git checkout -B ${{ github.event.inputs.releaseBranch }}-bump-to-next-micro-version
- mvn -Dfull versions:set -DnewVersion=${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT
- git commit -am "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT"
+ mvn -Dfull versions:set -DnewVersion=999-SNAPSHOT
+ git commit -am "build: move back to 999-SNAPSHOT"
git push origin ${{ github.event.inputs.releaseBranch }}-bump-to-next-micro-version
- gh pr create --reviewer triceo,ge0ffrey --base ${{ github.event.inputs.releaseBranch }} --head ${{ github.event.inputs.releaseBranch }}-bump-to-next-micro-version --title "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT" --body-file .github/workflows/release-pr-body-stable.md
- env:
- GITHUB_TOKEN: ${{ secrets.JRELEASER_GITHUB_TOKEN }}
-
- - name: Switch back to source branch and set snapshot version
- run: |
- git checkout ${{ github.event.inputs.sourceBranch }}
- git checkout -B ${{ github.event.inputs.releaseBranch }}-bump-to-next-minor-version
- mvn -Dfull versions:set -DnewVersion=${{ github.event.inputs.nextVersion }}-SNAPSHOT
- cp docs/target/antora-template.yml docs/src/antora.yml
- git add docs/src/antora.yml
- git commit -am "chore: move to ${{ github.event.inputs.nextVersion }}-SNAPSHOT"
- git push origin ${{ github.event.inputs.releaseBranch }}-bump-to-next-minor-version
- gh pr create --reviewer triceo,ge0ffrey --base ${{ github.event.inputs.sourceBranch }} --head ${{ github.event.inputs.releaseBranch }}-bump-to-next-minor-version --title "chore: move to ${{ github.event.inputs.nextVersion }}-SNAPSHOT" --body-file .github/workflows/release-pr-body.md
+ gh pr create --reviewer triceo --base ${{ github.event.inputs.releaseBranch }} --head ${{ github.event.inputs.releaseBranch }}-bump-to-next-micro-version --title "build: move back to 999-SNAPSHOT" --body-file .github/workflows/release-pr-body.md | ```suggestion
gh pr create --reviewer triceo --base ${{ github.event.inputs.releaseBranch }} --head ${{ github.event.inputs.releaseBranch }}-put-back-999-snapshot --title "build: move back to 999-SNAPSHOT" --body-file .github/workflows/release-pr-body.md
``` |
timefold-solver | github_2023 | java | 257 | TimefoldAI | rsynek | @@ -15,15 +16,27 @@ public final class ReflectionBeanPropertyMemberAccessor extends AbstractMemberAc
private final Class<?> propertyType;
private final String propertyName;
private final Method getterMethod;
+ private final MethodHandle getherMethodHandle;
private final Method setterMethod;
+ private final MethodHandle setterMethodHandle;
public ReflectionBeanPropertyMemberAccessor(Method getterMethod) {
this(getterMethod, false);
}
public ReflectionBeanPropertyMemberAccessor(Method getterMethod, boolean getterOnly) {
this.getterMethod = getterMethod;
- getterMethod.setAccessible(true); // Performance hack by avoiding security checks
+ MethodHandles.Lookup lookup = MethodHandles.lookup();
+ try {
+ getterMethod.setAccessible(true); // Performance hack by avoiding security checks
+ this.getherMethodHandle = lookup.unreflect(getterMethod) | There is also `unreflectGetter` and `unreflectSetter`, but these operate on `Field` instances, while here we already have the method. |
timefold-solver | github_2023 | java | 254 | TimefoldAI | triceo | @@ -42,6 +43,7 @@ public MultipleDelegateList(List<T>... delegates) {
}
this.totalSize = sizeSoFar;
+ this.cachedRebaseResult = null; | Maybe add a comment here as to why it's safe to store this here? |
timefold-solver | github_2023 | java | 243 | TimefoldAI | rsynek | @@ -525,15 +529,56 @@ private GeneratedGizmoClasses generateDomainAccessors(SolverConfig solverConfig,
Set<String> generatedMemberAccessorsClassNameSet = new HashSet<>();
Set<String> gizmoSolutionClonerClassNameSet = new HashSet<>();
+ /*
+ * TODO consistently change the name "entity" to something less confusing
+ * "entity" in this context means both "planning solution",
+ * "planning entity" and other things as well.
+ */
GizmoMemberAccessorEntityEnhancer entityEnhancer = new GizmoMemberAccessorEntityEnhancer();
if (solverConfig.getDomainAccessType() == DomainAccessType.GIZMO) {
Collection<AnnotationInstance> membersToGeneratedAccessorsFor = new ArrayList<>();
+ // Every entity and solution gets scanned for annotations.
+ // Annotated members get their accessors generated.
for (DotName dotName : DotNames.GIZMO_MEMBER_ACCESSOR_ANNOTATIONS) {
membersToGeneratedAccessorsFor.addAll(indexView.getAnnotations(dotName));
}
membersToGeneratedAccessorsFor.removeIf(this::shouldIgnoreMember);
+ // Fail fast on auto-discovery.
+ var planningSolutionAnnotationInstanceCollection =
+ indexView.getAnnotations(DotNames.PLANNING_SOLUTION);
+ if (planningSolutionAnnotationInstanceCollection.isEmpty()) {
+ throw new IllegalStateException(
+ "No classes found with a @" + PlanningSolution.class.getSimpleName() + " annotation.");
+ } else if (planningSolutionAnnotationInstanceCollection.size() > 1) {
+ throw new IllegalStateException("Multiple classes (" + convertAnnotationInstancesToString(
+ planningSolutionAnnotationInstanceCollection) + ") found with a @" +
+ PlanningSolution.class.getSimpleName() + " annotation.");
+ }
+ var planningSolutionAnnotationInstance =
+ planningSolutionAnnotationInstanceCollection.stream().findFirst().orElseThrow();
+ var autoDiscoverMemberType = planningSolutionAnnotationInstance.values().stream()
+ .filter(v -> v.name().equals("autoDiscoverMemberType"))
+ .findFirst()
+ .map(AnnotationValue::asEnum)
+ .map(AutoDiscoverMemberType::valueOf)
+ .orElse(AutoDiscoverMemberType.NONE);
+
+ if (autoDiscoverMemberType != AutoDiscoverMemberType.NONE) {
+ throw new UnsupportedOperationException(""" | Nice; sometimes I forget we are already past Java 15. |
timefold-solver | github_2023 | java | 243 | TimefoldAI | rsynek | @@ -525,15 +529,56 @@ private GeneratedGizmoClasses generateDomainAccessors(SolverConfig solverConfig,
Set<String> generatedMemberAccessorsClassNameSet = new HashSet<>();
Set<String> gizmoSolutionClonerClassNameSet = new HashSet<>();
+ /*
+ * TODO consistently change the name "entity" to something less confusing | What exactly does it enhance? Only things that may change during solving (solution, genuine and shadow entities) or even facts?
Trying to figure out what the name should be. |
timefold-solver | github_2023 | others | 240 | TimefoldAI | rsynek | @@ -329,17 +334,6 @@
<newArtifacts>
<artifact>${project.groupId}:${project.artifactId}:${project.version}</artifact>
</newArtifacts>
- <!-- By default revapi will check the oldArtifact against the currently executed build -->
- <analysisConfigurationFiles>
- <configurationFile>
- <path>src/build/revapi-config.json</path>
- <roots>
- <root>filters</root>
- <root>ignores</root>
- </roots>
- </configurationFile>
- </analysisConfigurationFiles>
- <failSeverity>potentiallyBreaking</failSeverity> | Is this configuration no longer relevant? |
timefold-solver | github_2023 | java | 240 | TimefoldAI | rsynek | @@ -178,7 +178,6 @@ private boolean isScoreCalculationDefined(SolverConfig solverConfig) {
}
return scoreDirectorFactoryConfig.getEasyScoreCalculatorClass() != null ||
scoreDirectorFactoryConfig.getIncrementalScoreCalculatorClass() != null ||
- scoreDirectorFactoryConfig.getScoreDrlList() != null || | Good catch |
timefold-solver | github_2023 | others | 240 | TimefoldAI | rsynek | @@ -72,6 +72,12 @@
<plugin>
<groupId>org.revapi</groupId>
<artifactId>revapi-maven-plugin</artifactId>
+ <configuration>
+ <analysisConfigurationFiles>
+ <file>${project.basedir}/src/build/revapi-filter.json</file>
+ <file>${project.basedir}/src/build/revapi-differences.json</file>
+ </analysisConfigurationFiles>
+ </configuration> | Why not define this config in the build parent pom.xml? |
timefold-solver | github_2023 | javascript | 216 | TimefoldAI | rsynek | @@ -26,30 +26,69 @@ function replaceTimefoldAutoHeaderFooter() {
<div class="me-auto"><a class="text-white" href="https://timefold.ai/product/support/">Support</a></div>
</div>
</div>
+ <div id="applicationInfo" class="container text-center"></div>
</footer>`));
+
+ applicationInfo();
}
}
+function showSimpleError(title) {
+ const notification = $(`<div class="toast" role="alert" aria-live="assertive" aria-atomic="true" style="min-width: 50rem"/>`)
+ .append($(`<div class="toast-header bg-danger">
+ <strong class="me-auto text-dark">Error</strong>
+ <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
+ </div>`))
+ .append($(`<div class="toast-body"/>`)
+ .append($(`<p/>`).text(title))
+ );
+ $("#notificationPanel").append(notification);
+ notification.toast({delay: 30000});
+ notification.toast('show');
+}
+
function showError(title, xhr) {
- const serverErrorMessage = !xhr.responseJSON ? `${xhr.status}: ${xhr.statusText}` : xhr.responseJSON.message;
- console.error(title + "\n" + serverErrorMessage);
- const notification = $(`<div class="toast" role="alert" aria-live="assertive" aria-atomic="true" style="min-width: 30rem"/>`)
+ var serverErrorMessage = !xhr.responseJSON ? `${xhr.status}: ${xhr.statusText}` : xhr.responseJSON.message;
+ var serverErrorCode = !xhr.responseJSON ? `unknown` : xhr.responseJSON.code;
+ var serverErrorId = !xhr.responseJSON ? `----` : xhr.responseJSON.id;
+ var serverErrorDetails = !xhr.responseJSON ? `no details provided` : xhr.responseJSON.details;
+
+ if (xhr.responseJSON && !serverErrorMessage) {
+ serverErrorMessage = JSON.stringify(xhr.responseJSON);
+ serverErrorCode = xhr.statusText + '(' + xhr.status + ')';
+ serverErrorId = `----`;
+ }
+
+ console.error(title + "\n" + serverErrorMessage + " : " + serverErrorDetails);
+ const notification = $(`<div class="toast" role="alert" aria-live="assertive" aria-atomic="true" style="min-width: 50rem"/>`)
.append($(`<div class="toast-header bg-danger">
<strong class="me-auto text-dark">Error</strong>
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
</div>`))
.append($(`<div class="toast-body"/>`)
.append($(`<p/>`).text(title))
.append($(`<pre/>`)
- .append($(`<code/>`).text(serverErrorMessage))
+ .append($(`<code/>`).text(serverErrorMessage + "\n\nCode: " + serverErrorCode + "\nError id: " + serverErrorId))
)
);
$("#notificationPanel").append(notification);
notification.toast({delay: 30000});
notification.toast('show');
}
+// ****************************************************************************
+// Application info
+// ****************************************************************************
+
+function applicationInfo() {
+ $.getJSON("tf/info", function (info) { | Maybe remove the prefix, see https://github.com/TimefoldAI/timefold-platform/pull/61#discussion_r1294405188 |
timefold-solver | github_2023 | others | 206 | TimefoldAI | rsynek | @@ -81,4 +81,42 @@
</plugin>
</plugins>
</build>
+
+ <profiles>
+ <profile>
+ <!--
+ Benchmarker is not supported in native.
+ However, Quarkus 3.2.4+ seems to have an issue where the native profile,
+ if present on another unrelated module, is magically and wrongly inherited in this module.
+ This means the native compilation can not be avoided and needs to be made to pass.
+ Tests at runtime are then disabled.
+ -->
+ <id>native</id>
+ <activation>
+ <property>
+ <name>native</name>
+ </property>
+ </activation>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-1.2-api</artifactId>
+ </dependency>
+ </dependencies>
+ <dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-1.2-api</artifactId>
+ <version>${version.org.apache.logging.log4j}</version>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+ <properties>
+ <quarkus.package.type>native</quarkus.package.type>
+ <quarkus.native.additional-build-args>--initialize-at-run-time=freemarker.ext.jython.JythonWrapper</quarkus.native.additional-build-args> | Good as a temporary workaround, but please at least file an issue to investigate this further. Ideally, this should be reported to Quarkus.
If this module is not supposed to work in native, we should not lose time by native compilation in every CI run. |
timefold-solver | github_2023 | others | 193 | TimefoldAI | rsynek | @@ -23,7 +23,7 @@
<!--</appender>-->
<!-- To override the debug log level from the command line, use the VM option "-Dlogback.level.ai.timefold.solver=trace" -->
- <logger name="ai.timefold.solver" level="${logback.level.ai.timefold.solver:-debug}"/>
+ <logger name="ai.timefold.solver" level="${logback.level.ai.timefold.solver:-info}"/> | Intentional? |
timefold-solver | github_2023 | java | 193 | TimefoldAI | rsynek | @@ -96,7 +96,22 @@ public T next() {
@Override
public String toString() {
- return "size = " + size;
+ switch (size) {
+ case 0 -> {
+ return "[]";
+ }
+ case 1 -> {
+ return "[" + first.getElement() + "]";
+ }
+ default -> {
+ StringBuilder builder = new StringBuilder("[");
+ for (T entry : this) { | What is the typical and maximal length of this list? |
timefold-solver | github_2023 | others | 193 | TimefoldAI | rsynek | @@ -458,6 +458,55 @@ stream), use <<constraintStreamsConditionalPropagation,ifExists>> instead.
It does not create cartesian products and therefore generally performs better.
====
+==== Evaluation of multiple joiners
+
+When using multiple joiners, there are some important considerations to keep in mind:
+
+[source,java,options="nowrap"]
+----
+ factory.forEach(VehicleShift.class)
+ .join(Visit.class,
+ Joiners.equal(Function.identity(), Visit::getVehicleShift), // Visit's VehicleShift is not null...
+ Joiners.lessThan(
+ vehicleShift -> vehicleShift.getMaxTravelTime(),
+ visit -> visit.getVehicleShift().getMaxTravelTime() // ... yet NPE may be thrown here.
+ ))
+----
+
+When indexing joiners (such as `equal` and `lessThan`) check their indexes,
+they take the input tuple and create a set of keys that will enter the index.
+These keys are different for the left and right side of the joiner.
+
+From the left side,
+the key is `[VehicleShift instance && result of calling VehicleShift.getMaxTravelTime()]`.
+(Using the first mapping function of each joiner.)
+From the right side,
+the key is `[the result of calling Visit.getVehicleShift() && result of calling Visit.getVehicleShift().getMaxTravelTime()]`.
+(Using the second mapping function of each joiner.)
+
+However, both of the key mapping functions are calculated independent of the other, | ```suggestion
However, both of the key mapping functions are calculated independently of the other,
``` |
timefold-solver | github_2023 | others | 193 | TimefoldAI | rsynek | @@ -458,6 +458,55 @@ stream), use <<constraintStreamsConditionalPropagation,ifExists>> instead.
It does not create cartesian products and therefore generally performs better.
====
+==== Evaluation of multiple joiners
+
+When using multiple joiners, there are some important considerations to keep in mind:
+
+[source,java,options="nowrap"]
+----
+ factory.forEach(VehicleShift.class)
+ .join(Visit.class,
+ Joiners.equal(Function.identity(), Visit::getVehicleShift), // Visit's VehicleShift is not null...
+ Joiners.lessThan(
+ vehicleShift -> vehicleShift.getMaxTravelTime(),
+ visit -> visit.getVehicleShift().getMaxTravelTime() // ... yet NPE may be thrown here.
+ ))
+----
+
+When indexing joiners (such as `equal` and `lessThan`) check their indexes, | Consistency:
```suggestion
When indexing joiners (such as `equal()` and `lessThan()`) check their indexes,
``` |
timefold-solver | github_2023 | java | 193 | TimefoldAI | rsynek | @@ -0,0 +1,216 @@
+package ai.timefold.solver.constraint.streams.bavet.common;
+
+import java.util.ArrayList;
+import java.util.BitSet;
+import java.util.List;
+import java.util.function.Consumer;
+
+import ai.timefold.solver.constraint.streams.bavet.common.AbstractPropagationMetadataCarrier.PropagationType;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.AbstractTuple;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleLifecycle;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleState;
+
+/**
+ * This implementation has the capability to move tuples between the individual propagation queues.
+ * This is significantly less efficient than the {@link StaticPropagationQueue}.
+ *
+ * @param <Carrier_>
+ * @param <Tuple_>
+ */
+sealed abstract class AbstractDynamicPropagationQueue<Carrier_ extends AbstractPropagationMetadataCarrier, Tuple_ extends AbstractTuple> | I think this class (and the Static one, too) is complex enough to deserve unit tests. |
timefold-solver | github_2023 | java | 193 | TimefoldAI | rsynek | @@ -0,0 +1,93 @@
+package ai.timefold.solver.constraint.streams.bavet.common;
+
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.AbstractTuple;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.TupleState;
+
+final class Group<OutTuple_ extends AbstractTuple, ResultContainer_>
+ extends AbstractPropagationMetadataCarrier<OutTuple_> {
+
+ public static <OutTuple_ extends AbstractTuple, ResultContainer_> Group<OutTuple_, ResultContainer_>
+ createWithoutAccumulate(Object groupKey, OutTuple_ outTuple) {
+ return new Group<>(new GroupDataWithKey<>(groupKey), outTuple);
+ }
+
+ public static <OutTuple_ extends AbstractTuple, ResultContainer_> Group<OutTuple_, ResultContainer_>
+ createWithoutGroupKey(ResultContainer_ resultContainer, OutTuple_ outTuple) {
+ return new Group<>(new GroupDataWithAccumulate<>(resultContainer), outTuple);
+ }
+
+ public static <OutTuple_ extends AbstractTuple, ResultContainer_> Group<OutTuple_, ResultContainer_> create(Object groupKey,
+ ResultContainer_ resultContainer, OutTuple_ outTuple) {
+ return new Group<>(new FullGroupData<>(groupKey, resultContainer), outTuple);
+ }
+
+ private final GroupData<ResultContainer_> groupData;
+ private final OutTuple_ outTuple;
+ public int parentCount = 1;
+
+ private Group(GroupData<ResultContainer_> groupData, OutTuple_ outTuple) {
+ this.groupData = groupData;
+ this.outTuple = outTuple;
+ }
+
+ public Object getGroupKey() {
+ return groupData.groupKey();
+ }
+
+ public ResultContainer_ getResultContainer() {
+ return groupData.resultContainer();
+ }
+
+ @Override
+ public OutTuple_ getTuple() {
+ return outTuple;
+ }
+
+ @Override
+ public TupleState getState() {
+ return outTuple.state;
+ }
+
+ @Override
+ public void setState(TupleState state) {
+ outTuple.state = state;
+ }
+
+ /**
+ * Save memory by allowing to not store the group key or the result container.
+ *
+ * @param <ResultContainer_>
+ */
+ private sealed interface GroupData<ResultContainer_> {
+
+ Object groupKey();
+
+ ResultContainer_ resultContainer();
+
+ }
+
+ private record GroupDataWithKey<ResultContainer_>(Object groupKey) implements GroupData<ResultContainer_> {
+
+ @Override
+ public ResultContainer_ resultContainer() {
+ throw new UnsupportedOperationException("Impossible state: no result container for group (" + groupKey + ").");
+ }
+
+ }
+
+ private record GroupDataWithAccumulate<ResultContainer_>(
+ ResultContainer_ resultContainer) implements GroupData<ResultContainer_> {
+
+ @Override
+ public Object groupKey() {
+ throw new UnsupportedOperationException("Impossible state: no group key.");
+ }
+
+ }
+
+ private record FullGroupData<ResultContainer_>(Object groupKey, | Perhaps `GroupDataWithKeyAndAccumulate` is more descriptive? |
timefold-solver | github_2023 | java | 193 | TimefoldAI | rsynek | @@ -0,0 +1,361 @@
+package ai.timefold.solver.constraint.streams.bavet;
+
+import static ai.timefold.solver.core.api.score.stream.Joiners.filtering;
+
+import ai.timefold.solver.constraint.streams.common.AbstractConstraintStreamTest;
+import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore;
+import ai.timefold.solver.core.api.score.stream.Constraint;
+import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
+import ai.timefold.solver.core.impl.testdata.domain.TestdataEntity;
+import ai.timefold.solver.core.impl.testdata.domain.TestdataSolution;
+import ai.timefold.solver.core.impl.testdata.domain.TestdataValue;
+
+import org.junit.jupiter.api.TestTemplate;
+
+final class BavetRegressionTest extends AbstractConstraintStreamTest {
+
+ protected BavetRegressionTest(boolean constraintMatchEnabled) {
+ super(new BavetConstraintStreamImplSupport(constraintMatchEnabled));
+ }
+
+ /**
+ * @see <a href="https://github.com/TimefoldAI/timefold-solver/issues/186">Timefold Solver Github Issue 186</a>
+ */
+ @TestTemplate
+ public void filteringJoinNullConflict() {
+ InnerScoreDirector<TestdataSolution, SimpleScore> scoreDirector =
+ buildScoreDirector(TestdataSolution.buildSolutionDescriptor(),
+ factory -> new Constraint[] {
+ factory.forEach(TestdataEntity.class)
+ .join(TestdataEntity.class,
+ filtering((a, b) -> {
+ if (a.getValue() == null) {
+ throw new IllegalStateException(
+ "Impossible state: value of A is null even though forEach() should have eliminated it.");
+ } else if (b.getValue() == null) {
+ throw new IllegalStateException(
+ "Impossible state: value of B is null even though join()'s inner forEach() should have eliminated it.");
+ }
+ return true;
+ }))
+ .penalize(SimpleScore.ONE)
+ .asConstraint(TEST_CONSTRAINT_NAME)
+ });
+
+ TestdataSolution solution = TestdataSolution.generateSolution(1, 2);
+ TestdataEntity entity1 = solution.getEntityList().get(0);
+ TestdataEntity entity2 = solution.getEntityList().get(1);
+ TestdataValue value = solution.getValueList().get(0);
+ entity1.setValue(null);
+ entity2.setValue(value);
+
+ scoreDirector.setWorkingSolution(solution);
+ assertScore(scoreDirector,
+ assertMatch(entity2, entity2)); // Only entity1 is left, because forEach/join ignore nulls.
+
+ // Switch entity1 and entity2 values; now entity2 has null and entity1 does not.
+ scoreDirector.beforeVariableChanged(entity1, "value");
+ entity1.setValue(value);
+ scoreDirector.afterVariableChanged(entity1, "value");
+ scoreDirector.beforeVariableChanged(entity2, "value");
+ entity2.setValue(null);
+ scoreDirector.afterVariableChanged(entity2, "value");
+ assertScore(scoreDirector,
+ assertMatch(entity1, entity1));
+
+ // Switch entity1 and entity2 values again to test the same from the other side.
+ scoreDirector.beforeVariableChanged(entity1, "value");
+ entity1.setValue(null);
+ scoreDirector.afterVariableChanged(entity1, "value");
+ scoreDirector.beforeVariableChanged(entity2, "value");
+ entity2.setValue(value);
+ scoreDirector.afterVariableChanged(entity2, "value");
+ assertScore(scoreDirector,
+ assertMatch(entity2, entity2));
+ }
+
+ /**
+ * @see <a href="https://github.com/TimefoldAI/timefold-solver/issues/186">Timefold Solver Github Issue 186</a>
+ */
+ @TestTemplate
+ public void filteringIfExistsNullConflict() {
+ InnerScoreDirector<TestdataSolution, SimpleScore> scoreDirector =
+ buildScoreDirector(TestdataSolution.buildSolutionDescriptor(),
+ factory -> new Constraint[] {
+ factory.forEach(TestdataEntity.class)
+ .ifExists(TestdataEntity.class,
+ filtering((a, b) -> {
+ if (a.getValue() == null) {
+ throw new IllegalStateException(
+ "Impossible state: value of A is null even though forEach() should have eliminated it.");
+ }
+ return true;
+ }))
+ .penalize(SimpleScore.ONE)
+ .asConstraint(TEST_CONSTRAINT_NAME)
+ });
+
+ TestdataSolution solution = TestdataSolution.generateSolution(1, 2);
+ TestdataEntity entity1 = solution.getEntityList().get(0);
+ TestdataEntity entity2 = solution.getEntityList().get(1);
+ TestdataValue value = solution.getValueList().get(0);
+ entity1.setValue(null);
+ entity2.setValue(value);
+
+ scoreDirector.setWorkingSolution(solution);
+ assertScore(scoreDirector,
+ assertMatch(entity2)); // Only entity1 is left, because forEach/ifExists ignore nulls.
+
+ // Switch entity1 and entity2 values; now entity2 has null and entity1 does not.
+ scoreDirector.beforeVariableChanged(entity1, "value");
+ entity1.setValue(value);
+ scoreDirector.afterVariableChanged(entity1, "value");
+ scoreDirector.beforeVariableChanged(entity2, "value");
+ entity2.setValue(null);
+ scoreDirector.afterVariableChanged(entity2, "value");
+ assertScore(scoreDirector,
+ assertMatch(entity1));
+
+ // Switch entity1 and entity2 values again to test the same from the other side.
+ scoreDirector.beforeVariableChanged(entity1, "value");
+ entity1.setValue(null);
+ scoreDirector.afterVariableChanged(entity1, "value");
+ scoreDirector.beforeVariableChanged(entity2, "value");
+ entity2.setValue(value);
+ scoreDirector.afterVariableChanged(entity2, "value");
+ assertScore(scoreDirector,
+ assertMatch(entity2));
+ }
+
+ /**
+ * @see <a href="https://github.com/TimefoldAI/timefold-solver/issues/186">Timefold Solver Github Issue 186</a>
+ */
+ @TestTemplate
+ public void filteringIfNotExistsNullConflict() {
+ InnerScoreDirector<TestdataSolution, SimpleScore> scoreDirector =
+ buildScoreDirector(TestdataSolution.buildSolutionDescriptor(),
+ factory -> new Constraint[] {
+ factory.forEach(TestdataEntity.class)
+ .ifNotExists(TestdataEntity.class,
+ filtering((a, b) -> (a.getValue() != b.getValue())))
+ .penalize(SimpleScore.ONE)
+ .asConstraint(TEST_CONSTRAINT_NAME)
+ });
+
+ TestdataSolution solution = TestdataSolution.generateSolution(1, 2);
+ TestdataEntity entity1 = solution.getEntityList().get(0);
+ TestdataEntity entity2 = solution.getEntityList().get(1);
+ TestdataValue value = solution.getValueList().get(0);
+ entity1.setValue(null);
+ entity2.setValue(value);
+
+ /*
+ * forEachExclNull propagates entity2.
+ * The tuple (entity2, entity2) therefore exists, but the values are equal.
+ * Therefore entity2 should be scored.
+ */
+ scoreDirector.setWorkingSolution(solution);
+ assertScore(scoreDirector,
+ assertMatch(entity2));
+
+ // Switch entity1 and entity2 values; now entity2 has null and entity1 does not.
+ scoreDirector.beforeVariableChanged(entity1, "value");
+ entity1.setValue(value);
+ scoreDirector.afterVariableChanged(entity1, "value");
+ scoreDirector.beforeVariableChanged(entity2, "value");
+ entity2.setValue(null);
+ scoreDirector.afterVariableChanged(entity2, "value");
+ assertScore(scoreDirector,
+ assertMatch(entity1));
+
+ // Switch entity1 and entity2 values again to test the same from the other side.
+ scoreDirector.beforeVariableChanged(entity1, "value");
+ entity1.setValue(null);
+ scoreDirector.afterVariableChanged(entity1, "value");
+ scoreDirector.beforeVariableChanged(entity2, "value");
+ entity2.setValue(value);
+ scoreDirector.afterVariableChanged(entity2, "value");
+ assertScore(scoreDirector,
+ assertMatch(entity2));
+ }
+
+ /**
+ * Like {@link #filteringJoinNullConflict()}, but using two different forEach nodes.
+ */
+ @TestTemplate
+ public void filteringJoinNullConflictDifferentNodes() {
+ InnerScoreDirector<TestdataSolution, SimpleScore> scoreDirector =
+ buildScoreDirector(TestdataSolution.buildSolutionDescriptor(),
+ factory -> new Constraint[] {
+ factory.forEachIncludingNullVars(TestdataEntity.class)
+ .filter(a -> a.getValue() != null)
+ .join(TestdataEntity.class,
+ filtering((a, b) -> {
+ if (a.getValue() == null) {
+ throw new IllegalStateException(
+ "Impossible state: value of A is null even though filter() should have eliminated it.");
+ } else if (b.getValue() == null) {
+ throw new IllegalStateException(
+ "Impossible state: value of B is null even though join()'s inner forEach() should have eliminated it.");
+ }
+ return true;
+ }))
+ .penalize(SimpleScore.ONE)
+ .asConstraint(TEST_CONSTRAINT_NAME)
+ });
+
+ TestdataSolution solution = TestdataSolution.generateSolution(1, 2);
+ TestdataEntity entity1 = solution.getEntityList().get(0);
+ TestdataEntity entity2 = solution.getEntityList().get(1);
+ TestdataValue value = solution.getValueList().get(0);
+ entity1.setValue(null);
+ entity2.setValue(value);
+
+ scoreDirector.setWorkingSolution(solution);
+ // TODO update the assertions once no longer throwing exceptions | Does this note still apply? |
timefold-solver | github_2023 | java | 193 | TimefoldAI | rsynek | @@ -181,82 +184,74 @@ public void update(InTuple_ tuple) {
undoAccumulator.run();
}
- GroupKey_ oldUserSuppliedGroupKey = extractUserSuppliedKey(oldGroup.groupKey);
- GroupKey_ newUserSuppliedGroupKey = hasMultipleGroups ? groupKeyFunction.apply(tuple) : null;
+ var oldUserSuppliedGroupKey = hasMultipleGroups ? extractUserSuppliedKey(oldGroup.getGroupKey()) : null;
+ var newUserSuppliedGroupKey = hasMultipleGroups ? groupKeyFunction.apply(tuple) : null;
if (Objects.equals(newUserSuppliedGroupKey, oldUserSuppliedGroupKey)) {
// No need to change parentCount because it is the same group
- OutTuple_ outTuple = accumulate(tuple, oldGroup);
- switch (outTuple.getState()) {
- case CREATING:
- case UPDATING:
- break;
- case OK:
- outTuple.setState(TupleState.UPDATING);
- dirtyGroupQueue.add(oldGroup);
- break;
- case DYING:
- case ABORTING:
- case DEAD:
- default:
- throw new IllegalStateException("Impossible state: The group (" + oldGroup + ") in node (" +
- this + ") is in an unexpected state (" + outTuple.getState() + ").");
+ var outTuple = accumulate(tuple, oldGroup);
+ switch (outTuple.state) {
+ case CREATING, UPDATING -> {
+ // Already in the correct state.
+ }
+ case OK -> propagationQueue.update(oldGroup); | Don't we need to set the tuple state to UPDATING anymore? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.