index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset/uni/AbstractUniDataStream.java | package ai.timefold.solver.core.impl.move.streams.dataset.uni;
import static ai.timefold.solver.core.impl.bavet.common.GroupNodeConstructor.oneKeyGroupBy;
import java.util.Objects;
import java.util.function.Function;
import ai.timefold.solver.core.impl.bavet.common.GroupNodeConstructor;
import ai.timefold.solver.core.impl.bavet.common.tuple.UniTuple;
import ai.timefold.solver.core.impl.bavet.uni.Group1Mapping0CollectorUniNode;
import ai.timefold.solver.core.impl.move.streams.dataset.DataStreamFactory;
import ai.timefold.solver.core.impl.move.streams.dataset.bi.JoinBiDataStream;
import ai.timefold.solver.core.impl.move.streams.dataset.common.AbstractDataStream;
import ai.timefold.solver.core.impl.move.streams.dataset.common.bridge.AftBridgeBiDataStream;
import ai.timefold.solver.core.impl.move.streams.dataset.common.bridge.AftBridgeUniDataStream;
import ai.timefold.solver.core.impl.move.streams.dataset.common.bridge.ForeBridgeUniDataStream;
import ai.timefold.solver.core.impl.move.streams.dataset.joiner.BiDataJoinerComber;
import ai.timefold.solver.core.impl.move.streams.maybeapi.BiDataJoiner;
import ai.timefold.solver.core.impl.move.streams.maybeapi.UniDataFilter;
import ai.timefold.solver.core.impl.move.streams.maybeapi.UniDataMapper;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.BiDataStream;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.UniDataStream;
import ai.timefold.solver.core.impl.util.ConstantLambdaUtils;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
public abstract class AbstractUniDataStream<Solution_, A> extends AbstractDataStream<Solution_>
implements UniDataStream<Solution_, A> {
protected AbstractUniDataStream(DataStreamFactory<Solution_> dataStreamFactory) {
super(dataStreamFactory, null);
}
protected AbstractUniDataStream(DataStreamFactory<Solution_> dataStreamFactory,
@Nullable AbstractDataStream<Solution_> parent) {
super(dataStreamFactory, parent);
}
@Override
public final UniDataStream<Solution_, A> filter(UniDataFilter<Solution_, A> filter) {
return shareAndAddChild(new FilterUniDataStream<>(dataStreamFactory, this, filter));
}
@Override
public <B> BiDataStream<Solution_, A, B> join(UniDataStream<Solution_, B> otherStream, BiDataJoiner<A, B>... joiners) {
var other = (AbstractUniDataStream<Solution_, B>) otherStream;
var leftBridge = new ForeBridgeUniDataStream<Solution_, A>(dataStreamFactory, this);
var rightBridge = new ForeBridgeUniDataStream<Solution_, B>(dataStreamFactory, other);
var joinerComber = BiDataJoinerComber.<Solution_, A, B> comb(joiners);
var joinStream = new JoinBiDataStream<>(dataStreamFactory, leftBridge, rightBridge,
joinerComber.mergedJoiner(), joinerComber.mergedFiltering());
return dataStreamFactory.share(joinStream, joinStream_ -> {
// Connect the bridges upstream, as it is an actual new join.
getChildStreamList().add(leftBridge);
other.getChildStreamList().add(rightBridge);
});
}
@Override
public <B> BiDataStream<Solution_, A, B> join(Class<B> otherClass, BiDataJoiner<A, B>... joiners) {
return join(dataStreamFactory.forEachNonDiscriminating(otherClass, false), joiners);
}
@SafeVarargs
@Override
public final <B> UniDataStream<Solution_, A> ifExists(Class<B> otherClass, BiDataJoiner<A, B>... joiners) {
return ifExists(dataStreamFactory.forEachNonDiscriminating(otherClass, false), joiners);
}
@SafeVarargs
@Override
public final <B> UniDataStream<Solution_, A> ifExists(UniDataStream<Solution_, B> otherStream,
BiDataJoiner<A, B>... joiners) {
return ifExistsOrNot(true, otherStream, joiners);
}
@SafeVarargs
@Override
public final <B> UniDataStream<Solution_, A> ifNotExists(Class<B> otherClass, BiDataJoiner<A, B>... joiners) {
return ifExistsOrNot(false, dataStreamFactory.forEachNonDiscriminating(otherClass, false), joiners);
}
@SafeVarargs
@Override
public final <B> UniDataStream<Solution_, A> ifNotExists(UniDataStream<Solution_, B> otherStream,
BiDataJoiner<A, B>... joiners) {
return ifExistsOrNot(false, otherStream, joiners);
}
private <B> UniDataStream<Solution_, A> ifExistsOrNot(boolean shouldExist, UniDataStream<Solution_, B> otherStream,
BiDataJoiner<A, B>[] joiners) {
var other = (AbstractUniDataStream<Solution_, B>) otherStream;
var joinerComber = BiDataJoinerComber.<Solution_, A, B> comb(joiners);
var parentBridgeB = other.shareAndAddChild(new ForeBridgeUniDataStream<Solution_, B>(dataStreamFactory, other));
return dataStreamFactory.share(new IfExistsUniDataStream<>(dataStreamFactory, this, parentBridgeB, shouldExist,
joinerComber.mergedJoiner(), joinerComber.mergedFiltering()), childStreamList::add);
}
/**
* Convert the {@link UniDataStream} to a different {@link UniDataStream},
* containing the set of tuples resulting from applying the group key mapping function
* on all tuples of the original stream.
* Neither tuple of the new stream {@link Objects#equals(Object, Object)} any other.
*
* @param groupKeyMapping mapping function to convert each element in the stream to a different element
* @param <GroupKey_> the type of a fact in the destination {@link UniDataStream}'s tuple;
* must honor {@link Object#hashCode() the general contract of hashCode}.
*/
protected <GroupKey_> AbstractUniDataStream<Solution_, GroupKey_> groupBy(Function<A, GroupKey_> groupKeyMapping) {
// We do not expose this on the API, as this operation is not yet needed in any of the moves.
// The groupBy API will need revisiting if exposed as a feature of Move Streams, do not expose as is.
GroupNodeConstructor<UniTuple<GroupKey_>> nodeConstructor =
oneKeyGroupBy(groupKeyMapping, Group1Mapping0CollectorUniNode::new);
return buildUniGroupBy(nodeConstructor);
}
private <NewA> AbstractUniDataStream<Solution_, NewA>
buildUniGroupBy(GroupNodeConstructor<UniTuple<NewA>> nodeConstructor) {
var stream = shareAndAddChild(new UniGroupUniDataStream<>(dataStreamFactory, this, nodeConstructor));
return dataStreamFactory.share(new AftBridgeUniDataStream<>(dataStreamFactory, stream),
stream::setAftBridge);
}
@Override
public <ResultA_> UniDataStream<Solution_, ResultA_> map(UniDataMapper<Solution_, A, ResultA_> mapping) {
var stream = shareAndAddChild(new UniMapUniDataStream<>(dataStreamFactory, this, mapping));
return dataStreamFactory.share(new AftBridgeUniDataStream<>(dataStreamFactory, stream), stream::setAftBridge);
}
@Override
public <ResultA_, ResultB_> BiDataStream<Solution_, ResultA_, ResultB_> map(UniDataMapper<Solution_, A, ResultA_> mappingA,
UniDataMapper<Solution_, A, ResultB_> mappingB) {
var stream = shareAndAddChild(new BiMapUniDataStream<>(dataStreamFactory, this, mappingA, mappingB));
return dataStreamFactory.share(new AftBridgeBiDataStream<>(dataStreamFactory, stream), stream::setAftBridge);
}
@Override
public AbstractUniDataStream<Solution_, A> distinct() {
if (guaranteesDistinct()) {
return this; // Already distinct, no need to create a new stream.
}
return groupBy(ConstantLambdaUtils.identity());
}
public UniDataset<Solution_, A> createDataset() {
var stream = shareAndAddChild(new TerminalUniDataStream<>(dataStreamFactory, this));
return stream.getDataset();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset/uni/BiMapUniDataStream.java | package ai.timefold.solver.core.impl.move.streams.dataset.uni;
import java.util.Objects;
import ai.timefold.solver.core.impl.bavet.uni.MapUniToBiNode;
import ai.timefold.solver.core.impl.move.streams.dataset.DataStreamFactory;
import ai.timefold.solver.core.impl.move.streams.dataset.bi.AbstractBiDataStream;
import ai.timefold.solver.core.impl.move.streams.dataset.common.DataNodeBuildHelper;
import ai.timefold.solver.core.impl.move.streams.dataset.common.bridge.AftBridgeBiDataStream;
import ai.timefold.solver.core.impl.move.streams.maybeapi.UniDataMapper;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
final class BiMapUniDataStream<Solution_, A, NewA, NewB>
extends AbstractBiDataStream<Solution_, NewA, NewB> {
private final UniDataMapper<Solution_, A, NewA> mappingFunctionA;
private final UniDataMapper<Solution_, A, NewB> mappingFunctionB;
private @Nullable AftBridgeBiDataStream<Solution_, NewA, NewB> aftStream;
public BiMapUniDataStream(DataStreamFactory<Solution_> dataStreamFactory, AbstractUniDataStream<Solution_, A> parent,
UniDataMapper<Solution_, A, NewA> mappingFunctionA, UniDataMapper<Solution_, A, NewB> mappingFunctionB) {
super(dataStreamFactory, parent);
this.mappingFunctionA = mappingFunctionA;
this.mappingFunctionB = mappingFunctionB;
}
public void setAftBridge(AftBridgeBiDataStream<Solution_, NewA, NewB> aftStream) {
this.aftStream = aftStream;
}
@Override
public boolean guaranteesDistinct() {
return false;
}
@Override
public void buildNode(DataNodeBuildHelper<Solution_> buildHelper) {
assertEmptyChildStreamList();
int inputStoreIndex = buildHelper.reserveTupleStoreIndex(parent.getTupleSource());
int outputStoreSize = buildHelper.extractTupleStoreSize(aftStream);
var node = new MapUniToBiNode<>(inputStoreIndex,
mappingFunctionA.toFunction(buildHelper.getSessionContext().solutionView()),
mappingFunctionB.toFunction(buildHelper.getSessionContext().solutionView()),
buildHelper.getAggregatedTupleLifecycle(aftStream.getChildStreamList()), outputStoreSize);
buildHelper.addNode(node, this);
}
@Override
public boolean equals(Object object) {
if (this == object)
return true;
if (object == null || getClass() != object.getClass())
return false;
BiMapUniDataStream<?, ?, ?, ?> that = (BiMapUniDataStream<?, ?, ?, ?>) object;
return Objects.equals(parent, that.parent) &&
Objects.equals(mappingFunctionA, that.mappingFunctionA) &&
Objects.equals(mappingFunctionB, that.mappingFunctionB);
}
@Override
public int hashCode() {
return Objects.hash(parent, mappingFunctionA, mappingFunctionB);
}
@Override
public String toString() {
return "UniMap()";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset/uni/FilterUniDataStream.java | package ai.timefold.solver.core.impl.move.streams.dataset.uni;
import java.util.Objects;
import ai.timefold.solver.core.impl.bavet.common.tuple.TupleLifecycle;
import ai.timefold.solver.core.impl.bavet.common.tuple.UniTuple;
import ai.timefold.solver.core.impl.move.streams.dataset.DataStreamFactory;
import ai.timefold.solver.core.impl.move.streams.dataset.common.DataNodeBuildHelper;
import ai.timefold.solver.core.impl.move.streams.maybeapi.UniDataFilter;
import org.jspecify.annotations.NullMarked;
@NullMarked
final class FilterUniDataStream<Solution_, A>
extends AbstractUniDataStream<Solution_, A> {
private final UniDataFilter<Solution_, A> filter;
public FilterUniDataStream(DataStreamFactory<Solution_> dataStreamFactory, AbstractUniDataStream<Solution_, A> parent,
UniDataFilter<Solution_, A> filter) {
super(dataStreamFactory, parent);
this.filter = Objects.requireNonNull(filter, "The filter cannot be null.");
}
@Override
public void buildNode(DataNodeBuildHelper<Solution_> buildHelper) {
var predicate = filter.toPredicate(buildHelper.getSessionContext().solutionView());
buildHelper.<UniTuple<A>> putInsertUpdateRetract(this, childStreamList,
tupleLifecycle -> TupleLifecycle.conditionally(tupleLifecycle, predicate));
}
@Override
public int hashCode() {
return Objects.hash(parent, filter);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof FilterUniDataStream<?, ?> other) {
return parent == other.parent
&& filter == other.filter;
} else {
return false;
}
}
@Override
public String toString() {
return "Filter() with " + childStreamList.size() + " children";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset/uni/ForEachIncludingPinnedDataStream.java | package ai.timefold.solver.core.impl.move.streams.dataset.uni;
import java.util.Objects;
import ai.timefold.solver.core.impl.bavet.common.TupleSource;
import ai.timefold.solver.core.impl.move.streams.dataset.DataStreamFactory;
import org.jspecify.annotations.NullMarked;
@NullMarked
public final class ForEachIncludingPinnedDataStream<Solution_, A>
extends AbstractForEachDataStream<Solution_, A>
implements TupleSource {
public ForEachIncludingPinnedDataStream(DataStreamFactory<Solution_> dataStreamFactory, Class<A> forEachClass,
boolean includeNull) {
super(dataStreamFactory, forEachClass, includeNull);
}
@Override
public boolean equals(Object o) {
return o instanceof ForEachIncludingPinnedDataStream<?, ?> that &&
Objects.equals(shouldIncludeNull, that.shouldIncludeNull) &&
Objects.equals(forEachClass, that.forEachClass);
}
@Override
public int hashCode() {
return Objects.hash(shouldIncludeNull, forEachClass);
}
@Override
public String toString() {
return "ForEach (" + forEachClass.getSimpleName() + ") with " + childStreamList.size() + " children";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset/uni/IfExistsUniDataStream.java | package ai.timefold.solver.core.impl.move.streams.dataset.uni;
import java.util.Objects;
import java.util.Set;
import ai.timefold.solver.core.impl.bavet.common.AbstractIfExistsNode;
import ai.timefold.solver.core.impl.bavet.common.index.IndexerFactory;
import ai.timefold.solver.core.impl.bavet.common.tuple.TupleLifecycle;
import ai.timefold.solver.core.impl.bavet.common.tuple.UniTuple;
import ai.timefold.solver.core.impl.bavet.uni.IndexedIfExistsUniNode;
import ai.timefold.solver.core.impl.bavet.uni.UnindexedIfExistsUniNode;
import ai.timefold.solver.core.impl.move.streams.dataset.DataStreamFactory;
import ai.timefold.solver.core.impl.move.streams.dataset.common.AbstractDataStream;
import ai.timefold.solver.core.impl.move.streams.dataset.common.DataNodeBuildHelper;
import ai.timefold.solver.core.impl.move.streams.dataset.common.IfExistsDataStream;
import ai.timefold.solver.core.impl.move.streams.dataset.common.bridge.ForeBridgeUniDataStream;
import ai.timefold.solver.core.impl.move.streams.dataset.joiner.DefaultBiDataJoiner;
import ai.timefold.solver.core.impl.move.streams.maybeapi.BiDataFilter;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
final class IfExistsUniDataStream<Solution_, A, B>
extends AbstractUniDataStream<Solution_, A>
implements IfExistsDataStream<Solution_> {
private final AbstractUniDataStream<Solution_, A> parentA;
private final ForeBridgeUniDataStream<Solution_, B> parentBridgeB;
private final boolean shouldExist;
private final DefaultBiDataJoiner<A, B> joiner;
private final @Nullable BiDataFilter<Solution_, A, B> filtering;
public IfExistsUniDataStream(DataStreamFactory<Solution_> dataStreamFactory, AbstractUniDataStream<Solution_, A> parentA,
ForeBridgeUniDataStream<Solution_, B> parentBridgeB, boolean shouldExist, DefaultBiDataJoiner<A, B> joiner,
@Nullable BiDataFilter<Solution_, A, B> filtering) {
super(dataStreamFactory);
this.parentA = parentA;
this.parentBridgeB = parentBridgeB;
this.shouldExist = shouldExist;
this.joiner = joiner;
this.filtering = filtering;
}
@Override
public void collectActiveDataStreams(Set<AbstractDataStream<Solution_>> dataStreamSet) {
parentA.collectActiveDataStreams(dataStreamSet);
parentBridgeB.collectActiveDataStreams(dataStreamSet);
dataStreamSet.add(this);
}
@Override
public void buildNode(DataNodeBuildHelper<Solution_> buildHelper) {
TupleLifecycle<UniTuple<A>> downstream = buildHelper.getAggregatedTupleLifecycle(childStreamList);
var indexerFactory = new IndexerFactory<>(joiner.toBiJoiner());
var node = getNode(indexerFactory, buildHelper, downstream);
buildHelper.addNode(node, this, this, parentBridgeB);
}
private AbstractIfExistsNode<UniTuple<A>, B> getNode(IndexerFactory<B> indexerFactory,
DataNodeBuildHelper<Solution_> buildHelper, TupleLifecycle<UniTuple<A>> downstream) {
var sessionContext = buildHelper.getSessionContext();
var isFiltering = filtering != null;
if (indexerFactory.hasJoiners()) {
if (isFiltering) {
return new IndexedIfExistsUniNode<>(shouldExist, indexerFactory,
buildHelper.reserveTupleStoreIndex(parentA.getTupleSource()),
buildHelper.reserveTupleStoreIndex(parentA.getTupleSource()),
buildHelper.reserveTupleStoreIndex(parentA.getTupleSource()),
buildHelper.reserveTupleStoreIndex(parentBridgeB.getTupleSource()),
buildHelper.reserveTupleStoreIndex(parentBridgeB.getTupleSource()),
buildHelper.reserveTupleStoreIndex(parentBridgeB.getTupleSource()),
downstream, filtering.toBiPredicate(sessionContext.solutionView()));
} else {
return new IndexedIfExistsUniNode<>(shouldExist, indexerFactory,
buildHelper.reserveTupleStoreIndex(parentA.getTupleSource()),
buildHelper.reserveTupleStoreIndex(parentA.getTupleSource()),
buildHelper.reserveTupleStoreIndex(parentBridgeB.getTupleSource()),
buildHelper.reserveTupleStoreIndex(parentBridgeB.getTupleSource()),
downstream);
}
} else if (isFiltering) {
return new UnindexedIfExistsUniNode<>(shouldExist,
buildHelper.reserveTupleStoreIndex(parentA.getTupleSource()),
buildHelper.reserveTupleStoreIndex(parentA.getTupleSource()),
buildHelper.reserveTupleStoreIndex(parentBridgeB.getTupleSource()),
buildHelper.reserveTupleStoreIndex(parentBridgeB.getTupleSource()),
downstream, filtering.toBiPredicate(sessionContext.solutionView()));
} else {
return new UnindexedIfExistsUniNode<>(shouldExist,
buildHelper.reserveTupleStoreIndex(parentA.getTupleSource()),
buildHelper.reserveTupleStoreIndex(parentBridgeB.getTupleSource()), downstream);
}
}
@Override
public boolean equals(Object o) {
return o instanceof IfExistsUniDataStream<?, ?, ?> that
&& shouldExist == that.shouldExist
&& Objects.equals(parentA, that.parentA)
&& Objects.equals(parentBridgeB, that.parentBridgeB)
&& Objects.equals(joiner, that.joiner)
&& Objects.equals(filtering, that.filtering);
}
@Override
public int hashCode() {
return Objects.hash(parentA, parentBridgeB, shouldExist, joiner, filtering);
}
@Override
public String toString() {
return "IfExists() with " + childStreamList.size() + " children";
}
@Override
public AbstractDataStream<Solution_> getTupleSource() {
return parentA.getTupleSource();
}
@Override
public AbstractDataStream<Solution_> getLeftParent() {
return parentA;
}
@Override
public AbstractDataStream<Solution_> getRightParent() {
return parentBridgeB;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset/uni/TerminalUniDataStream.java | package ai.timefold.solver.core.impl.move.streams.dataset.uni;
import ai.timefold.solver.core.impl.bavet.common.tuple.UniTuple;
import ai.timefold.solver.core.impl.move.streams.dataset.DataStreamFactory;
import ai.timefold.solver.core.impl.move.streams.dataset.common.DataNodeBuildHelper;
import ai.timefold.solver.core.impl.move.streams.dataset.common.TerminalDataStream;
import org.jspecify.annotations.NullMarked;
@NullMarked
final class TerminalUniDataStream<Solution_, A>
extends AbstractUniDataStream<Solution_, A>
implements TerminalDataStream<Solution_, UniTuple<A>, UniDataset<Solution_, A>> {
private final UniDataset<Solution_, A> dataset;
public TerminalUniDataStream(DataStreamFactory<Solution_> dataStreamFactory, AbstractUniDataStream<Solution_, A> parent) {
super(dataStreamFactory, parent);
this.dataset = new UniDataset<>(dataStreamFactory, this);
}
@Override
public void buildNode(DataNodeBuildHelper<Solution_> buildHelper) {
assertEmptyChildStreamList();
var inputStoreIndex = buildHelper.reserveTupleStoreIndex(parent.getTupleSource());
buildHelper.putInsertUpdateRetract(this, dataset.instantiate(inputStoreIndex));
}
@Override
public UniDataset<Solution_, A> getDataset() {
return dataset;
}
@Override
public String toString() {
return "Terminal node";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset/uni/UniDataset.java | package ai.timefold.solver.core.impl.move.streams.dataset.uni;
import ai.timefold.solver.core.impl.bavet.common.tuple.UniTuple;
import ai.timefold.solver.core.impl.move.streams.dataset.DataStreamFactory;
import ai.timefold.solver.core.impl.move.streams.dataset.common.AbstractDataset;
import org.jspecify.annotations.NullMarked;
@NullMarked
public final class UniDataset<Solution_, A> extends AbstractDataset<Solution_, UniTuple<A>> {
public UniDataset(DataStreamFactory<Solution_> dataStreamFactory, AbstractUniDataStream<Solution_, A> parent) {
super(dataStreamFactory, parent);
}
@Override
public UniDatasetInstance<Solution_, A> instantiate(int storeIndex) {
return new UniDatasetInstance<>(this, storeIndex);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset/uni/UniDatasetInstance.java | package ai.timefold.solver.core.impl.move.streams.dataset.uni;
import java.util.Iterator;
import java.util.Random;
import ai.timefold.solver.core.impl.bavet.common.tuple.UniTuple;
import ai.timefold.solver.core.impl.move.streams.dataset.common.AbstractDataset;
import ai.timefold.solver.core.impl.move.streams.dataset.common.AbstractDatasetInstance;
import ai.timefold.solver.core.impl.util.ElementAwareList;
import ai.timefold.solver.core.impl.util.ElementAwareListEntry;
import org.jspecify.annotations.NullMarked;
@NullMarked
public final class UniDatasetInstance<Solution_, A>
extends AbstractDatasetInstance<Solution_, UniTuple<A>> {
private final ElementAwareList<UniTuple<A>> tupleList = new ElementAwareList<>();
public UniDatasetInstance(AbstractDataset<Solution_, UniTuple<A>> parent, int inputStoreIndex) {
super(parent, inputStoreIndex);
}
@Override
public void insert(UniTuple<A> tuple) {
var entry = tupleList.add(tuple);
tuple.setStore(inputStoreIndex, entry);
}
@Override
public void update(UniTuple<A> tuple) {
// No need to do anything.
}
@Override
public void retract(UniTuple<A> tuple) {
ElementAwareListEntry<UniTuple<A>> entry = tuple.removeStore(inputStoreIndex);
entry.remove();
}
public Iterator<UniTuple<A>> iterator() {
return tupleList.iterator();
}
public Iterator<UniTuple<A>> iterator(Random workingRandom) {
return tupleList.randomizedIterator(workingRandom);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset/uni/UniGroupUniDataStream.java | package ai.timefold.solver.core.impl.move.streams.dataset.uni;
import java.util.Objects;
import ai.timefold.solver.core.impl.bavet.common.GroupNodeConstructor;
import ai.timefold.solver.core.impl.bavet.common.tuple.UniTuple;
import ai.timefold.solver.core.impl.move.streams.dataset.DataStreamFactory;
import ai.timefold.solver.core.impl.move.streams.dataset.common.DataNodeBuildHelper;
import ai.timefold.solver.core.impl.move.streams.dataset.common.bridge.AftBridgeUniDataStream;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
final class UniGroupUniDataStream<Solution_, A, NewA>
extends AbstractUniDataStream<Solution_, A> {
private final GroupNodeConstructor<UniTuple<NewA>> nodeConstructor;
private @Nullable AftBridgeUniDataStream<Solution_, NewA> aftStream;
public UniGroupUniDataStream(DataStreamFactory<Solution_> dataStreamFactory, AbstractUniDataStream<Solution_, A> parent,
GroupNodeConstructor<UniTuple<NewA>> nodeConstructor) {
super(dataStreamFactory, parent);
this.nodeConstructor = nodeConstructor;
}
public void setAftBridge(AftBridgeUniDataStream<Solution_, NewA> aftStream) {
this.aftStream = aftStream;
}
// ************************************************************************
// Node creation
// ************************************************************************
@Override
public void buildNode(DataNodeBuildHelper<Solution_> buildHelper) {
var aftStreamChildList = aftStream.getChildStreamList();
nodeConstructor.build(buildHelper, parent.getTupleSource(), aftStream, aftStreamChildList, this,
dataStreamFactory.getEnvironmentMode());
}
// ************************************************************************
// Equality for node sharing
// ************************************************************************
@Override
public boolean equals(Object object) {
if (this == object)
return true;
if (object == null || getClass() != object.getClass())
return false;
var that = (UniGroupUniDataStream<?, ?, ?>) object;
return Objects.equals(parent, that.parent) && Objects.equals(nodeConstructor, that.nodeConstructor);
}
@Override
public int hashCode() {
return Objects.hash(parent, nodeConstructor);
}
@Override
public String toString() {
return "UniGroup()";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/dataset/uni/UniMapUniDataStream.java | package ai.timefold.solver.core.impl.move.streams.dataset.uni;
import java.util.Objects;
import ai.timefold.solver.core.impl.bavet.uni.MapUniToUniNode;
import ai.timefold.solver.core.impl.move.streams.dataset.DataStreamFactory;
import ai.timefold.solver.core.impl.move.streams.dataset.common.DataNodeBuildHelper;
import ai.timefold.solver.core.impl.move.streams.dataset.common.bridge.AftBridgeUniDataStream;
import ai.timefold.solver.core.impl.move.streams.maybeapi.UniDataMapper;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
final class UniMapUniDataStream<Solution_, A, NewA>
extends AbstractUniDataStream<Solution_, A> {
private final UniDataMapper<Solution_, A, NewA> mappingFunction;
private @Nullable AftBridgeUniDataStream<Solution_, NewA> aftStream;
public UniMapUniDataStream(DataStreamFactory<Solution_> dataStreamFactory, AbstractUniDataStream<Solution_, A> parent,
UniDataMapper<Solution_, A, NewA> mappingFunction) {
super(dataStreamFactory, parent);
this.mappingFunction = mappingFunction;
}
public void setAftBridge(AftBridgeUniDataStream<Solution_, NewA> aftStream) {
this.aftStream = aftStream;
}
// ************************************************************************
// Node creation
// ************************************************************************
@Override
public boolean guaranteesDistinct() {
return false;
}
@Override
public void buildNode(DataNodeBuildHelper<Solution_> buildHelper) {
assertEmptyChildStreamList();
int inputStoreIndex = buildHelper.reserveTupleStoreIndex(parent.getTupleSource());
int outputStoreSize = buildHelper.extractTupleStoreSize(aftStream);
var node = new MapUniToUniNode<>(inputStoreIndex,
mappingFunction.toFunction(buildHelper.getSessionContext().solutionView()),
buildHelper.getAggregatedTupleLifecycle(aftStream.getChildStreamList()), outputStoreSize);
buildHelper.addNode(node, this);
}
// ************************************************************************
// Equality for node sharing
// ************************************************************************
@Override
public boolean equals(Object object) {
if (this == object)
return true;
if (object == null || getClass() != object.getClass())
return false;
UniMapUniDataStream<?, ?, ?> that = (UniMapUniDataStream<?, ?, ?>) object;
return Objects.equals(parent, that.parent) && Objects.equals(mappingFunction, that.mappingFunction);
}
@Override
public int hashCode() {
return Objects.hash(parent, mappingFunction);
}
// ************************************************************************
// Getters/setters
// ************************************************************************
@Override
public String toString() {
return "UniMap()";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/BiDataFilter.java | package ai.timefold.solver.core.impl.move.streams.maybeapi;
import java.util.function.BiPredicate;
import ai.timefold.solver.core.api.function.TriPredicate;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.BiDataStream;
import ai.timefold.solver.core.preview.api.move.SolutionView;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/**
* A filter that can be applied to a {@link BiDataStream} to filter out pairs of data,
* optionally using {@link SolutionView} to query for solution state.
*
* @param <Solution_> the type of the solution
* @param <A> the type of the first parameter
* @param <B> the type of the second parameter
*/
@NullMarked
public interface BiDataFilter<Solution_, A, B> extends TriPredicate<SolutionView<Solution_>, A, B> {
@Override
boolean test(SolutionView<Solution_> solutionView, @Nullable A a, @Nullable B b);
@Override
default BiDataFilter<Solution_, A, B> and(TriPredicate<? super SolutionView<Solution_>, ? super A, ? super B> other) {
return (BiDataFilter<Solution_, A, B>) TriPredicate.super.and(other);
}
default BiPredicate<A, B> toBiPredicate(SolutionView<Solution_> solutionView) {
return (a, b) -> test(solutionView, a, b);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/BiDataJoiner.java | package ai.timefold.solver.core.impl.move.streams.maybeapi;
import ai.timefold.solver.core.api.score.stream.Joiners;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.UniDataStream;
import org.jspecify.annotations.NullMarked;
/**
* Created with {@link Joiners}.
* Used by {@link UniDataStream#join(Class, BiDataJoiner[])}, ...
*
* @see Joiners
*/
@NullMarked
public interface BiDataJoiner<A, B> {
BiDataJoiner<A, B> and(BiDataJoiner<A, B> otherJoiner);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/BiDataMapper.java | package ai.timefold.solver.core.impl.move.streams.maybeapi;
import java.util.function.BiFunction;
import ai.timefold.solver.core.api.function.TriFunction;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.BiDataStream;
import ai.timefold.solver.core.preview.api.move.SolutionView;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/**
* A mapping function that can be applied to {@link BiDataStream} to transform data,
* optionally using {@link SolutionView} to query for solution state.
*
* @param <Solution_> the type of the solution
* @param <A> the type of the first parameter
* @param <B> the type of the second parameter
*/
@NullMarked
public interface BiDataMapper<Solution_, A, B, Result_> extends TriFunction<SolutionView<Solution_>, A, B, Result_> {
@Override
Result_ apply(SolutionView<Solution_> solutionSolutionView, @Nullable A a, @Nullable B b);
default BiFunction<A, B, Result_> toBiFunction(SolutionView<Solution_> solutionView) {
return (a, b) -> apply(solutionView, a, b);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/DataJoiners.java | package ai.timefold.solver.core.impl.move.streams.maybeapi;
import java.util.function.BiPredicate;
import java.util.function.Function;
import ai.timefold.solver.core.api.score.stream.bi.BiConstraintStream;
import ai.timefold.solver.core.impl.bavet.common.joiner.JoinerType;
import ai.timefold.solver.core.impl.move.streams.dataset.joiner.DefaultBiDataJoiner;
import ai.timefold.solver.core.impl.move.streams.dataset.joiner.FilteringBiDataJoiner;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.UniDataStream;
import ai.timefold.solver.core.impl.util.ConstantLambdaUtils;
import org.jspecify.annotations.NullMarked;
/**
* Creates an {@link BiDataJoiner}, ... instance
* for use in {@link UniDataStream#join(Class, BiDataJoiner[])}, ...
*/
@NullMarked
public final class DataJoiners {
/**
* As defined by {@link #equal(Function)} with {@link Function#identity()} as the argument.
*
* @param <A> the type of both objects
*/
public static <A> BiDataJoiner<A, A> equal() {
return equal(ConstantLambdaUtils.identity());
}
/**
* As defined by {@link #equal(Function, Function)} with both arguments using the same mapping.
*
* @param <A> the type of both objects
* @param <Property_> the type of the property to compare
* @param mapping mapping function to apply to both A and B
*/
public static <A, Property_> BiDataJoiner<A, A> equal(Function<A, Property_> mapping) {
return equal(mapping, mapping);
}
/**
* Joins every A and B that share a property.
* These are exactly the pairs where {@code leftMapping.apply(A).equals(rightMapping.apply(B))}.
* For example, on a cartesian product of list {@code [Ann(age = 20), Beth(age = 25), Eric(age = 20)]}
* with both leftMapping and rightMapping being {@code Person::getAge},
* this joiner will produce pairs {@code (Ann, Ann), (Ann, Eric), (Beth, Beth), (Eric, Ann), (Eric, Eric)}.
*
* @param <B> the type of object on the right
* @param <Property_> the type of the property to compare
* @param leftMapping mapping function to apply to A
* @param rightMapping mapping function to apply to B
*/
public static <A, B, Property_> BiDataJoiner<A, B> equal(Function<A, Property_> leftMapping,
Function<B, Property_> rightMapping) {
return new DefaultBiDataJoiner<>(leftMapping, JoinerType.EQUAL, rightMapping);
}
/**
* As defined by {@link #lessThan(Function, Function)} with both arguments using the same mapping.
*
* @param mapping mapping function to apply
* @param <A> the type of both objects
* @param <Property_> the type of the property to compare
*/
public static <A, Property_ extends Comparable<Property_>> BiDataJoiner<A, A>
lessThan(Function<A, Property_> mapping) {
return lessThan(mapping, mapping);
}
/**
* Joins every A and B where a value of property on A is less than the value of a property on B.
* These are exactly the pairs where {@code leftMapping.apply(A).compareTo(rightMapping.apply(B)) < 0}.
*
* For example, on a cartesian product of list {@code [Ann(age = 20), Beth(age = 25), Eric(age = 20)]}
* with both leftMapping and rightMapping being {@code Person::getAge},
* this joiner will produce pairs {@code (Ann, Beth), (Eric, Beth)}.
*
* @param leftMapping mapping function to apply to A
* @param rightMapping mapping function to apply to B
* @param <A> the type of object on the left
* @param <B> the type of object on the right
* @param <Property_> the type of the property to compare
*/
public static <A, B, Property_ extends Comparable<Property_>> BiDataJoiner<A, B> lessThan(
Function<A, Property_> leftMapping, Function<B, Property_> rightMapping) {
return new DefaultBiDataJoiner<>(leftMapping, JoinerType.LESS_THAN, rightMapping);
}
/**
* As defined by {@link #lessThanOrEqual(Function, Function)} with both arguments using the same mapping.
*
* @param mapping mapping function to apply
* @param <A> the type of both objects
* @param <Property_> the type of the property to compare
*/
public static <A, Property_ extends Comparable<Property_>> BiDataJoiner<A, A> lessThanOrEqual(
Function<A, Property_> mapping) {
return lessThanOrEqual(mapping, mapping);
}
/**
* Joins every A and B where a value of property on A is less than or equal to the value of a property on B.
* These are exactly the pairs where {@code leftMapping.apply(A).compareTo(rightMapping.apply(B)) <= 0}.
*
* For example, on a cartesian product of list {@code [Ann(age = 20), Beth(age = 25), Eric(age = 20)]}
* with both leftMapping and rightMapping being {@code Person::getAge},
* this joiner will produce pairs
* {@code (Ann, Ann), (Ann, Beth), (Ann, Eric), (Beth, Beth), (Eric, Ann), (Eric, Beth), (Eric, Eric)}.
*
* @param leftMapping mapping function to apply to A
* @param rightMapping mapping function to apply to B
* @param <A> the type of object on the left
* @param <B> the type of object on the right
* @param <Property_> the type of the property to compare
*/
public static <A, B, Property_ extends Comparable<Property_>> BiDataJoiner<A, B> lessThanOrEqual(
Function<A, Property_> leftMapping, Function<B, Property_> rightMapping) {
return new DefaultBiDataJoiner<>(leftMapping, JoinerType.LESS_THAN_OR_EQUAL, rightMapping);
}
/**
* As defined by {@link #greaterThan(Function, Function)} with both arguments using the same mapping.
*
* @param mapping mapping function to apply
* @param <A> the type of both objects
* @param <Property_> the type of the property to compare
*/
public static <A, Property_ extends Comparable<Property_>> BiDataJoiner<A, A> greaterThan(
Function<A, Property_> mapping) {
return greaterThan(mapping, mapping);
}
/**
* Joins every A and B where a value of property on A is greater than the value of a property on B.
* These are exactly the pairs where {@code leftMapping.apply(A).compareTo(rightMapping.apply(B)) > 0}.
*
* For example, on a cartesian product of list {@code [Ann(age = 20), Beth(age = 25), Eric(age = 20)]}
* with both leftMapping and rightMapping being {@code Person::getAge},
* this joiner will produce pairs {@code (Beth, Ann), (Beth, Eric)}.
*
* @param leftMapping mapping function to apply to A
* @param rightMapping mapping function to apply to B
* @param <A> the type of object on the left
* @param <B> the type of object on the right
* @param <Property_> the type of the property to compare
*/
public static <A, B, Property_ extends Comparable<Property_>> BiDataJoiner<A, B> greaterThan(
Function<A, Property_> leftMapping, Function<B, Property_> rightMapping) {
return new DefaultBiDataJoiner<>(leftMapping, JoinerType.GREATER_THAN, rightMapping);
}
/**
* As defined by {@link #greaterThanOrEqual(Function, Function)} with both arguments using the same mapping.
*
* @param mapping mapping function to apply
* @param <A> the type of both objects
* @param <Property_> the type of the property to compare
*/
public static <A, Property_ extends Comparable<Property_>> BiDataJoiner<A, A> greaterThanOrEqual(
Function<A, Property_> mapping) {
return greaterThanOrEqual(mapping, mapping);
}
/**
* Joins every A and B where a value of property on A is greater than or equal to the value of a property on B.
* These are exactly the pairs where {@code leftMapping.apply(A).compareTo(rightMapping.apply(B)) >= 0}.
*
* For example, on a cartesian product of list {@code [Ann(age = 20), Beth(age = 25), Eric(age = 20)]}
* with both leftMapping and rightMapping being {@code Person::getAge},
* this joiner will produce pairs
* {@code (Ann, Ann), (Ann, Eric), (Beth, Ann), (Beth, Beth), (Beth, Eric), (Eric, Ann), (Eric, Eric)}.
*
* @param leftMapping mapping function to apply to A
* @param rightMapping mapping function to apply to B
* @param <A> the type of object on the left
* @param <B> the type of object on the right
* @param <Property_> the type of the property to compare
*/
public static <A, B, Property_ extends Comparable<Property_>> BiDataJoiner<A, B> greaterThanOrEqual(
Function<A, Property_> leftMapping, Function<B, Property_> rightMapping) {
return new DefaultBiDataJoiner<>(leftMapping, JoinerType.GREATER_THAN_OR_EQUAL, rightMapping);
}
/**
* Applies a filter to the joined tuple, with the semantics of {@link BiConstraintStream#filter(BiPredicate)}.
*
* For example, on a cartesian product of list {@code [Ann(age = 20), Beth(age = 25), Eric(age = 20)]}
* with filter being {@code age == 20},
* this joiner will produce pairs {@code (Ann, Ann), (Ann, Eric), (Eric, Ann), (Eric, Eric)}.
*
* @param filter filter to apply
* @param <A> type of the first fact in the tuple
* @param <B> type of the second fact in the tuple
*/
public static <Solution_, A, B> BiDataJoiner<A, B> filtering(BiDataFilter<Solution_, A, B> filter) {
return new FilteringBiDataJoiner<>(filter);
}
/**
* Joins every A and B that overlap for an interval which is specified by a start and end property on both A and B.
* These are exactly the pairs where {@code A.start < B.end} and {@code A.end > B.start}.
*
* For example, on a cartesian product of list
* {@code [Ann(start=08:00, end=14:00), Beth(start=12:00, end=18:00), Eric(start=16:00, end=22:00)]}
* with startMapping being {@code Person::getStart} and endMapping being {@code Person::getEnd},
* this joiner will produce pairs
* {@code (Ann, Ann), (Ann, Beth), (Beth, Ann), (Beth, Beth), (Beth, Eric), (Eric, Beth), (Eric, Eric)}.
*
* @param startMapping maps the argument to the start point of its interval (inclusive)
* @param endMapping maps the argument to the end point of its interval (exclusive)
* @param <A> the type of both the first and second argument
* @param <Property_> the type used to define the interval, comparable
*/
public static <A, Property_ extends Comparable<Property_>> BiDataJoiner<A, A> overlapping(
Function<A, Property_> startMapping, Function<A, Property_> endMapping) {
return overlapping(startMapping, endMapping, startMapping, endMapping);
}
/**
* As defined by {@link #overlapping(Function, Function)}.
*
* @param leftStartMapping maps the first argument to its interval start point (inclusive)
* @param leftEndMapping maps the first argument to its interval end point (exclusive)
* @param rightStartMapping maps the second argument to its interval start point (inclusive)
* @param rightEndMapping maps the second argument to its interval end point (exclusive)
* @param <A> the type of the first argument
* @param <B> the type of the second argument
* @param <Property_> the type used to define the interval, comparable
*/
public static <A, B, Property_ extends Comparable<Property_>> BiDataJoiner<A, B> overlapping(
Function<A, Property_> leftStartMapping, Function<A, Property_> leftEndMapping,
Function<B, Property_> rightStartMapping, Function<B, Property_> rightEndMapping) {
return DataJoiners.lessThan(leftStartMapping, rightEndMapping)
.and(DataJoiners.greaterThan(leftEndMapping, rightStartMapping));
}
private DataJoiners() {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/UniDataFilter.java | package ai.timefold.solver.core.impl.move.streams.maybeapi;
import java.util.function.BiPredicate;
import java.util.function.Predicate;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.UniDataStream;
import ai.timefold.solver.core.preview.api.move.SolutionView;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/**
* A filter that can be applied to a {@link UniDataStream} to filter out pairs of data,
* optionally using {@link SolutionView} to query for solution state.
*
* @param <Solution_> the type of the solution
* @param <A> the type of the first parameter
*/
@NullMarked
public interface UniDataFilter<Solution_, A> extends BiPredicate<SolutionView<Solution_>, A> {
@Override
boolean test(SolutionView<Solution_> solutionView, @Nullable A a);
@Override
default UniDataFilter<Solution_, A> and(BiPredicate<? super SolutionView<Solution_>, ? super A> other) {
return (UniDataFilter<Solution_, A>) BiPredicate.super.and(other);
}
default Predicate<A> toPredicate(SolutionView<Solution_> solutionView) {
return a -> test(solutionView, a);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/UniDataMapper.java | package ai.timefold.solver.core.impl.move.streams.maybeapi;
import java.util.function.BiFunction;
import java.util.function.Function;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.UniDataStream;
import ai.timefold.solver.core.preview.api.move.SolutionView;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/**
* A mapping function that can be applied to {@link UniDataStream} to transform data,
* optionally using {@link SolutionView} to query for solution state.
*
* @param <Solution_> the type of the solution
* @param <A> the type of the first parameter
*/
@NullMarked
public interface UniDataMapper<Solution_, A, Result_> extends BiFunction<SolutionView<Solution_>, A, Result_> {
@Override
Result_ apply(SolutionView<Solution_> solutionSolutionView, @Nullable A a);
default Function<A, Result_> toFunction(SolutionView<Solution_> solutionView) {
return a -> apply(solutionView, a);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/package-info.java | /**
* Should eventually become {@code ai.timefold.solver.core.preview.api.move.streams}.
* TODO move this to the preview package, when we have the basic generic moves working
*/
package ai.timefold.solver.core.impl.move.streams.maybeapi; |
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic/move/AbstractMove.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.generic.move;
import java.util.List;
import ai.timefold.solver.core.impl.domain.solution.descriptor.DefaultPlanningListVariableMetaModel;
import ai.timefold.solver.core.impl.domain.solution.descriptor.DefaultPlanningVariableMetaModel;
import ai.timefold.solver.core.impl.domain.solution.descriptor.InnerVariableMetaModel;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.preview.api.domain.metamodel.GenuineVariableMetaModel;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningListVariableMetaModel;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningVariableMetaModel;
import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel;
import ai.timefold.solver.core.preview.api.move.Move;
import org.jspecify.annotations.NullMarked;
@NullMarked
public abstract class AbstractMove<Solution_> implements Move<Solution_> {
private static final char OPENING_PARENTHESES = '(';
private static final char CLOSING_PARENTHESES = ')';
public final String describe() {
var metaModels = variableMetaModels();
var substring = switch (metaModels.size()) {
case 0 -> "";
case 1 -> OPENING_PARENTHESES + getVariableDescriptor(metaModels.get(0)).getSimpleEntityAndVariableName()
+ CLOSING_PARENTHESES;
default -> {
var stringBuilder = new StringBuilder()
.append(OPENING_PARENTHESES);
var first = true;
for (var variableMetaModel : metaModels) {
if (first) {
first = false;
} else {
stringBuilder.append(", ");
}
stringBuilder.append(getVariableDescriptor(variableMetaModel).getSimpleEntityAndVariableName());
}
stringBuilder.append(CLOSING_PARENTHESES);
yield stringBuilder.toString();
}
};
return getClass().getSimpleName() + substring;
}
public abstract String toString();
public abstract List<? extends GenuineVariableMetaModel<Solution_, ?, ?>> variableMetaModels();
@SuppressWarnings("unchecked")
protected static <Solution_> VariableDescriptor<Solution_>
getVariableDescriptor(VariableMetaModel<Solution_, ?, ?> variableMetaModel) {
return ((InnerVariableMetaModel<Solution_>) variableMetaModel).variableDescriptor();
}
protected static <Solution_> GenuineVariableDescriptor<Solution_>
getVariableDescriptor(PlanningVariableMetaModel<Solution_, ?, ?> variableMetaModel) {
return ((DefaultPlanningVariableMetaModel<Solution_, ?, ?>) variableMetaModel).variableDescriptor();
}
protected static <Solution_> ListVariableDescriptor<Solution_>
getVariableDescriptor(PlanningListVariableMetaModel<Solution_, ?, ?> variableMetaModel) {
return ((DefaultPlanningListVariableMetaModel<Solution_, ?, ?>) variableMetaModel).variableDescriptor();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic/move/ChangeMove.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.generic.move;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningVariableMetaModel;
import ai.timefold.solver.core.preview.api.move.MutableSolutionView;
import ai.timefold.solver.core.preview.api.move.Rebaser;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @param <Entity_> the entity type, the class with the {@link PlanningEntity} annotation
* @param <Value_> the variable type, the type of the property with the {@link PlanningVariable} annotation
*/
@NullMarked
public class ChangeMove<Solution_, Entity_, Value_> extends AbstractMove<Solution_> {
protected final PlanningVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel;
protected final Entity_ entity;
protected final @Nullable Value_ toPlanningValue;
private @Nullable Value_ currentValue;
public ChangeMove(PlanningVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Entity_ entity,
@Nullable Value_ toPlanningValue) {
this.variableMetaModel = Objects.requireNonNull(variableMetaModel);
this.entity = Objects.requireNonNull(entity);
this.toPlanningValue = toPlanningValue;
}
protected @Nullable Value_ getValue() {
if (currentValue == null) {
currentValue = getVariableDescriptor(variableMetaModel).getValue(entity);
}
return currentValue;
}
@Override
public void execute(MutableSolutionView<Solution_> solutionView) {
getValue(); // Cache the current value if not already cached.
solutionView.changeVariable(variableMetaModel, entity, toPlanningValue);
}
@Override
public ChangeMove<Solution_, Entity_, Value_> rebase(Rebaser rebaser) {
return new ChangeMove<>(variableMetaModel, Objects.requireNonNull(rebaser.rebase(entity)),
rebaser.rebase(toPlanningValue));
}
@Override
public Collection<Entity_> extractPlanningEntities() {
return Collections.singletonList(entity);
}
@Override
public Collection<Value_> extractPlanningValues() {
return Collections.singletonList(toPlanningValue);
}
@Override
public List<PlanningVariableMetaModel<Solution_, Entity_, Value_>> variableMetaModels() {
return Collections.singletonList(variableMetaModel);
}
@Override
public boolean equals(Object o) {
return o instanceof ChangeMove<?, ?, ?> other
&& Objects.equals(variableMetaModel, other.variableMetaModel)
&& Objects.equals(entity, other.entity)
&& Objects.equals(toPlanningValue, other.toPlanningValue);
}
@Override
public int hashCode() {
return Objects.hash(variableMetaModel, entity, toPlanningValue);
}
@Override
public String toString() {
return entity + " {" + getValue() + " -> " + toPlanningValue + "}";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic/move/CompositeMove.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.generic.move;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.util.CollectionUtils;
import ai.timefold.solver.core.preview.api.move.Move;
import ai.timefold.solver.core.preview.api.move.MutableSolutionView;
import ai.timefold.solver.core.preview.api.move.Rebaser;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/**
* A CompositeMove is composed out of multiple other moves.
* <p>
* Warning: each of moves in the moveList must not rely on the effect of a previous move in the moveList
* to create its undoMove correctly.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @see Move
*/
@NullMarked
public final class CompositeMove<Solution_> implements Move<Solution_> {
/**
* @param moves never null, sometimes empty. Do not modify this argument afterwards or the CompositeMove corrupts.
* @return never null
*/
@SafeVarargs
public static <Solution_, Move_ extends Move<Solution_>> Move<Solution_> buildMove(Move_... moves) {
return switch (moves.length) {
case 0 -> throw new UnsupportedOperationException("The CompositeMove cannot be built from an empty move list.");
case 1 -> moves[0];
default -> new CompositeMove<>(moves);
};
}
/**
* @param moveList never null, sometimes empty
* @return never null
*/
@SuppressWarnings("unchecked")
public static <Solution_, Move_ extends Move<Solution_>> Move<Solution_> buildMove(List<Move_> moveList) {
return buildMove(moveList.toArray(new Move[0]));
}
private final Move<Solution_>[] moves;
private CompositeMove(Move<Solution_>[] moves) {
this.moves = moves;
}
@Override
public void execute(MutableSolutionView<Solution_> solutionView) {
for (Move<Solution_> move : moves) {
move.execute(solutionView);
}
}
@SuppressWarnings("unchecked")
@Override
public Move<Solution_> rebase(Rebaser rebaser) {
Move<Solution_>[] rebasedMoves = new Move[moves.length];
for (int i = 0; i < moves.length; i++) {
rebasedMoves[i] = moves[i].rebase(rebaser);
}
return new CompositeMove<>(rebasedMoves);
}
@Override
public Collection<?> extractPlanningEntities() {
Set<Object> entities = CollectionUtils.newLinkedHashSet(moves.length * 2);
for (Move<Solution_> move : moves) {
entities.addAll(move.extractPlanningEntities());
}
return entities;
}
@Override
public Collection<@Nullable Object> extractPlanningValues() {
Set<Object> values = CollectionUtils.newLinkedHashSet(moves.length * 2);
for (Move<Solution_> move : moves) {
values.addAll(move.extractPlanningValues());
}
return values;
}
@Override
public String describe() {
return getClass().getSimpleName() + Arrays.stream(moves)
.map(Move::describe)
.sorted()
.map(childMoveTypeDescription -> "* " + childMoveTypeDescription)
.collect(Collectors.joining(",", "(", ")"));
}
@Override
public boolean equals(Object o) {
return o instanceof CompositeMove<?> that
&& Objects.deepEquals(moves, that.moves);
}
@Override
public int hashCode() {
return Arrays.hashCode(moves);
}
@Override
public String toString() {
return Arrays.toString(moves);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic/move/ListAssignMove.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.generic.move;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningListVariableMetaModel;
import ai.timefold.solver.core.preview.api.move.Move;
import ai.timefold.solver.core.preview.api.move.MutableSolutionView;
import ai.timefold.solver.core.preview.api.move.Rebaser;
import org.jspecify.annotations.NullMarked;
@NullMarked
public final class ListAssignMove<Solution_, Entity_, Value_> extends AbstractMove<Solution_> {
private final PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel;
private final Value_ planningValue;
private final Entity_ destinationEntity;
private final int destinationIndex;
public ListAssignMove(PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Value_ planningValue,
Entity_ destinationEntity, int destinationIndex) {
this.variableMetaModel = Objects.requireNonNull(variableMetaModel);
this.planningValue = Objects.requireNonNull(planningValue);
this.destinationEntity = Objects.requireNonNull(destinationEntity);
if (destinationIndex < 0) {
throw new IllegalArgumentException("The destinationIndex (" + destinationIndex + ") must be greater than 0.");
}
this.destinationIndex = destinationIndex;
}
@Override
public void execute(MutableSolutionView<Solution_> mutableSolutionView) {
mutableSolutionView.assignValue(variableMetaModel, planningValue, destinationEntity, destinationIndex);
}
@Override
public Move<Solution_> rebase(Rebaser rebaser) {
return new ListAssignMove<>(variableMetaModel, Objects.requireNonNull(rebaser.rebase(planningValue)),
Objects.requireNonNull(rebaser.rebase(destinationEntity)), destinationIndex);
}
@Override
public Collection<Entity_> extractPlanningEntities() {
return List.of(destinationEntity);
}
@Override
public Collection<Value_> extractPlanningValues() {
return List.of(planningValue);
}
@Override
public List<PlanningListVariableMetaModel<Solution_, Entity_, Value_>> variableMetaModels() {
return List.of(variableMetaModel);
}
public Value_ getPlanningValue() {
return planningValue;
}
public Entity_ getDestinationEntity() {
return destinationEntity;
}
public int getDestinationIndex() {
return destinationIndex;
}
@Override
public boolean equals(Object o) {
return o instanceof ListAssignMove<?, ?, ?> other
&& Objects.equals(variableMetaModel, other.variableMetaModel)
&& Objects.equals(planningValue, other.planningValue)
&& Objects.equals(destinationEntity, other.destinationEntity)
&& destinationIndex == other.destinationIndex;
}
@Override
public int hashCode() {
return Objects.hash(variableMetaModel, planningValue, destinationEntity, destinationIndex);
}
@Override
public String toString() {
return String.format("%s {null -> %s[%d]}", planningValue, destinationEntity, destinationIndex);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic/move/ListChangeMove.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.generic.move;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningListVariableMetaModel;
import ai.timefold.solver.core.preview.api.move.MutableSolutionView;
import ai.timefold.solver.core.preview.api.move.Rebaser;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/**
* Moves an element of a {@link PlanningListVariable list variable}. The moved element is identified
* by an entity instance and a position in that entity's list variable. The element is inserted at the given index
* in the given destination entity's list variable.
* <p>
* An undo move is simply created by flipping the source and destination entity+index.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @param <Entity_> the entity type, the class with the {@link PlanningEntity} annotation
* @param <Value_> the variable type, the type of the property with the {@link PlanningVariable} annotation
*/
@NullMarked
public final class ListChangeMove<Solution_, Entity_, Value_> extends AbstractMove<Solution_> {
private final PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel;
private final Entity_ sourceEntity;
private final int sourceIndex;
private final Entity_ destinationEntity;
private final int destinationIndex;
private @Nullable Value_ planningValue;
/**
* The move removes a planning value element from {@code sourceEntity.listVariable[sourceIndex]}
* and inserts the planning value at {@code destinationEntity.listVariable[destinationIndex]}.
*
* <h4>ListChangeMove anatomy</h4>
*
* <pre>
* {@code
* / destinationEntity
* | / destinationIndex
* | |
* A {Ann[0]}->{Bob[2]}
* | | |
* planning value / | \ sourceIndex
* \ sourceEntity
* }
* </pre>
*
* <h4>Example 1 - source and destination entities are different</h4>
*
* <pre>
* {@code
* GIVEN
* Ann.tasks = [A, B, C]
* Bob.tasks = [X, Y]
*
* WHEN
* ListChangeMove: A {Ann[0]->Bob[2]}
*
* THEN
* Ann.tasks = [B, C]
* Bob.tasks = [X, Y, A]
* }
* </pre>
*
* <h4>Example 2 - source and destination is the same entity</h4>
*
* <pre>
* {@code
* GIVEN
* Ann.tasks = [A, B, C]
*
* WHEN
* ListChangeMove: A {Ann[0]->Ann[2]}
*
* THEN
* Ann.tasks = [B, C, A]
* }
* </pre>
*
* @param variableMetaModel never null
* @param sourceEntity planning entity instance from which a planning value will be removed, for example "Ann"
* @param sourceIndex index in sourceEntity's list variable from which a planning value will be removed
* @param destinationEntity planning entity instance to which a planning value will be moved, for example "Bob"
* @param destinationIndex index in destinationEntity's list variable where the moved planning value will be inserted
*/
public ListChangeMove(PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Entity_ sourceEntity,
int sourceIndex, Entity_ destinationEntity, int destinationIndex) {
this.variableMetaModel = Objects.requireNonNull(variableMetaModel);
this.sourceEntity = Objects.requireNonNull(sourceEntity);
if (sourceIndex < 0) {
throw new IllegalArgumentException("The sourceIndex (" + sourceIndex + ") must be greater than 0.");
}
this.sourceIndex = sourceIndex;
this.destinationEntity = Objects.requireNonNull(destinationEntity);
if (destinationIndex < 0) {
throw new IllegalArgumentException("The destinationIndex (" + destinationIndex + ") must be greater than 0.");
}
this.destinationIndex = destinationIndex;
}
@SuppressWarnings("unchecked")
private Value_ getMovedValue() {
if (planningValue == null) {
planningValue = (Value_) getVariableDescriptor(variableMetaModel)
.getValue(sourceEntity)
.get(sourceIndex);
}
return planningValue;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void execute(MutableSolutionView<Solution_> solutionView) {
planningValue = solutionView.moveValueBetweenLists(variableMetaModel, sourceEntity, sourceIndex, destinationEntity,
destinationIndex);
}
@Override
public ListChangeMove<Solution_, Entity_, Value_> rebase(Rebaser rebaser) {
return new ListChangeMove<>(variableMetaModel,
Objects.requireNonNull(rebaser.rebase(sourceEntity)), sourceIndex,
Objects.requireNonNull(rebaser.rebase(destinationEntity)), destinationIndex);
}
@Override
public Collection<Entity_> extractPlanningEntities() {
if (sourceEntity == destinationEntity) {
return Collections.singleton(sourceEntity);
} else {
return List.of(sourceEntity, destinationEntity);
}
}
@Override
public Collection<Value_> extractPlanningValues() {
return Collections.singleton(getMovedValue());
}
@Override
public List<PlanningListVariableMetaModel<Solution_, Entity_, Value_>> variableMetaModels() {
return List.of(variableMetaModel);
}
public Entity_ getSourceEntity() {
return sourceEntity;
}
public int getSourceIndex() {
return sourceIndex;
}
public Entity_ getDestinationEntity() {
return destinationEntity;
}
public int getDestinationIndex() {
return destinationIndex;
}
@Override
public boolean equals(Object o) {
return o instanceof ListChangeMove<?, ?, ?> other
&& Objects.equals(variableMetaModel, other.variableMetaModel)
&& Objects.equals(sourceEntity, other.sourceEntity)
&& sourceIndex == other.sourceIndex
&& Objects.equals(destinationEntity, other.destinationEntity)
&& destinationIndex == other.destinationIndex;
}
@Override
public int hashCode() {
return Objects.hash(variableMetaModel, sourceEntity, sourceIndex, destinationEntity, destinationIndex);
}
@Override
public String toString() {
return String.format("%s {%s[%d] -> %s[%d]}",
getMovedValue(), sourceEntity, sourceIndex, destinationEntity, destinationIndex);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic/move/ListSwapMove.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.generic.move;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningListVariableMetaModel;
import ai.timefold.solver.core.preview.api.move.MutableSolutionView;
import ai.timefold.solver.core.preview.api.move.Rebaser;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/**
* Swaps two elements of a {@link PlanningListVariable list variable}.
* Each element is identified by an entity instance and an index in that entity's list variable.
* The swap move has two sides called left and right.
* The element at {@code leftIndex} in {@code leftEntity}'s list variable
* is replaced by the element at {@code rightIndex} in {@code rightEntity}'s list variable and vice versa.
* Left and right entity can be the same instance.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @param <Entity_> the entity type, the class with the {@link PlanningEntity} annotation
* @param <Value_> the variable type, the type of the property with the {@link PlanningVariable} annotation
*/
@NullMarked
public final class ListSwapMove<Solution_, Entity_, Value_> extends AbstractMove<Solution_> {
private final PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel;
private final Entity_ leftEntity;
private final int leftIndex;
private final Entity_ rightEntity;
private final int rightIndex;
/**
* Cache of the values of the entities
* at the time of the first call of {@link #getLeftValueCache()} and {@link #getRightValueCache()} respectively.
* Ideally, the method would first be called before the values are changed by the move,
* so that the {@link #toString()} method shows the original values.
*/
private @Nullable Value_ leftValue;
private @Nullable Value_ rightValue;
/**
* Create a move that swaps a list variable element at {@code leftEntity.listVariable[leftIndex]} with
* {@code rightEntity.listVariable[rightIndex]}.
*
* <h4>ListSwapMove anatomy</h4>
*
* <pre>
* {@code
* / rightEntity
* right element \ | / rightIndex
* | | |
* A {Ann[0]} <-> Y {Bob[1]}
* | | |
* left element / | \ leftIndex
* \ leftEntity
* }
* </pre>
*
* <h4>Example</h4>
*
* <pre>
* {@code
* GIVEN
* Ann.tasks = [A, B, C]
* Bob.tasks = [X, Y]
*
* WHEN
* ListSwapMove: A {Ann[0]} <-> Y {Bob[1]}
*
* THEN
* Ann.tasks = [Y, B, C]
* Bob.tasks = [X, A]
* }
* </pre>
*
* @param variableMetaModel describes the variable to be changed by this move
* @param leftEntity together with {@code leftIndex} identifies the left element to be moved
* @param leftIndex together with {@code leftEntity} identifies the left element to be moved
* @param rightEntity together with {@code rightIndex} identifies the right element to be moved
* @param rightIndex together with {@code rightEntity} identifies the right element to be moved
*/
public ListSwapMove(PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Entity_ leftEntity,
int leftIndex, Entity_ rightEntity, int rightIndex) {
this.variableMetaModel = variableMetaModel;
this.leftEntity = leftEntity;
this.leftIndex = leftIndex;
this.rightEntity = rightEntity;
this.rightIndex = rightIndex;
}
public Entity_ getLeftEntity() {
return leftEntity;
}
public int getLeftIndex() {
return leftIndex;
}
public Entity_ getRightEntity() {
return rightEntity;
}
public int getRightIndex() {
return rightIndex;
}
private Value_ getLeftValueCache() {
if (leftValue == null) {
leftValue = getVariableDescriptor(variableMetaModel).getElement(leftEntity, leftIndex);
}
return leftValue;
}
private Value_ getRightValueCache() {
if (rightValue == null) {
rightValue = getVariableDescriptor(variableMetaModel).getElement(rightEntity, rightIndex);
}
return rightValue;
}
@Override
public void execute(MutableSolutionView<Solution_> solutionView) {
solutionView.swapValuesBetweenLists(variableMetaModel, leftEntity, leftIndex, rightEntity, rightIndex);
}
@Override
public ListSwapMove<Solution_, Entity_, Value_> rebase(Rebaser rebaser) {
return new ListSwapMove<>(variableMetaModel, rebaser.rebase(leftEntity), leftIndex, rebaser.rebase(rightEntity),
rightIndex);
}
@Override
public List<PlanningListVariableMetaModel<Solution_, Entity_, Value_>> variableMetaModels() {
return Collections.singletonList(variableMetaModel);
}
@Override
public Collection<Entity_> extractPlanningEntities() {
return leftEntity == rightEntity ? Collections.singleton(leftEntity) : Arrays.asList(leftEntity, rightEntity);
}
@Override
public Collection<Value_> extractPlanningValues() {
return Arrays.asList(getLeftValueCache(), getRightValueCache());
}
@Override
public boolean equals(Object o) {
return o instanceof ListSwapMove<?, ?, ?> other
&& Objects.equals(variableMetaModel, other.variableMetaModel)
&& Objects.equals(leftEntity, other.leftEntity)
&& leftIndex == other.leftIndex
&& Objects.equals(rightEntity, other.rightEntity)
&& rightIndex == other.rightIndex;
}
@Override
public int hashCode() {
return Objects.hash(variableMetaModel, leftEntity, leftIndex, rightEntity, rightIndex);
}
@Override
public String toString() {
return String.format("%s {%s[%d]} <-> %s {%s[%d]}",
getLeftValueCache(), leftEntity, leftIndex,
getRightValueCache(), rightEntity, rightIndex);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic/move/ListUnassignMove.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.generic.move;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningListVariableMetaModel;
import ai.timefold.solver.core.preview.api.move.Move;
import ai.timefold.solver.core.preview.api.move.MutableSolutionView;
import ai.timefold.solver.core.preview.api.move.Rebaser;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
public final class ListUnassignMove<Solution_, Entity_, Value_> extends AbstractMove<Solution_> {
private final PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel;
private final Entity_ sourceEntity;
private final int sourceIndex;
private @Nullable Value_ unassignedValue;
public ListUnassignMove(PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel, Entity_ sourceEntity,
int sourceIndex) {
this.variableMetaModel = Objects.requireNonNull(variableMetaModel);
this.sourceEntity = Objects.requireNonNull(sourceEntity);
if (sourceIndex < 0) {
throw new IllegalArgumentException("The sourceIndex (" + sourceIndex + ") must be greater than or equal to 0.");
}
this.sourceIndex = sourceIndex;
}
@Override
public void execute(MutableSolutionView<Solution_> solutionView) {
unassignedValue = solutionView.unassignValue(variableMetaModel, sourceEntity, sourceIndex);
}
@Override
public Move<Solution_> rebase(Rebaser rebaser) {
return new ListUnassignMove<>(variableMetaModel, rebaser.rebase(sourceEntity), sourceIndex);
}
@Override
public Collection<Entity_> extractPlanningEntities() {
return Collections.singleton(sourceEntity);
}
@Override
public Collection<Value_> extractPlanningValues() {
return Collections.singleton(getUnassignedValue());
}
private Value_ getUnassignedValue() {
if (unassignedValue == null) {
unassignedValue =
Objects.requireNonNull(getVariableDescriptor(variableMetaModel).getElement(sourceEntity, sourceIndex));
}
return unassignedValue;
}
@Override
public List<PlanningListVariableMetaModel<Solution_, Entity_, Value_>> variableMetaModels() {
return Collections.singletonList(variableMetaModel);
}
public Entity_ getSourceEntity() {
return sourceEntity;
}
public int getSourceIndex() {
return sourceIndex;
}
@Override
public boolean equals(Object o) {
return o instanceof ListUnassignMove<?, ?, ?> other
&& Objects.equals(variableMetaModel, other.variableMetaModel)
&& Objects.equals(sourceEntity, other.sourceEntity)
&& sourceIndex == other.sourceIndex;
}
@Override
public int hashCode() {
return Objects.hash(variableMetaModel, sourceEntity, sourceIndex);
}
@Override
public String toString() {
return String.format("%s {%s[%d] -> null}", getUnassignedValue(), sourceEntity, sourceIndex);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic/move/SwapMove.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.generic.move;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningVariableMetaModel;
import ai.timefold.solver.core.preview.api.move.MutableSolutionView;
import ai.timefold.solver.core.preview.api.move.Rebaser;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/**
* Swaps values of {@link PlanningVariable} between two different {@link PlanningEntity} instances.
* Requires to specify a (sub)set of variables to swap values of,
* all of which must belong to the same entity class.
*
* <p>
* Only provide entities whose values can be swapped;
* for example, if one of the values is not in the value range of the other entity's variable,
* then swapping would lead to an invalid solution.
* This move will skip that swap,
* but it is more efficient to not propose it in the first place.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @param <Entity_> the entity type, the class with the {@link PlanningEntity} annotation
*/
@NullMarked
public final class SwapMove<Solution_, Entity_> extends AbstractMove<Solution_> {
private final List<PlanningVariableMetaModel<Solution_, Entity_, Object>> variableMetaModelList;
private final Entity_ leftEntity;
private final Entity_ rightEntity;
/**
* Cache of the values of the entities at the time of the first call of {@link #getCachedValues()}.
* Ideally, the method would first be called before the values are changed by the move,
* so that the {@link #toString()} method shows the original values.
* <p>
* The list is structured such that for each variable in {@link #variableMetaModelList},
* in order, it contains first the value of {@link #leftEntity} and then the value of {@link #rightEntity}.
* Example: with two variables v1 and v2, the list contains [left.v1, right.v1, left.v2, right.v2].
*/
private @Nullable List<@Nullable Object> valueCache;
public SwapMove(List<PlanningVariableMetaModel<Solution_, Entity_, Object>> variableMetaModelList, Entity_ leftEntity,
Entity_ rightEntity) {
this.variableMetaModelList = Objects.requireNonNull(variableMetaModelList);
if (variableMetaModelList.isEmpty()) {
throw new IllegalArgumentException(
"Swap move requires at least one planning variable to swap between entities, but got (%s)."
.formatted(variableMetaModelList));
}
this.leftEntity = Objects.requireNonNull(leftEntity);
this.rightEntity = Objects.requireNonNull(rightEntity);
if (leftEntity == rightEntity) {
throw new IllegalArgumentException("Swap move requires two different entities (%s)."
.formatted(leftEntity));
}
}
@Override
public List<PlanningVariableMetaModel<Solution_, Entity_, Object>> variableMetaModels() {
return variableMetaModelList;
}
public Entity_ getLeftEntity() {
return leftEntity;
}
public Entity_ getRightEntity() {
return rightEntity;
}
@Override
public SwapMove<Solution_, Entity_> rebase(Rebaser rebaser) {
return new SwapMove<>(variableMetaModelList, rebaser.rebase(leftEntity), rebaser.rebase(rightEntity));
}
@Override
public void execute(MutableSolutionView<Solution_> solutionView) {
var cachedValues = getCachedValues();
for (var i = 0; i < cachedValues.size(); i += 2) {
var variableMetaModel = variableMetaModelList.get(i / 2);
var oldLeftValue = cachedValues.get(i);
var oldRightValue = cachedValues.get(i + 1);
if (Objects.equals(oldLeftValue, oldRightValue)
|| !solutionView.isValueInRange(variableMetaModel, leftEntity, oldRightValue)
|| !solutionView.isValueInRange(variableMetaModel, rightEntity, oldLeftValue)) {
// No change needed, skip it.
continue;
}
solutionView.changeVariable(variableMetaModel, leftEntity, oldRightValue);
solutionView.changeVariable(variableMetaModel, rightEntity, oldLeftValue);
}
}
private List<@Nullable Object> getCachedValues() {
if (valueCache != null) {
return valueCache;
}
valueCache = new ArrayList<>(variableMetaModelList.size() * 2);
for (var variableMetaModel : variableMetaModelList) {
var variableDescriptor = getVariableDescriptor(variableMetaModel);
valueCache.add(variableDescriptor.getValue(leftEntity));
valueCache.add(variableDescriptor.getValue(rightEntity));
}
return valueCache;
}
@Override
public Collection<Entity_> extractPlanningEntities() {
return List.of(leftEntity, rightEntity);
}
@Override
public Collection<@Nullable Object> extractPlanningValues() {
return new LinkedHashSet<>(getCachedValues()); // Not using Set.of(), as values may be null.
}
@Override
public boolean equals(Object o) {
return o instanceof SwapMove<?, ?> other
&& Objects.equals(variableMetaModelList, other.variableMetaModelList)
&& Objects.equals(leftEntity, other.leftEntity)
&& Objects.equals(rightEntity, other.rightEntity);
}
@Override
public int hashCode() {
return Objects.hash(variableMetaModelList, leftEntity, rightEntity);
}
@Override
public String toString() {
var s = new StringBuilder(variableMetaModelList.size() * 16);
s.append(leftEntity).append(" {");
appendVariablesToString(s, true);
s.append("} <-> ");
s.append(rightEntity).append(" {");
appendVariablesToString(s, false);
s.append("}");
return s.toString();
}
private void appendVariablesToString(StringBuilder s, boolean isLeftEntity) {
var cachedValues = getCachedValues();
for (var i = 0; i < cachedValues.size(); i += 2) {
var index = isLeftEntity ? i : i + 1;
var value = cachedValues.get(index);
if (i > 0) {
s.append(", ");
}
s.append(value == null ? "null" : value.toString());
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic/provider/ChangeMoveProvider.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.generic.provider;
import java.util.Objects;
import ai.timefold.solver.core.impl.move.streams.maybeapi.generic.move.ChangeMove;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.MoveProducer;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.MoveProvider;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.MoveStreamFactory;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningVariableMetaModel;
import org.jspecify.annotations.NullMarked;
@NullMarked
public class ChangeMoveProvider<Solution_, Entity_, Value_>
implements MoveProvider<Solution_> {
private final PlanningVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel;
public ChangeMoveProvider(PlanningVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel) {
this.variableMetaModel = Objects.requireNonNull(variableMetaModel);
}
@Override
public MoveProducer<Solution_> apply(MoveStreamFactory<Solution_> moveStreamFactory) {
var dataStream = moveStreamFactory.enumerateEntityValuePairs(variableMetaModel)
.filter((solutionView, entity, value) -> {
Value_ currentValue = solutionView.getValue(variableMetaModel, Objects.requireNonNull(entity));
return !Objects.equals(currentValue, value);
});
return moveStreamFactory.pick(dataStream)
.asMove((solution, entity, value) -> new ChangeMove<>(variableMetaModel, Objects.requireNonNull(entity),
value));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic/provider/ListChangeMoveProvider.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.generic.provider;
import java.util.Objects;
import ai.timefold.solver.core.impl.move.streams.maybeapi.BiDataFilter;
import ai.timefold.solver.core.impl.move.streams.maybeapi.DataJoiners;
import ai.timefold.solver.core.impl.move.streams.maybeapi.generic.move.ListAssignMove;
import ai.timefold.solver.core.impl.move.streams.maybeapi.generic.move.ListChangeMove;
import ai.timefold.solver.core.impl.move.streams.maybeapi.generic.move.ListUnassignMove;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.MoveProducer;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.MoveProvider;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.MoveStreamFactory;
import ai.timefold.solver.core.preview.api.domain.metamodel.ElementPosition;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningListVariableMetaModel;
import ai.timefold.solver.core.preview.api.domain.metamodel.PositionInList;
import ai.timefold.solver.core.preview.api.domain.metamodel.UnassignedElement;
import ai.timefold.solver.core.preview.api.move.SolutionView;
import org.jspecify.annotations.NullMarked;
/**
* For each unassigned value, creates a move to assign it to some position of some list variable.
* For each assigned value that is not pinned, creates:
*
* <ul>
* <li>A move to unassign it.</li>
* <li>A move to reassign it to another position if assigned.</li>
* </ul>
*
* To assign or reassign a value, creates:
*
* <ul>
* <li>A move for every unpinned value in every entity's list variable to assign the value before that position.</li>
* <li>A move for every entity to assign it to the last position in the list variable.</li>
* </ul>
*
* This is a generic move provider that works with any list variable;
* user-defined change move providers needn't be this complex, as they understand the specifics of the domain.
*/
@NullMarked
public class ListChangeMoveProvider<Solution_, Entity_, Value_>
implements MoveProvider<Solution_> {
private final PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel;
private final BiDataFilter<Solution_, Entity_, Value_> isValueInListFilter;
public ListChangeMoveProvider(PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel) {
this.variableMetaModel = Objects.requireNonNull(variableMetaModel);
this.isValueInListFilter = (solution, entity, value) -> {
if (entity == null || value == null) {
// Necessary for the null to survive until the later stage,
// where we will use it as a special marker to either unassign the value,
// or move it to the end of list.
return true;
}
return solution.isValueInRange(variableMetaModel, entity, value);
};
}
@Override
public MoveProducer<Solution_> apply(MoveStreamFactory<Solution_> moveStreamFactory) {
// Stream with unpinned entities;
// includes null if the variable allows unassigned values.
var unpinnedEntities =
moveStreamFactory.enumerate(variableMetaModel.entity().type(), variableMetaModel.allowsUnassignedValues());
// Stream with unpinned values, which are assigned to any list variable;
// always includes null so that we can later create a position at the end of the list,
// i.e. with no value after it.
var unpinnedValues = moveStreamFactory.enumerate(variableMetaModel.type(), true)
.filter((solutionView, value) -> value == null
|| solutionView.getPositionOf(variableMetaModel, value) instanceof PositionInList);
// Joins the two previous streams to create pairs of (entity, value),
// eliminating values which do not match that entity's value range.
// It maps these pairs to expected target positions in that entity's list variable.
var entityValuePairs = unpinnedEntities.join(unpinnedValues, DataJoiners.filtering(isValueInListFilter))
.map((solutionView, entity, value) -> {
if (entity == null) { // Null entity means we need to unassign the value.
return ElementPosition.unassigned();
}
var valueCount = solutionView.countValues(variableMetaModel, entity);
if (value == null || valueCount == 0) { // This will trigger assignment of the value at the end of the list.
return ElementPosition.of(entity, valueCount);
} else { // This will trigger assignment of the value immediately before this value.
return solutionView.getPositionOf(variableMetaModel, value);
}
})
.distinct();
// Finally the stream of these positions is joined with the stream of all existing values,
// filtering out those which would not result in a valid move.
var dataStream = moveStreamFactory.enumerate(variableMetaModel.type(), false)
.join(entityValuePairs, DataJoiners.filtering(this::isValidChange));
// When picking from this stream, we decide what kind of move we need to create,
// based on whether the value is assigned or unassigned.
return moveStreamFactory.pick(dataStream)
.asMove((solutionView, value, targetPosition) -> {
var currentPosition = solutionView.getPositionOf(variableMetaModel, Objects.requireNonNull(value));
if (targetPosition instanceof UnassignedElement) {
var currentElementPosition = currentPosition.ensureAssigned();
return new ListUnassignMove<>(variableMetaModel, currentElementPosition.entity(),
currentElementPosition.index());
}
var targetElementPosition = Objects.requireNonNull(targetPosition).ensureAssigned();
if (currentPosition instanceof UnassignedElement) {
return new ListAssignMove<>(variableMetaModel, value, targetElementPosition.entity(),
targetElementPosition.index());
}
var currentElementPosition = currentPosition.ensureAssigned();
return new ListChangeMove<>(variableMetaModel, currentElementPosition.entity(),
currentElementPosition.index(), targetElementPosition.entity(), targetElementPosition.index());
});
}
private boolean isValidChange(SolutionView<Solution_> solutionView, Value_ value, ElementPosition targetPosition) {
var currentPosition = solutionView.getPositionOf(variableMetaModel, value);
if (currentPosition.equals(targetPosition)) { // No change needed.
return false;
}
if (currentPosition instanceof UnassignedElement) { // Only assign the value if the target entity will accept it.
var targetPositionInList = targetPosition.ensureAssigned();
return solutionView.isValueInRange(variableMetaModel, targetPositionInList.entity(), value);
}
if (!(targetPosition instanceof PositionInList targetPositionInList)) { // Unassigning a value.
return true;
}
var currentPositionInList = currentPosition.ensureAssigned();
if (currentPositionInList.entity() == targetPositionInList.entity()) { // The value is already in the list.
var valueCount = solutionView.countValues(variableMetaModel, currentPositionInList.entity());
if (valueCount == 1) { // The value is the only value in the list; no change.
return false;
} else if (targetPositionInList.index() == valueCount) { // Trying to move the value past the end of the list.
return false;
} else { // Same list, same position; ignore.
return currentPositionInList.index() != targetPositionInList.index();
}
}
// We can move freely between entities, assuming the target entity accepts the value.
return solutionView.isValueInRange(variableMetaModel, targetPositionInList.entity(), value);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic/provider/ListSwapMoveProvider.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.generic.provider;
import java.util.Objects;
import ai.timefold.solver.core.impl.move.streams.maybeapi.DataJoiners;
import ai.timefold.solver.core.impl.move.streams.maybeapi.generic.move.ListSwapMove;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.MoveProducer;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.MoveProvider;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.MoveStreamFactory;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningListVariableMetaModel;
import ai.timefold.solver.core.preview.api.domain.metamodel.PositionInList;
import ai.timefold.solver.core.preview.api.move.SolutionView;
import org.jspecify.annotations.NullMarked;
@NullMarked
public class ListSwapMoveProvider<Solution_, Entity_, Value_>
implements MoveProvider<Solution_> {
private final PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel;
public ListSwapMoveProvider(PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel) {
this.variableMetaModel = Objects.requireNonNull(variableMetaModel);
}
@Override
public MoveProducer<Solution_> apply(MoveStreamFactory<Solution_> moveStreamFactory) {
var assignedValueStream = moveStreamFactory.enumerate(variableMetaModel.type(), false)
.filter((solutionView,
value) -> solutionView.getPositionOf(variableMetaModel, value) instanceof PositionInList);
var validAssignedValuePairStream = assignedValueStream.join(assignedValueStream,
DataJoiners.filtering((SolutionView<Solution_> solutionView, Value_ leftValue,
Value_ rightValue) -> !Objects.equals(leftValue, rightValue)));
// Ensure unique pairs; without demanding PlanningId, this becomes tricky.
// Convert values to their locations in list.
var validAssignedValueUniquePairStream =
validAssignedValuePairStream
.map((solutionView, leftValue, rightValue) -> new UniquePair<>(leftValue, rightValue))
.distinct()
.map((solutionView, pair) -> FullElementPosition.of(variableMetaModel, solutionView, pair.first()),
(solutionView, pair) -> FullElementPosition.of(variableMetaModel, solutionView, pair.second()));
// Eliminate pairs that cannot be swapped due to value range restrictions.
var result = validAssignedValueUniquePairStream
.filter((solutionView, leftPosition, rightPosition) -> solutionView.isValueInRange(variableMetaModel,
rightPosition.entity(), leftPosition.value())
&& solutionView.isValueInRange(variableMetaModel, leftPosition.entity(), rightPosition.value()));
// Finally pick the moves.
return moveStreamFactory.pick(result)
.asMove((solutionView, leftPosition, rightPosition) -> new ListSwapMove<>(variableMetaModel,
leftPosition.entity(), leftPosition.index(),
rightPosition.entity(), rightPosition.index()));
}
private record FullElementPosition<Entity_, Value_>(Value_ value, Entity_ entity, int index) {
public static <Solution_, Entity_, Value_> FullElementPosition<Entity_, Value_> of(
PlanningListVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel,
SolutionView<Solution_> solutionView, Value_ value) {
var assignedElement = solutionView.getPositionOf(variableMetaModel, value).ensureAssigned();
return new FullElementPosition<>(value, assignedElement.entity(), assignedElement.index());
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic/provider/SwapMoveProvider.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.generic.provider;
import static ai.timefold.solver.core.impl.move.streams.maybeapi.DataJoiners.filtering;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;
import ai.timefold.solver.core.impl.domain.solution.descriptor.DefaultPlanningVariableMetaModel;
import ai.timefold.solver.core.impl.move.streams.maybeapi.generic.move.SwapMove;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.MoveProducer;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.MoveProvider;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.MoveStreamFactory;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningEntityMetaModel;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningVariableMetaModel;
import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel;
import ai.timefold.solver.core.preview.api.move.SolutionView;
import org.jspecify.annotations.NullMarked;
@NullMarked
public class SwapMoveProvider<Solution_, Entity_>
implements MoveProvider<Solution_> {
private final PlanningEntityMetaModel<Solution_, Entity_> entityMetaModel;
private final List<PlanningVariableMetaModel<Solution_, Entity_, Object>> variableMetaModelList;
@SuppressWarnings("unchecked")
public SwapMoveProvider(PlanningEntityMetaModel<Solution_, Entity_> entityMetaModel) {
this.entityMetaModel = Objects.requireNonNull(entityMetaModel);
this.variableMetaModelList = entityMetaModel.variables().stream()
.flatMap(v -> {
if (v instanceof PlanningVariableMetaModel<Solution_, Entity_, ?> planningVariableMetaModel) {
return Stream.of((PlanningVariableMetaModel<Solution_, Entity_, Object>) planningVariableMetaModel);
}
return Stream.empty();
})
.toList();
if (variableMetaModelList.isEmpty()) {
throw new IllegalArgumentException("The entityClass (%s) has no basic planning variables."
.formatted(entityMetaModel.type().getCanonicalName()));
}
}
public SwapMoveProvider(List<PlanningVariableMetaModel<Solution_, Entity_, Object>> variableMetaModelList) {
this.variableMetaModelList = Objects.requireNonNull(variableMetaModelList);
var entityMetaModels = variableMetaModelList.stream()
.map(VariableMetaModel::entity)
.distinct()
.toList();
this.entityMetaModel = switch (entityMetaModels.size()) {
case 0 -> throw new IllegalArgumentException("The variableMetaModelList (%s) is empty."
.formatted(variableMetaModelList));
case 1 -> entityMetaModels.get(0);
default -> throw new IllegalArgumentException(
"The variableMetaModelList (%s) contains variables from multiple entity classes."
.formatted(variableMetaModelList));
};
}
@Override
public MoveProducer<Solution_> apply(MoveStreamFactory<Solution_> moveStreamFactory) {
var entityType = entityMetaModel.type();
var dataStream = moveStreamFactory.enumerate(entityType, false)
.join(entityType,
filtering((SolutionView<Solution_> solutionView, Entity_ leftEntity, Entity_ rightEntity) -> {
if (leftEntity == rightEntity) {
return false;
}
var change = false;
for (var variableMetaModel : variableMetaModelList) {
var defaultVariableMetaModel =
(DefaultPlanningVariableMetaModel<Solution_, Entity_, Object>) variableMetaModel;
var variableDescriptor = defaultVariableMetaModel.variableDescriptor();
var oldLeftValue = variableDescriptor.getValue(leftEntity);
var oldRightValue = variableDescriptor.getValue(rightEntity);
if (Objects.equals(oldLeftValue, oldRightValue)) {
continue;
}
if (solutionView.isValueInRange(variableMetaModel, leftEntity, oldRightValue)
&& solutionView.isValueInRange(variableMetaModel, rightEntity, oldLeftValue)) {
change = true;
} else {
// One of the swaps falls out of range, skip this pair altogether.
return false;
}
}
return change;
}))
// Ensure unique pairs; without demanding PlanningId, this becomes tricky.
.map((solutionView, leftEntity, rightEntity) -> new UniquePair<>(leftEntity, rightEntity))
.distinct()
.map((solutionView, pair) -> pair.first(), (solutionView, pair) -> pair.second());
return moveStreamFactory.pick(dataStream)
.asMove((solutionView, leftEntity, rightEntity) -> new SwapMove<>(variableMetaModelList, leftEntity,
rightEntity));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/generic/provider/UniquePair.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.generic.provider;
import java.util.Objects;
/**
* A pair of two entities where (a, b) is considered equal to (b, a).
*/
record UniquePair<Entity_>(Entity_ first, Entity_ second) {
@Override
public boolean equals(Object o) {
return o instanceof UniquePair<?> other &&
((first == other.first && second == other.second) || (first == other.second && second == other.first));
}
@Override
public int hashCode() {
var firstHash = Objects.hashCode(first);
var secondHash = Objects.hashCode(second);
// We always include both hashes, so that the order of first and second does not matter.
// We compute in long to minimize intermediate overflows.
var longHash = (31L * firstHash * secondHash) + firstHash + secondHash;
return Long.hashCode(longHash);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/stream/BiDataStream.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.stream;
import ai.timefold.solver.core.impl.move.streams.maybeapi.BiDataFilter;
import ai.timefold.solver.core.impl.move.streams.maybeapi.BiDataMapper;
import ai.timefold.solver.core.impl.move.streams.maybeapi.UniDataMapper;
import ai.timefold.solver.core.preview.api.move.SolutionView;
import org.jspecify.annotations.NullMarked;
@NullMarked
public interface BiDataStream<Solution_, A, B> extends DataStream<Solution_> {
/**
* Exhaustively test each fact against the {@link BiDataFilter}
* and match if {@link BiDataFilter#test(SolutionView, Object, Object)} returns true.
*/
BiDataStream<Solution_, A, B> filter(BiDataFilter<Solution_, A, B> filter);
// ************************************************************************
// Operations with duplicate tuple possibility
// ************************************************************************
/**
* As defined by {@link UniDataStream#map(UniDataMapper)}.
*
* <p>
* Use with caution,
* as the increased memory allocation rates coming from tuple creation may negatively affect performance.
*
* @param mapping function to convert the original tuple into the new tuple
* @param <ResultA_> the type of the only fact in the resulting {@link UniDataStream}'s tuple
*/
<ResultA_> UniDataStream<Solution_, ResultA_> map(BiDataMapper<Solution_, A, B, ResultA_> mapping);
/**
* As defined by {@link #map(BiDataMapper)}, only resulting in {@link BiDataStream}.
*
* @param mappingA function to convert the original tuple into the first fact of a new tuple
* @param mappingB function to convert the original tuple into the second fact of a new tuple
* @param <ResultA_> the type of the first fact in the resulting {@link BiDataStream}'s tuple
* @param <ResultB_> the type of the first fact in the resulting {@link BiDataStream}'s tuple
*/
<ResultA_, ResultB_> BiDataStream<Solution_, ResultA_, ResultB_> map(BiDataMapper<Solution_, A, B, ResultA_> mappingA,
BiDataMapper<Solution_, A, B, ResultB_> mappingB);
/**
* As defined by {@link UniDataStream#distinct()}.
*/
BiDataStream<Solution_, A, B> distinct();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/stream/BiMoveConstructor.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.stream;
import ai.timefold.solver.core.preview.api.move.Move;
import ai.timefold.solver.core.preview.api.move.SolutionView;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
@FunctionalInterface
public non-sealed interface BiMoveConstructor<Solution_, A, B>
extends MoveConstructor<Solution_> {
Move<Solution_> apply(SolutionView<Solution_> solutionView, @Nullable A a, @Nullable B b);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/stream/BiMoveStream.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.stream;
import org.jspecify.annotations.NullMarked;
@NullMarked
public interface BiMoveStream<Solution_, A, B> extends MoveStream<Solution_> {
MoveProducer<Solution_> asMove(BiMoveConstructor<Solution_, A, B> moveConstructor);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/stream/DataStream.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.stream;
import org.jspecify.annotations.NullMarked;
@NullMarked
public interface DataStream<Solution_> {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/stream/MoveConstructor.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.stream;
import org.jspecify.annotations.NullMarked;
@NullMarked
public sealed interface MoveConstructor<Solution_> permits BiMoveConstructor {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/stream/MoveProducer.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.stream;
import ai.timefold.solver.core.impl.move.streams.MoveIterable;
import org.jspecify.annotations.NullMarked;
@NullMarked
public interface MoveProducer<Solution_> {
MoveIterable<Solution_> getMoveIterable(MoveStreamSession<Solution_> moveStreamSession);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/stream/MoveProvider.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.stream;
import java.util.function.Function;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
/**
* Implement this to provide a definition for one move type.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
@FunctionalInterface
public interface MoveProvider<Solution_>
extends Function<MoveStreamFactory<Solution_>, MoveProducer<Solution_>> {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/stream/MoveProviders.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.stream;
import java.util.List;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningSolutionMetaModel;
public interface MoveProviders<Solution_> {
List<MoveProvider<Solution_>> defineMoves(PlanningSolutionMetaModel<Solution_> solutionMetaModel);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/stream/MoveStream.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.stream;
import org.jspecify.annotations.NullMarked;
@NullMarked
public interface MoveStream<Solution_> {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/stream/MoveStreamFactory.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.stream;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.entity.PlanningPin;
import ai.timefold.solver.core.api.domain.entity.PlanningPinToIndex;
import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
import ai.timefold.solver.core.impl.move.streams.maybeapi.UniDataFilter;
import ai.timefold.solver.core.preview.api.domain.metamodel.GenuineVariableMetaModel;
import org.jspecify.annotations.NullMarked;
@NullMarked
public interface MoveStreamFactory<Solution_> {
/**
* Start a {@link DataStream} of all instances of the sourceClass
* that are known as {@link ProblemFactCollectionProperty problem facts}
* or {@link PlanningEntity planning entities}.
* <p>
* If the sourceClass is a {@link PlanningEntity}, then it is automatically
* {@link UniDataStream#filter(UniDataFilter) filtered} to only contain entities
* which are not pinned.
* <p>
* If the sourceClass is a shadow entity (an entity without any genuine planning variables),
* and if there exists a genuine {@link PlanningEntity} with a {@link PlanningListVariable}
* which accepts instances of this shadow entity as values in that list,
* then this stream will filter out all sourceClass instances
* which are pinned in that list.
* <p>
* This stream returns genuine entities regardless of whether they have any null genuine planning variables.
* This stream returns shadow entities regardless of whether they are assigned to any genuine entity.
* They can easily be {@link UniDataStream#filter(UniDataFilter) filtered out}.
*
* @return A stream containing a tuple for each of the entities as described above.
* @see PlanningPin An annotation to mark the entire entity as pinned.
* @see PlanningPinToIndex An annotation to specify only a portion of {@link PlanningListVariable} is pinned.
* @see #enumerateIncludingPinned(Class, boolean) Specialized method exists to automatically include pinned entities as
* well.
*/
<A> UniDataStream<Solution_, A> enumerate(Class<A> sourceClass, boolean includeNull);
/**
* Start a {@link DataStream} of all instances of the sourceClass
* that are known as {@link ProblemFactCollectionProperty problem facts}
* or {@link PlanningEntity planning entities}.
* If the sourceClass is a genuine or shadow entity,
* it returns instances regardless of their pinning status.
* Otherwise as defined by {@link #enumerate(Class, boolean)}.
*/
<A> UniDataStream<Solution_, A> enumerateIncludingPinned(Class<A> sourceClass, boolean includeNull);
/**
* Enumerate possible values for any given entity,
* where entities are obtained using {@link #enumerate(Class, boolean)},
* with the class matching the entity type of the variable.
* If the variable allows unassigned values, the resulting stream will include a null value.
*
* @param variableMetaModel the meta model of the variable to enumerate
* @return data stream with all possible values of a given variable
*/
default <Entity_, Value_> BiDataStream<Solution_, Entity_, Value_> enumerateEntityValuePairs(
GenuineVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel) {
return enumerateEntityValuePairs(variableMetaModel, enumerate(variableMetaModel.entity().type(), false));
}
/**
* Enumerate possible values for any given entity.
* If the variable allows unassigned values, the resulting stream will include a null value.
*
* @param variableMetaModel the meta model of the variable to enumerate
* @param entityDataStream the data stream of entities to enumerate values for
* @return data stream with all possible values of a given variable
*/
<Entity_, Value_> BiDataStream<Solution_, Entity_, Value_> enumerateEntityValuePairs(
GenuineVariableMetaModel<Solution_, Entity_, Value_> variableMetaModel,
UniDataStream<Solution_, Entity_> entityDataStream);
default <A> UniMoveStream<Solution_, A> pick(Class<A> clz) {
return pick(enumerate(clz, false));
}
<A> UniMoveStream<Solution_, A> pick(UniDataStream<Solution_, A> dataStream);
<A, B> BiMoveStream<Solution_, A, B> pick(BiDataStream<Solution_, A, B> dataStream);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/stream/MoveStreamSession.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.stream;
import org.jspecify.annotations.NullMarked;
@NullMarked
public interface MoveStreamSession<Solution_> {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/stream/UniDataStream.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.stream;
import static ai.timefold.solver.core.impl.util.ConstantLambdaUtils.notEqualsForDataStreams;
import java.util.Arrays;
import java.util.stream.Stream;
import ai.timefold.solver.core.impl.move.streams.maybeapi.BiDataFilter;
import ai.timefold.solver.core.impl.move.streams.maybeapi.BiDataJoiner;
import ai.timefold.solver.core.impl.move.streams.maybeapi.DataJoiners;
import ai.timefold.solver.core.impl.move.streams.maybeapi.UniDataFilter;
import ai.timefold.solver.core.impl.move.streams.maybeapi.UniDataMapper;
import ai.timefold.solver.core.preview.api.move.SolutionView;
import org.jspecify.annotations.NullMarked;
@NullMarked
public interface UniDataStream<Solution_, A> extends DataStream<Solution_> {
/**
* Exhaustively test each fact against the {@link UniDataFilter}
* and match if {@link UniDataFilter#test(SolutionView, Object)} returns true.
*/
UniDataStream<Solution_, A> filter(UniDataFilter<Solution_, A> filter);
/**
* Create a new {@link BiDataStream} for every combination of A and B for which the {@link BiDataJoiner}
* is true (for the properties it extracts from both facts).
* <p>
* Important: Joining is faster and more scalable than a {@link BiDataStream#filter(BiDataFilter) filter},
* because it applies hashing and/or indexing on the properties,
* so it doesn't create nor checks every combination of A and B.
*
* @param <B> the type of the second matched fact
* @return a stream that matches every combination of A and B for which the {@link BiDataJoiner} is true
*/
<B> BiDataStream<Solution_, A, B> join(UniDataStream<Solution_, B> otherStream, BiDataJoiner<A, B>... joiners);
/**
* Create a new {@link BiDataStream} for every combination of A and B
* for which the {@link BiDataJoiner} is true (for the properties it extracts from both facts).
* The stream will include all facts or entities of the given class,
* regardless of their pinning status.
* <p>
* Important: Joining is faster and more scalable than a {@link BiDataStream#filter(BiDataFilter) filter},
* because it applies hashing and/or indexing on the properties,
* so it doesn't create nor checks every combination of A and B.
*
* @param <B> the type of the second matched fact
* @return a stream that matches every combination of A and B for which the {@link BiDataJoiner} is true
*/
<B> BiDataStream<Solution_, A, B> join(Class<B> otherClass, BiDataJoiner<A, B>... joiners);
/**
* Create a new {@link UniDataStream} for every A where B exists for which all {@link BiDataJoiner}s are true
* (for the properties they extract from both facts).
*
* @param <B> the type of the second matched fact
* @return a stream that matches every A where B exists for which the {@link BiDataJoiner}s are true
*/
@SuppressWarnings("unchecked")
<B> UniDataStream<Solution_, A> ifExists(Class<B> otherClass, BiDataJoiner<A, B>... joiners);
/**
* Create a new {@link UniDataStream} for every A where B exists for which all {@link BiDataJoiner}s are true
* (for the properties it extracts from both facts).
*
* @param <B> the type of the second matched fact
* @return a stream that matches every A where B exists for which the {@link BiDataJoiner}s are true
*/
@SuppressWarnings("unchecked")
<B> UniDataStream<Solution_, A> ifExists(UniDataStream<Solution_, B> otherStream, BiDataJoiner<A, B>... joiners);
/**
* Create a new {@link UniDataStream} for every A, if another A exists that does not {@link Object#equals(Object)}
* the first, and for which the {@link BiDataJoiner}s are true (for the properties they extract from both facts).
*
* @return a stream that matches every A where a different A exists for which the {@link BiDataJoiner}s are true
*/
@SuppressWarnings("unchecked")
default UniDataStream<Solution_, A> ifExistsOther(Class<A> otherClass, BiDataJoiner<A, A>... joiners) {
BiDataJoiner<A, A> otherness = DataJoiners.filtering(notEqualsForDataStreams());
@SuppressWarnings("unchecked")
BiDataJoiner<A, A>[] allJoiners = Stream.concat(Arrays.stream(joiners), Stream.of(otherness))
.toArray(BiDataJoiner[]::new);
return ifExists(otherClass, allJoiners);
}
/**
* Create a new {@link UniDataStream} for every A where B does not exist for which the {@link BiDataJoiner}s are true
* (for the properties they extract from both facts).
*
* @param <B> the type of the second matched fact
* @return a stream that matches every A where B does not exist for which the {@link BiDataJoiner}s are true
*/
@SuppressWarnings("unchecked")
<B> UniDataStream<Solution_, A> ifNotExists(Class<B> otherClass, BiDataJoiner<A, B>... joiners);
/**
* Create a new {@link UniDataStream} for every A where B does not exist for which the {@link BiDataJoiner}s are true
* (for the properties they extract from both facts).
*
* @param <B> the type of the second matched fact
* @return a stream that matches every A where B does not exist for which the {@link BiDataJoiner}s are true
*/
@SuppressWarnings("unchecked")
<B> UniDataStream<Solution_, A> ifNotExists(UniDataStream<Solution_, B> otherStream, BiDataJoiner<A, B>... joiners);
/**
* Create a new {@link UniDataStream} for every A, if no other A exists that does not {@link Object#equals(Object)}
* the first,
* for which the {@link BiDataJoiner}s are true (for the properties they extract from both facts).
*
* @return a stream that matches every A where a different A does not exist
*/
@SuppressWarnings("unchecked")
default UniDataStream<Solution_, A> ifNotExistsOther(Class<A> otherClass, BiDataJoiner<A, A>... joiners) {
BiDataJoiner<A, A> otherness = DataJoiners.filtering(notEqualsForDataStreams());
@SuppressWarnings("unchecked")
BiDataJoiner<A, A>[] allJoiners = Stream.concat(Arrays.stream(joiners), Stream.of(otherness))
.toArray(BiDataJoiner[]::new);
return ifNotExists(otherClass, allJoiners);
}
// ************************************************************************
// Operations with duplicate tuple possibility
// ************************************************************************
/**
* Transforms the stream in such a way that tuples are remapped using the given function.
* This may produce a stream with duplicate tuples.
* See {@link #distinct()} for details.
* <p>
* There are several recommendations for implementing the mapping function:
*
* <ul>
* <li>Purity.
* The mapping function should only depend on its input.
* That is, given the same input, it always returns the same output.</li>
* <li>Bijectivity.
* No two input tuples should map to the same output tuple,
* or to tuples that are {@link Object#equals(Object) equal}.
* Not following this recommendation creates a data stream with duplicate tuples,
* and may force you to use {@link #distinct()} later, which comes at a performance cost.</li>
* <li>Immutable data carriers.
* The objects returned by the mapping function should be identified by their contents and nothing else.
* If two of them have contents which {@link Object#equals(Object) equal},
* then they should likewise {@link Object#equals(Object) equal} and preferably be the same instance.
* The objects returned by the mapping function should also be immutable,
* meaning their contents should not be allowed to change.</li>
* </ul>
*
* <p>
* Simple example: assuming a data stream of tuples of {@code Person}s
* {@code [Ann(age = 20), Beth(age = 25), Cathy(age = 30)]},
* calling {@code map(Person::getAge)} on such stream will produce a stream of {@link Integer}s
* {@code [20, 25, 30]},
*
* <p>
* Example with a non-bijective mapping function: assuming a data stream of tuples of {@code Person}s
* {@code [Ann(age = 20), Beth(age = 25), Cathy(age = 30), David(age = 30), Eric(age = 20)]},
* calling {@code map(Person::getAge)} on such stream will produce a stream of {@link Integer}s
* {@code [20, 25, 30, 30, 20]}.
*
* <p>
* Use with caution,
* as the increased memory allocation rates coming from tuple creation may negatively affect performance.
*
* @param mapping function to convert the original tuple into the new tuple
* @param <ResultA_> the type of the only fact in the resulting {@link UniDataStream}'s tuple
*/
<ResultA_> UniDataStream<Solution_, ResultA_> map(UniDataMapper<Solution_, A, ResultA_> mapping);
/**
* As defined by {@link #map(UniDataMapper)}, only resulting in {@link BiDataStream}.
*
* @param mappingA function to convert the original tuple into the first fact of a new tuple
* @param mappingB function to convert the original tuple into the second fact of a new tuple
* @param <ResultA_> the type of the first fact in the resulting {@link BiDataStream}'s tuple
* @param <ResultB_> the type of the first fact in the resulting {@link BiDataStream}'s tuple
*/
<ResultA_, ResultB_> BiDataStream<Solution_, ResultA_, ResultB_> map(UniDataMapper<Solution_, A, ResultA_> mappingA,
UniDataMapper<Solution_, A, ResultB_> mappingB);
/**
* Transforms the stream in such a way that all the tuples going through it are distinct.
* (No two tuples will {@link Object#equals(Object) equal}.)
*
* <p>
* By default, tuples going through a data stream are distinct.
* However, operations such as {@link #map(UniDataMapper)} may create a stream which breaks that promise.
* By calling this method on such a stream,
* duplicate copies of the same tuple will be omitted at a performance cost.
*/
UniDataStream<Solution_, A> distinct();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/move/streams/maybeapi/stream/UniMoveStream.java | package ai.timefold.solver.core.impl.move.streams.maybeapi.stream;
import java.util.function.BiPredicate;
import org.jspecify.annotations.NullMarked;
@NullMarked
public interface UniMoveStream<Solution_, A> extends MoveStream<Solution_> {
default <B> BiMoveStream<Solution_, A, B> pick(UniDataStream<Solution_, B> uniDataStream) {
return pick(uniDataStream, (a, b) -> true);
}
<B> BiMoveStream<Solution_, A, B> pick(UniDataStream<Solution_, B> uniDataStream, BiPredicate<A, B> filter);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/partitionedsearch/DefaultPartitionedSearchPhaseFactory.java | package ai.timefold.solver.core.impl.partitionedsearch;
import ai.timefold.solver.core.config.partitionedsearch.PartitionedSearchPhaseConfig;
import ai.timefold.solver.core.enterprise.TimefoldSolverEnterpriseService;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.phase.AbstractPhaseFactory;
import ai.timefold.solver.core.impl.solver.recaller.BestSolutionRecaller;
import ai.timefold.solver.core.impl.solver.termination.SolverTermination;
public class DefaultPartitionedSearchPhaseFactory<Solution_>
extends AbstractPhaseFactory<Solution_, PartitionedSearchPhaseConfig> {
public DefaultPartitionedSearchPhaseFactory(PartitionedSearchPhaseConfig phaseConfig) {
super(phaseConfig);
}
@Override
public PartitionedSearchPhase<Solution_> buildPhase(int phaseIndex, boolean lastInitializingPhase,
HeuristicConfigPolicy<Solution_> solverConfigPolicy, BestSolutionRecaller<Solution_> bestSolutionRecaller,
SolverTermination<Solution_> solverTermination) {
return TimefoldSolverEnterpriseService.loadOrFail(TimefoldSolverEnterpriseService.Feature.PARTITIONED_SEARCH)
.buildPartitionedSearch(phaseIndex, phaseConfig, solverConfigPolicy, solverTermination,
this::buildPhaseTermination);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/partitionedsearch/PartitionedSearchPhase.java | package ai.timefold.solver.core.impl.partitionedsearch;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.phase.AbstractPhase;
import ai.timefold.solver.core.impl.phase.Phase;
/**
* A {@link PartitionedSearchPhase} is a {@link Phase} which uses a Partition Search algorithm.
* It splits the {@link PlanningSolution} into pieces and solves those separately with other {@link Phase}s.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @see Phase
* @see AbstractPhase
*/
public interface PartitionedSearchPhase<Solution_> extends Phase<Solution_> {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/partitionedsearch | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/partitionedsearch/partitioner/SolutionPartitioner.java | package ai.timefold.solver.core.impl.partitionedsearch.partitioner;
import java.util.List;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
/**
* Splits one {@link PlanningSolution solution} into multiple partitions.
* The partitions are solved and merged based on the {@link PlanningSolution#lookUpStrategyType()}.
* <p>
* To add custom properties, configure custom properties and add public setters for them.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public interface SolutionPartitioner<Solution_> {
/**
* Returns a list of partition cloned {@link PlanningSolution solutions}
* for which each {@link PlanningEntity planning entity}
* is partition cloned into exactly 1 of those partitions.
* Problem facts can be multiple partitions (with our without cloning).
* <p>
* Any class that is {@link SolutionCloner solution cloned} must also be partitioned cloned.
* A class can be partition cloned without being solution cloned.
*
* @param scoreDirector never null, the {@link ScoreDirector}
* which has the {@link ScoreDirector#getWorkingSolution()} that needs to be split up
* @param runnablePartThreadLimit null if unlimited, never negative
* @return never null, {@link List#size()} of at least 1.
*/
List<Solution_> splitWorkingSolution(ScoreDirector<Solution_> scoreDirector, Integer runnablePartThreadLimit);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/AbstractPhase.java | package ai.timefold.solver.core.impl.phase;
import java.util.Map;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
import ai.timefold.solver.core.config.solver.monitoring.SolverMetric;
import ai.timefold.solver.core.impl.localsearch.DefaultLocalSearchPhase;
import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleListener;
import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleSupport;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
import ai.timefold.solver.core.impl.solver.exception.ScoreCorruptionException;
import ai.timefold.solver.core.impl.solver.exception.VariableCorruptionException;
import ai.timefold.solver.core.impl.solver.monitoring.ScoreLevels;
import ai.timefold.solver.core.impl.solver.monitoring.SolverMetricUtil;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.termination.PhaseTermination;
import ai.timefold.solver.core.impl.solver.termination.Termination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.micrometer.core.instrument.Tags;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @see DefaultLocalSearchPhase
*/
public abstract class AbstractPhase<Solution_> implements Phase<Solution_> {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected final int phaseIndex;
protected final String logIndentation;
// Called "phaseTermination" to clearly distinguish from "solverTermination" inside AbstractSolver.
protected final PhaseTermination<Solution_> phaseTermination;
protected final boolean assertPhaseScoreFromScratch;
protected final boolean assertStepScoreFromScratch;
protected final boolean assertExpectedStepScore;
protected final boolean assertShadowVariablesAreNotStaleAfterStep;
/** Used for {@link #addPhaseLifecycleListener(PhaseLifecycleListener)}. */
protected PhaseLifecycleSupport<Solution_> phaseLifecycleSupport = new PhaseLifecycleSupport<>();
protected AbstractPhase(AbstractPhaseBuilder<Solution_> builder) {
phaseIndex = builder.phaseIndex;
logIndentation = builder.logIndentation;
phaseTermination = builder.phaseTermination;
assertPhaseScoreFromScratch = builder.assertPhaseScoreFromScratch;
assertStepScoreFromScratch = builder.assertStepScoreFromScratch;
assertExpectedStepScore = builder.assertExpectedStepScore;
assertShadowVariablesAreNotStaleAfterStep = builder.assertShadowVariablesAreNotStaleAfterStep;
}
public int getPhaseIndex() {
return phaseIndex;
}
public Termination<Solution_> getPhaseTermination() {
return phaseTermination;
}
public boolean isAssertStepScoreFromScratch() {
return assertStepScoreFromScratch;
}
public boolean isAssertExpectedStepScore() {
return assertExpectedStepScore;
}
public boolean isAssertShadowVariablesAreNotStaleAfterStep() {
return assertShadowVariablesAreNotStaleAfterStep;
}
public abstract String getPhaseTypeString();
// ************************************************************************
// Lifecycle methods
// ************************************************************************
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
phaseLifecycleSupport.fireSolvingStarted(solverScope);
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
phaseLifecycleSupport.fireSolvingEnded(solverScope);
}
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
phaseScope.startingNow();
phaseScope.reset();
if (!isNested()) {
var solver = phaseScope.getSolverScope().getSolver();
solver.phaseStarted(phaseScope);
}
phaseTermination.phaseStarted(phaseScope);
phaseScope.setTermination(phaseTermination);
phaseLifecycleSupport.firePhaseStarted(phaseScope);
}
/**
* Whether this phase is nested inside another phase.
* Nested phases, such as ruin and recreate, must not notify the solver of their starting;
* otherwise unimproved termination of local search would be reset every time the nested phase starts,
* effectively disabling this termination.
* Nested phases also do not collect step and phase metrics.
*
* @return false for nested phases, true for every other phase
*/
protected boolean isNested() {
return false;
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
if (!isNested()) {
var solver = phaseScope.getSolverScope().getSolver();
solver.phaseEnded(phaseScope);
}
phaseTermination.phaseEnded(phaseScope);
phaseLifecycleSupport.firePhaseEnded(phaseScope);
if (assertPhaseScoreFromScratch) {
var score = phaseScope.getSolverScope().calculateScore();
try {
phaseScope.assertWorkingScoreFromScratch(score, getPhaseTypeString() + " phase ended");
} catch (ScoreCorruptionException | VariableCorruptionException e) {
throw new IllegalStateException("""
Solver corruption was detected. Solutions provided by this solver can not be trusted.
Corruptions typically arise from a bug in either your constraints or your variable listeners,
but they may also be caused by a rare solver bug.
Run your solver with %s %s to find out more information about the error \
and if you are convinced that the problem is not in your code, please report a bug to Timefold.
At your own risk, you may run your solver with %s or %s instead to ignore this error."""
.formatted(EnvironmentMode.class.getSimpleName(),
EnvironmentMode.FULL_ASSERT, EnvironmentMode.NO_ASSERT,
EnvironmentMode.NON_REPRODUCIBLE),
e);
}
}
}
@Override
public void stepStarted(AbstractStepScope<Solution_> stepScope) {
if (!isNested()) {
var solver = stepScope.getPhaseScope().getSolverScope().getSolver();
solver.stepStarted(stepScope);
}
phaseTermination.stepStarted(stepScope);
phaseLifecycleSupport.fireStepStarted(stepScope);
}
protected void calculateWorkingStepScore(AbstractStepScope<Solution_> stepScope, Object completedAction) {
AbstractPhaseScope<Solution_> phaseScope = stepScope.getPhaseScope();
var score = phaseScope.calculateScore();
stepScope.setScore(score);
if (assertStepScoreFromScratch) {
phaseScope.assertWorkingScoreFromScratch(score, completedAction);
}
if (assertShadowVariablesAreNotStaleAfterStep) {
phaseScope.assertShadowVariablesAreNotStale(score, completedAction);
}
}
protected <Score_ extends Score<Score_>> void predictWorkingStepScore(AbstractStepScope<Solution_> stepScope,
Object completedAction) {
var phaseScope = stepScope.getPhaseScope();
// There is no need to recalculate the score, but we still need to set it
phaseScope.getSolutionDescriptor().setScore(phaseScope.getWorkingSolution(),
stepScope.<Score_> getScore().raw());
if (assertStepScoreFromScratch) {
phaseScope.<Score_> assertPredictedScoreFromScratch(stepScope.getScore(), completedAction);
}
if (assertExpectedStepScore) {
phaseScope.<Score_> assertExpectedWorkingScore(stepScope.getScore(), completedAction);
}
if (assertShadowVariablesAreNotStaleAfterStep) {
phaseScope.<Score_> assertShadowVariablesAreNotStale(stepScope.getScore(), completedAction);
}
}
@Override
public void stepEnded(AbstractStepScope<Solution_> stepScope) {
if (!isNested()) {
var solver = stepScope.getPhaseScope().getSolverScope().getSolver();
solver.stepEnded(stepScope);
collectMetrics(stepScope);
}
phaseTermination.stepEnded(stepScope);
phaseLifecycleSupport.fireStepEnded(stepScope);
}
private static <Solution_> void collectMetrics(AbstractStepScope<Solution_> stepScope) {
var solverScope = stepScope.getPhaseScope().getSolverScope();
if (solverScope.isMetricEnabled(SolverMetric.STEP_SCORE) && stepScope.getScore().isFullyAssigned()) {
Tags tags = solverScope.getMonitoringTags();
ScoreDefinition<?> scoreDefinition = solverScope.getScoreDefinition();
Map<Tags, ScoreLevels> tagToScoreLevels = solverScope.getStepScoreMap();
SolverMetricUtil.registerScore(SolverMetric.STEP_SCORE, tags, scoreDefinition, tagToScoreLevels,
stepScope.getScore());
}
}
@Override
public void addPhaseLifecycleListener(PhaseLifecycleListener<Solution_> phaseLifecycleListener) {
phaseLifecycleSupport.addEventListener(phaseLifecycleListener);
}
@Override
public void removePhaseLifecycleListener(PhaseLifecycleListener<Solution_> phaseLifecycleListener) {
phaseLifecycleSupport.removeEventListener(phaseLifecycleListener);
}
// ************************************************************************
// Assert methods
// ************************************************************************
protected void assertWorkingSolutionInitialized(AbstractPhaseScope<Solution_> phaseScope) {
if (!phaseScope.getStartingScore().isFullyAssigned()) {
var scoreDirector = phaseScope.getScoreDirector();
var solutionDescriptor = scoreDirector.getSolutionDescriptor();
var initializationStatistics = scoreDirector.getValueRangeManager().getInitializationStatistics();
var uninitializedEntityCount = initializationStatistics.uninitializedEntityCount();
if (uninitializedEntityCount > 0) {
throw new IllegalStateException(
"""
%s phase (%d) needs to start from an initialized solution, but there are (%d) uninitialized entities.
Maybe there is no Construction Heuristic configured before this phase to initialize the solution.
Or maybe the getter/setters of your planning variables in your domain classes aren't implemented correctly."""
.formatted(getPhaseTypeString(), phaseIndex, uninitializedEntityCount));
}
var unassignedValueCount = initializationStatistics.unassignedValueCount();
if (unassignedValueCount > 0) {
throw new IllegalStateException(
"""
%s phase (%d) needs to start from an initialized solution, \
but planning list variable (%s) has (%d) unexpected unassigned values.
Maybe there is no Construction Heuristic configured before this phase to initialize the solution."""
.formatted(getPhaseTypeString(), phaseIndex, solutionDescriptor.getListVariableDescriptor(),
unassignedValueCount));
}
}
}
public abstract static class AbstractPhaseBuilder<Solution_> {
private final int phaseIndex;
private final String logIndentation;
private final PhaseTermination<Solution_> phaseTermination;
private boolean assertPhaseScoreFromScratch = false;
private boolean assertStepScoreFromScratch = false;
private boolean assertExpectedStepScore = false;
private boolean assertShadowVariablesAreNotStaleAfterStep = false;
protected AbstractPhaseBuilder(int phaseIndex, String logIndentation, PhaseTermination<Solution_> phaseTermination) {
this.phaseIndex = phaseIndex;
this.logIndentation = logIndentation;
this.phaseTermination = phaseTermination;
}
public AbstractPhaseBuilder<Solution_> enableAssertions(EnvironmentMode environmentMode) {
assertPhaseScoreFromScratch = environmentMode.isAsserted();
assertStepScoreFromScratch = environmentMode.isFullyAsserted();
assertExpectedStepScore = environmentMode.isIntrusivelyAsserted();
assertShadowVariablesAreNotStaleAfterStep = environmentMode.isIntrusivelyAsserted();
return this;
}
protected abstract AbstractPhase<Solution_> build();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/AbstractPhaseFactory.java | package ai.timefold.solver.core.impl.phase;
import java.util.Collections;
import java.util.Objects;
import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig;
import ai.timefold.solver.core.config.exhaustivesearch.ExhaustiveSearchPhaseConfig;
import ai.timefold.solver.core.config.localsearch.LocalSearchPhaseConfig;
import ai.timefold.solver.core.config.partitionedsearch.PartitionedSearchPhaseConfig;
import ai.timefold.solver.core.config.phase.PhaseConfig;
import ai.timefold.solver.core.config.phase.custom.CustomPhaseConfig;
import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicPhaseScope;
import ai.timefold.solver.core.impl.exhaustivesearch.scope.ExhaustiveSearchPhaseScope;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope;
import ai.timefold.solver.core.impl.phase.custom.scope.CustomPhaseScope;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.solver.termination.PhaseTermination;
import ai.timefold.solver.core.impl.solver.termination.SolverTermination;
import ai.timefold.solver.core.impl.solver.termination.TerminationFactory;
import ai.timefold.solver.core.impl.solver.termination.UniversalTermination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractPhaseFactory<Solution_, PhaseConfig_ extends PhaseConfig<PhaseConfig_>>
implements PhaseFactory<Solution_> {
protected final Logger logger = LoggerFactory.getLogger(getClass());
protected final PhaseConfig_ phaseConfig;
public AbstractPhaseFactory(PhaseConfig_ phaseConfig) {
this.phaseConfig = phaseConfig;
}
protected PhaseTermination<Solution_> buildPhaseTermination(HeuristicConfigPolicy<Solution_> configPolicy,
SolverTermination<Solution_> solverTermination) {
var terminationConfig_ = Objects.requireNonNullElseGet(phaseConfig.getTerminationConfig(), TerminationConfig::new);
var phaseTermination = PhaseTermination.bridge(solverTermination);
var resultingTermination = TerminationFactory.<Solution_> create(terminationConfig_)
.buildTermination(configPolicy, phaseTermination);
var inapplicableTerminationList = !(this instanceof NoChangePhaseFactory<?>) &&
resultingTermination instanceof UniversalTermination<Solution_> universalTermination
? universalTermination.getPhaseTerminationsInapplicableTo(getPhaseScopeClass())
: Collections.emptyList();
var phaseName = this.getClass().getSimpleName()
.replace("PhaseFactory", "")
.replace("Default", "");
if (solverTermination != resultingTermination) {
// Only fail if the user put the inapplicable termination on the phase, not on the solver.
// On the solver level, inapplicable phase terminations are skipped.
// Otherwise you would only be able to configure a global phase-level termination on the solver
// if it was applicable to all phases.
if (!inapplicableTerminationList.isEmpty()) {
throw new IllegalStateException(
"""
The phase (%s) configured with terminations (%s) includes some terminations which are not applicable to it (%s).
Maybe remove these terminations from the phase's configuration."""
.formatted(phaseName, phaseTermination, inapplicableTerminationList));
}
} else if (!inapplicableTerminationList.isEmpty()) {
logger.trace("""
The solver-level termination ({}) includes phase-level terminations ({}) \
which are not applicable to the phase ({}).
These phase-level terminations will not take effect in this phase.""",
solverTermination, inapplicableTerminationList, phaseName);
}
return resultingTermination;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private Class<? extends AbstractPhaseScope> getPhaseScopeClass() {
if (phaseConfig instanceof ConstructionHeuristicPhaseConfig) {
return ConstructionHeuristicPhaseScope.class;
} else if (phaseConfig instanceof CustomPhaseConfig) {
return CustomPhaseScope.class;
} else if (phaseConfig instanceof LocalSearchPhaseConfig) {
return LocalSearchPhaseScope.class;
} else if (phaseConfig instanceof ExhaustiveSearchPhaseConfig) {
return ExhaustiveSearchPhaseScope.class;
} else if (phaseConfig instanceof PartitionedSearchPhaseConfig) {
try {
return (Class<? extends AbstractPhaseScope>) Class
.forName("ai.timefold.solver.enterprise.core.partitioned.PartitionedSearchPhaseScope");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("""
The class (%s) is not found.
Make sure Timefold Solver Enterprise Edition is on the classpath, or disable partitioned search.
"""
.formatted("ai.timefold.solver.enterprise.core.partitioned.PartitionedSearchPhaseScope"));
}
} else {
throw new IllegalStateException("Unsupported phaseConfig class: %s".formatted(phaseConfig.getClass()));
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/AbstractPossiblyInitializingPhase.java | package ai.timefold.solver.core.impl.phase;
import ai.timefold.solver.core.impl.phase.custom.CustomPhase;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.solver.termination.PhaseTermination;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
public abstract class AbstractPossiblyInitializingPhase<Solution_>
extends AbstractPhase<Solution_>
implements PossiblyInitializingPhase<Solution_> {
private final boolean lastInitializingPhase;
protected AbstractPossiblyInitializingPhase(AbstractPossiblyInitializingPhaseBuilder<Solution_> builder) {
super(builder);
this.lastInitializingPhase = builder.isLastInitializingPhase();
}
@Override
public final boolean isLastInitializingPhase() {
return lastInitializingPhase;
}
protected static TerminationStatus translateEarlyTermination(AbstractPhaseScope<?> phaseScope,
@Nullable TerminationStatus earlyTerminationStatus, boolean hasMoreSteps) {
if (earlyTerminationStatus == null || !hasMoreSteps) {
// We need to set the termination status to indicate that the phase has ended successfully.
// This happens in two situations:
// 1. The phase is over, and early termination did not happen.
// 2. Early termination happened at the end of the last step, meaning a success anyway.
// This happens when BestScore termination is set to the same score that the last step ends with.
return TerminationStatus.regular(phaseScope.getNextStepIndex());
} else {
return earlyTerminationStatus;
}
}
protected void ensureCorrectTermination(AbstractPhaseScope<Solution_> phaseScope, Logger logger) {
var terminationStatus = getTerminationStatus();
if (!terminationStatus.terminated()) {
throw new IllegalStateException("Impossible state: construction heuristic phase (%d) ended, but not terminated."
.formatted(phaseScope.getPhaseIndex()));
} else if (terminationStatus.early()) {
var advice = this instanceof CustomPhase<?>
? "If the phase was used to initialize the solution, the solution may not be fully initialized."
: "The solution may not be fully initialized.";
logger.warn("""
{} terminated early with step count ({}).
{}""",
this.getClass().getSimpleName(), terminationStatus.stepCount(), advice);
}
}
public static abstract class AbstractPossiblyInitializingPhaseBuilder<Solution_>
extends AbstractPhaseBuilder<Solution_> {
private final boolean lastInitializingPhase;
protected AbstractPossiblyInitializingPhaseBuilder(int phaseIndex, boolean lastInitializingPhase, String phaseName,
PhaseTermination<Solution_> phaseTermination) {
super(phaseIndex, phaseName, phaseTermination);
this.lastInitializingPhase = lastInitializingPhase;
}
public boolean isLastInitializingPhase() {
return lastInitializingPhase;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/NoChangePhase.java | package ai.timefold.solver.core.impl.phase;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.termination.PhaseTermination;
/**
* A {@link NoChangePhase} is a {@link Phase} which does nothing.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @deprecated Deprecated on account of having no use.
*/
@Deprecated(forRemoval = true, since = "1.20.0")
public class NoChangePhase<Solution_> extends AbstractPhase<Solution_> {
private NoChangePhase(Builder<Solution_> builder) {
super(builder);
}
@Override
public String getPhaseTypeString() {
return "No Change";
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void solve(SolverScope<Solution_> solverScope) {
logger.info("{}No Change phase ({}) ended.",
logIndentation,
phaseIndex);
}
public static class Builder<Solution_> extends AbstractPhaseBuilder<Solution_> {
public Builder(int phaseIndex, String logIndentation, PhaseTermination<Solution_> phaseTermination) {
super(phaseIndex, logIndentation, phaseTermination);
}
@Override
public NoChangePhase<Solution_> build() {
return new NoChangePhase<>(this);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/NoChangePhaseFactory.java | package ai.timefold.solver.core.impl.phase;
import ai.timefold.solver.core.config.phase.NoChangePhaseConfig;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.solver.recaller.BestSolutionRecaller;
import ai.timefold.solver.core.impl.solver.termination.SolverTermination;
/**
*
* @param <Solution_>
* @deprecated Deprecated on account of deprecating {@link NoChangePhase}.
*/
@Deprecated(forRemoval = true, since = "1.20.0")
public class NoChangePhaseFactory<Solution_> extends AbstractPhaseFactory<Solution_, NoChangePhaseConfig> {
public NoChangePhaseFactory(NoChangePhaseConfig phaseConfig) {
super(phaseConfig);
}
@Override
public NoChangePhase<Solution_> buildPhase(int phaseIndex, boolean lastInitializingPhase,
HeuristicConfigPolicy<Solution_> solverConfigPolicy, BestSolutionRecaller<Solution_> bestSolutionRecaller,
SolverTermination<Solution_> solverTermination) {
HeuristicConfigPolicy<Solution_> phaseConfigPolicy = solverConfigPolicy.createPhaseConfigPolicy();
return new NoChangePhase.Builder<>(phaseIndex, solverConfigPolicy.getLogIndentation(),
buildPhaseTermination(phaseConfigPolicy, solverTermination)).build();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/Phase.java | package ai.timefold.solver.core.impl.phase;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleListener;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
import ai.timefold.solver.core.impl.solver.DefaultSolver;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
/**
* A phase of a {@link Solver}.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @see AbstractPhase
*/
public interface Phase<Solution_> extends PhaseLifecycleListener<Solution_> {
/**
* Add a {@link PhaseLifecycleListener} that is only notified
* of the {@link PhaseLifecycleListener#phaseStarted(AbstractPhaseScope) phase}
* and the {@link PhaseLifecycleListener#stepStarted(AbstractStepScope) step} starting/ending events from this phase
* (and the {@link PhaseLifecycleListener#solvingStarted(SolverScope) solving} events too of course).
* <p>
* To get notified for all phases, use {@link DefaultSolver#addPhaseLifecycleListener(PhaseLifecycleListener)} instead.
*
* @param phaseLifecycleListener never null
*/
void addPhaseLifecycleListener(PhaseLifecycleListener<Solution_> phaseLifecycleListener);
/**
* @param phaseLifecycleListener never null
* @see #addPhaseLifecycleListener(PhaseLifecycleListener)
*/
void removePhaseLifecycleListener(PhaseLifecycleListener<Solution_> phaseLifecycleListener);
void solve(SolverScope<Solution_> solverScope);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/PhaseFactory.java | package ai.timefold.solver.core.impl.phase;
import java.util.ArrayList;
import java.util.List;
import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig;
import ai.timefold.solver.core.config.constructionheuristic.placer.QueuedEntityPlacerConfig;
import ai.timefold.solver.core.config.exhaustivesearch.ExhaustiveSearchPhaseConfig;
import ai.timefold.solver.core.config.localsearch.LocalSearchPhaseConfig;
import ai.timefold.solver.core.config.partitionedsearch.PartitionedSearchPhaseConfig;
import ai.timefold.solver.core.config.phase.NoChangePhaseConfig;
import ai.timefold.solver.core.config.phase.PhaseConfig;
import ai.timefold.solver.core.config.phase.custom.CustomPhaseConfig;
import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
import ai.timefold.solver.core.impl.constructionheuristic.DefaultConstructionHeuristicPhaseFactory;
import ai.timefold.solver.core.impl.exhaustivesearch.DefaultExhaustiveSearchPhaseFactory;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.localsearch.DefaultLocalSearchPhaseFactory;
import ai.timefold.solver.core.impl.partitionedsearch.DefaultPartitionedSearchPhaseFactory;
import ai.timefold.solver.core.impl.phase.custom.DefaultCustomPhaseFactory;
import ai.timefold.solver.core.impl.solver.recaller.BestSolutionRecaller;
import ai.timefold.solver.core.impl.solver.termination.SolverTermination;
public interface PhaseFactory<Solution_> {
static <Solution_> PhaseFactory<Solution_> create(PhaseConfig<?> phaseConfig) {
if (LocalSearchPhaseConfig.class.isAssignableFrom(phaseConfig.getClass())) {
return new DefaultLocalSearchPhaseFactory<>((LocalSearchPhaseConfig) phaseConfig);
} else if (ConstructionHeuristicPhaseConfig.class.isAssignableFrom(phaseConfig.getClass())) {
return new DefaultConstructionHeuristicPhaseFactory<>((ConstructionHeuristicPhaseConfig) phaseConfig);
} else if (PartitionedSearchPhaseConfig.class.isAssignableFrom(phaseConfig.getClass())) {
return new DefaultPartitionedSearchPhaseFactory<>((PartitionedSearchPhaseConfig) phaseConfig);
} else if (CustomPhaseConfig.class.isAssignableFrom(phaseConfig.getClass())) {
return new DefaultCustomPhaseFactory<>((CustomPhaseConfig) phaseConfig);
} else if (ExhaustiveSearchPhaseConfig.class.isAssignableFrom(phaseConfig.getClass())) {
return new DefaultExhaustiveSearchPhaseFactory<>((ExhaustiveSearchPhaseConfig) phaseConfig);
} else if (NoChangePhaseConfig.class.isAssignableFrom(phaseConfig.getClass())) {
return new NoChangePhaseFactory<>((NoChangePhaseConfig) phaseConfig);
} else {
throw new IllegalArgumentException(String.format("Unknown %s type: (%s).",
PhaseConfig.class.getSimpleName(), phaseConfig.getClass().getName()));
}
}
static <Solution_> List<Phase<Solution_>> buildPhases(List<PhaseConfig> phaseConfigList,
HeuristicConfigPolicy<Solution_> configPolicy, BestSolutionRecaller<Solution_> bestSolutionRecaller,
SolverTermination<Solution_> termination) {
List<Phase<Solution_>> phaseList = new ArrayList<>(phaseConfigList.size());
boolean isPhaseSelected = false;
for (int phaseIndex = 0; phaseIndex < phaseConfigList.size(); phaseIndex++) {
var phaseConfig = phaseConfigList.get(phaseIndex);
if (phaseIndex > 0) {
PhaseConfig previousPhaseConfig = phaseConfigList.get(phaseIndex - 1);
if (!canTerminate(previousPhaseConfig)) {
throw new IllegalStateException("Solver configuration contains an unreachable phase. "
+ "Phase #" + phaseIndex + " (" + phaseConfig + ") follows a phase "
+ "without a configured termination (" + previousPhaseConfig + ").");
}
}
var isConstructionPhase = ConstructionHeuristicPhaseConfig.class.isAssignableFrom(phaseConfig.getClass());
// We currently do not support nearby functionality for CH.
// Additionally, mixed models must not include any nearby settings for basic variables,
// as this may cause failures in certain cases,
// such as when defining multiple variables with a Cartesian product.
var entityPlacerConfig =
isConstructionPhase ? ((ConstructionHeuristicPhaseConfig) phaseConfig).getEntityPlacerConfig() : null;
var disableNearbySetting =
configPolicy.getNearbyDistanceMeterClass() != null && entityPlacerConfig != null
&& QueuedEntityPlacerConfig.class.isAssignableFrom(entityPlacerConfig.getClass())
&& configPolicy.getSolutionDescriptor().hasBothBasicAndListVariables();
var updatedConfigPolicy =
disableNearbySetting ? configPolicy.copyConfigPolicyWithoutNearbySetting() : configPolicy;
// The initialization phase can only be applied to construction heuristics or custom phases
var isConstructionOrCustomPhase =
isConstructionPhase || CustomPhaseConfig.class.isAssignableFrom(phaseConfig.getClass());
// The next phase must be a local search
var isNextPhaseLocalSearch = phaseIndex + 1 < phaseConfigList.size()
&& LocalSearchPhaseConfig.class.isAssignableFrom(phaseConfigList.get(phaseIndex + 1).getClass());
PhaseFactory<Solution_> phaseFactory = PhaseFactory.create(phaseConfig);
var phase = phaseFactory.buildPhase(phaseIndex,
!isPhaseSelected && isConstructionOrCustomPhase && isNextPhaseLocalSearch, updatedConfigPolicy,
bestSolutionRecaller, termination);
// Ensure only one initialization phase is set
if (!isPhaseSelected && isConstructionOrCustomPhase && isNextPhaseLocalSearch) {
isPhaseSelected = true;
}
phaseList.add(phase);
}
return phaseList;
}
static boolean canTerminate(PhaseConfig phaseConfig) {
if (phaseConfig instanceof ConstructionHeuristicPhaseConfig
|| phaseConfig instanceof ExhaustiveSearchPhaseConfig
|| phaseConfig instanceof CustomPhaseConfig) { // Termination guaranteed.
return true;
}
TerminationConfig terminationConfig = phaseConfig.getTerminationConfig();
return (terminationConfig != null && terminationConfig.isConfigured());
}
Phase<Solution_> buildPhase(int phaseIndex, boolean lastInitializingPhase,
HeuristicConfigPolicy<Solution_> solverConfigPolicy, BestSolutionRecaller<Solution_> bestSolutionRecaller,
SolverTermination<Solution_> solverTermination);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/PossiblyInitializingPhase.java | package ai.timefold.solver.core.impl.phase;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.solver.SolverJobBuilder;
import ai.timefold.solver.core.api.solver.SolverJobBuilder.FirstInitializedSolutionConsumer;
import ai.timefold.solver.core.impl.constructionheuristic.ConstructionHeuristicPhase;
import ai.timefold.solver.core.impl.localsearch.LocalSearchPhase;
import ai.timefold.solver.core.impl.phase.custom.CustomPhase;
import org.jspecify.annotations.NullMarked;
/**
* Describes a phase that can be used to initialize a solution.
* {@link ConstructionHeuristicPhase} is automatically an initializing phase.
* {@link CustomPhase} can be an initializing phase, if it comes before the first {@link LocalSearchPhase}.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
@NullMarked
public interface PossiblyInitializingPhase<Solution_> extends Phase<Solution_> {
/**
* Check if a phase should trigger the first initialized solution event.
* The first initialized solution immediately precedes the first {@link LocalSearchPhase}.
*
* @return true if the phase is the final phase before the first local search phase.
* @see SolverJobBuilder#withFirstInitializedSolutionConsumer(FirstInitializedSolutionConsumer)
*/
boolean isLastInitializingPhase();
/**
* The status with which the phase terminated.
*/
TerminationStatus getTerminationStatus();
/**
* The status with which the phase terminated.
*
* @param terminated If the phase terminated.
* @param early If the phase terminated early without completing all steps.
* If true, this signifies a solution that is not fully initialized.
* @param stepCount The number of steps completed.
*/
record TerminationStatus(boolean terminated, boolean early, int stepCount) {
public static TerminationStatus NOT_TERMINATED = new TerminationStatus(false, false, -1);
public static TerminationStatus regular(int stepCount) {
return new TerminationStatus(true, false, stepCount);
}
public static TerminationStatus early(int stepCount) {
return new TerminationStatus(true, true, stepCount);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/custom/CustomPhase.java | package ai.timefold.solver.core.impl.phase.custom;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.solver.phase.PhaseCommand;
import ai.timefold.solver.core.impl.phase.AbstractPhase;
import ai.timefold.solver.core.impl.phase.Phase;
import ai.timefold.solver.core.impl.phase.PossiblyInitializingPhase;
import org.jspecify.annotations.NullMarked;
/**
* A {@link CustomPhase} is a {@link Phase} which uses {@link PhaseCommand}s.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @see Phase
* @see AbstractPhase
* @see DefaultCustomPhase
*/
@NullMarked
public interface CustomPhase<Solution_> extends PossiblyInitializingPhase<Solution_> {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/custom/CustomPhaseCommand.java | package ai.timefold.solver.core.impl.phase.custom;
import java.util.function.BooleanSupplier;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.api.solver.phase.PhaseCommand;
import org.jspecify.annotations.NullMarked;
/**
* @deprecated Use {@link PhaseCommand} instead.
*/
@FunctionalInterface
@NullMarked
@Deprecated(forRemoval = true, since = "1.20.0")
public interface CustomPhaseCommand<Solution_> extends PhaseCommand<Solution_> {
@Override
default void changeWorkingSolution(ScoreDirector<Solution_> scoreDirector, BooleanSupplier isPhaseTerminated) {
changeWorkingSolution(scoreDirector);
}
void changeWorkingSolution(ScoreDirector<Solution_> scoreDirector);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/custom/DefaultCustomPhase.java | package ai.timefold.solver.core.impl.phase.custom;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.solver.phase.PhaseCommand;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
import ai.timefold.solver.core.impl.phase.AbstractPossiblyInitializingPhase;
import ai.timefold.solver.core.impl.phase.custom.scope.CustomPhaseScope;
import ai.timefold.solver.core.impl.phase.custom.scope.CustomStepScope;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.termination.PhaseTermination;
import org.jspecify.annotations.NullMarked;
/**
* Default implementation of {@link CustomPhase}.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
@NullMarked
public final class DefaultCustomPhase<Solution_>
extends AbstractPossiblyInitializingPhase<Solution_>
implements CustomPhase<Solution_> {
private final List<PhaseCommand<Solution_>> customPhaseCommandList;
private TerminationStatus terminationStatus = TerminationStatus.NOT_TERMINATED;
private DefaultCustomPhase(DefaultCustomPhaseBuilder<Solution_> builder) {
super(builder);
this.customPhaseCommandList = builder.customPhaseCommandList;
}
@Override
public TerminationStatus getTerminationStatus() {
return terminationStatus;
}
@Override
public String getPhaseTypeString() {
return "Custom";
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void solve(SolverScope<Solution_> solverScope) {
var phaseScope = new CustomPhaseScope<>(solverScope, phaseIndex);
phaseStarted(phaseScope);
TerminationStatus earlyTerminationStatus = null;
var iterator = customPhaseCommandList.iterator();
while (iterator.hasNext()) {
var customPhaseCommand = iterator.next();
solverScope.checkYielding();
if (phaseTermination.isPhaseTerminated(phaseScope)) {
earlyTerminationStatus = TerminationStatus.early(phaseScope.getNextStepIndex());
break;
}
var stepScope = new CustomStepScope<>(phaseScope);
stepStarted(stepScope);
doStep(stepScope, customPhaseCommand);
stepEnded(stepScope);
phaseScope.setLastCompletedStepScope(stepScope);
}
// We only store the termination status, which is exposed to the outside, when the phase has ended.
terminationStatus = translateEarlyTermination(phaseScope, earlyTerminationStatus, iterator.hasNext());
phaseEnded(phaseScope);
}
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
terminationStatus = TerminationStatus.NOT_TERMINATED;
}
private void doStep(CustomStepScope<Solution_> stepScope, PhaseCommand<Solution_> customPhaseCommand) {
var scoreDirector = stepScope.getScoreDirector();
customPhaseCommand.changeWorkingSolution(scoreDirector,
() -> phaseTermination.isPhaseTerminated(stepScope.getPhaseScope()));
calculateWorkingStepScore(stepScope, customPhaseCommand);
var solver = stepScope.getPhaseScope().getSolverScope().getSolver();
solver.getBestSolutionRecaller().processWorkingSolutionDuringStep(stepScope);
}
public void stepEnded(CustomStepScope<Solution_> stepScope) {
super.stepEnded(stepScope);
var phaseScope = stepScope.getPhaseScope();
if (logger.isDebugEnabled()) {
logger.debug("{} Custom step ({}), time spent ({}), score ({}), {} best score ({}).",
logIndentation,
stepScope.getStepIndex(),
phaseScope.calculateSolverTimeMillisSpentUpToNow(),
stepScope.getScore().raw(),
stepScope.getBestScoreImproved() ? "new" : " ",
phaseScope.getBestScore().raw());
}
}
public void phaseEnded(CustomPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
ensureCorrectTermination(phaseScope, logger);
phaseScope.endingNow();
logger.info("{}Custom phase ({}) ended: time spent ({}), best score ({}),"
+ " move evaluation speed ({}/sec), step total ({}).",
logIndentation,
phaseIndex,
phaseScope.calculateSolverTimeMillisSpentUpToNow(),
phaseScope.getBestScore().raw(),
phaseScope.getPhaseMoveEvaluationSpeed(),
phaseScope.getNextStepIndex());
}
public static final class DefaultCustomPhaseBuilder<Solution_>
extends AbstractPossiblyInitializingPhaseBuilder<Solution_> {
private final List<PhaseCommand<Solution_>> customPhaseCommandList;
public DefaultCustomPhaseBuilder(int phaseIndex, boolean lastInitializingPhase, String logIndentation,
PhaseTermination<Solution_> phaseTermination, List<PhaseCommand<Solution_>> customPhaseCommandList) {
super(phaseIndex, lastInitializingPhase, logIndentation, phaseTermination);
this.customPhaseCommandList = List.copyOf(customPhaseCommandList);
}
@Override
public DefaultCustomPhaseBuilder<Solution_> enableAssertions(EnvironmentMode environmentMode) {
super.enableAssertions(environmentMode);
return this;
}
@Override
public DefaultCustomPhase<Solution_> build() {
return new DefaultCustomPhase<>(this);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/custom/DefaultCustomPhaseFactory.java | package ai.timefold.solver.core.impl.phase.custom;
import java.util.ArrayList;
import java.util.Collection;
import ai.timefold.solver.core.api.solver.phase.PhaseCommand;
import ai.timefold.solver.core.config.phase.custom.CustomPhaseConfig;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.phase.AbstractPhaseFactory;
import ai.timefold.solver.core.impl.solver.recaller.BestSolutionRecaller;
import ai.timefold.solver.core.impl.solver.termination.SolverTermination;
public class DefaultCustomPhaseFactory<Solution_> extends AbstractPhaseFactory<Solution_, CustomPhaseConfig> {
public DefaultCustomPhaseFactory(CustomPhaseConfig phaseConfig) {
super(phaseConfig);
}
@Override
public CustomPhase<Solution_> buildPhase(int phaseIndex, boolean lastInitializingPhase,
HeuristicConfigPolicy<Solution_> solverConfigPolicy, BestSolutionRecaller<Solution_> bestSolutionRecaller,
SolverTermination<Solution_> solverTermination) {
var phaseConfigPolicy = solverConfigPolicy.createPhaseConfigPolicy();
var customPhaseCommandClassList = phaseConfig.getCustomPhaseCommandClassList();
var customPhaseCommandList = phaseConfig.getCustomPhaseCommandList();
if (ConfigUtils.isEmptyCollection(customPhaseCommandClassList)
&& ConfigUtils.isEmptyCollection(customPhaseCommandList)) {
throw new IllegalArgumentException(
"Configure at least 1 <customPhaseCommandClass> in the <customPhase> configuration.");
}
var customPhaseCommandList_ = new ArrayList<PhaseCommand<Solution_>>(getCustomPhaseCommandListSize());
if (customPhaseCommandClassList != null) {
for (var customPhaseCommandClass : customPhaseCommandClassList) {
if (customPhaseCommandClass == null) {
throw new IllegalArgumentException("""
The customPhaseCommandClass (%s) cannot be null in the customPhase (%s).
Maybe there was a typo in the class name provided in the solver config XML?"""
.formatted(customPhaseCommandClass, phaseConfig));
}
customPhaseCommandList_.add(createCustomPhaseCommand(customPhaseCommandClass));
}
}
if (customPhaseCommandList != null) {
customPhaseCommandList_.addAll((Collection) customPhaseCommandList);
}
return new DefaultCustomPhase.DefaultCustomPhaseBuilder<>(phaseIndex, lastInitializingPhase,
solverConfigPolicy.getLogIndentation(), buildPhaseTermination(phaseConfigPolicy, solverTermination),
customPhaseCommandList_)
.enableAssertions(phaseConfigPolicy.getEnvironmentMode())
.build();
}
private PhaseCommand<Solution_> createCustomPhaseCommand(Class<? extends PhaseCommand> customPhaseCommandClass) {
PhaseCommand<Solution_> customPhaseCommand =
ConfigUtils.newInstance(phaseConfig, "customPhaseCommandClass", customPhaseCommandClass);
ConfigUtils.applyCustomProperties(customPhaseCommand, "customPhaseCommandClass", phaseConfig.getCustomProperties(),
"customProperties");
return customPhaseCommand;
}
private int getCustomPhaseCommandListSize() {
var customPhaseCommandClassList = phaseConfig.getCustomPhaseCommandClassList();
var customPhaseCommandList = phaseConfig.getCustomPhaseCommandList();
return (customPhaseCommandClassList == null ? 0 : customPhaseCommandClassList.size())
+ (customPhaseCommandList == null ? 0 : customPhaseCommandList.size());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/custom | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/custom/scope/CustomPhaseScope.java | package ai.timefold.solver.core.impl.phase.custom.scope;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public final class CustomPhaseScope<Solution_> extends AbstractPhaseScope<Solution_> {
private CustomStepScope<Solution_> lastCompletedStepScope;
public CustomPhaseScope(SolverScope<Solution_> solverScope, int phaseIndex) {
this(solverScope, phaseIndex, false);
}
public CustomPhaseScope(SolverScope<Solution_> solverScope, int phaseIndex, boolean phaseSendsBestSolutionEvents) {
super(solverScope, phaseIndex, phaseSendsBestSolutionEvents);
lastCompletedStepScope = new CustomStepScope<>(this, -1);
}
@Override
public CustomStepScope<Solution_> getLastCompletedStepScope() {
return lastCompletedStepScope;
}
public void setLastCompletedStepScope(CustomStepScope<Solution_> lastCompletedStepScope) {
this.lastCompletedStepScope = lastCompletedStepScope;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/custom | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/custom/scope/CustomStepScope.java | package ai.timefold.solver.core.impl.phase.custom.scope;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public final class CustomStepScope<Solution_> extends AbstractStepScope<Solution_> {
private final CustomPhaseScope<Solution_> phaseScope;
public CustomStepScope(CustomPhaseScope<Solution_> phaseScope) {
this(phaseScope, phaseScope.getNextStepIndex());
}
public CustomStepScope(CustomPhaseScope<Solution_> phaseScope, int stepIndex) {
super(stepIndex);
this.phaseScope = phaseScope;
}
@Override
public CustomPhaseScope<Solution_> getPhaseScope() {
return phaseScope;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/event/PhaseLifecycleListener.java | package ai.timefold.solver.core.impl.phase.event;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
import ai.timefold.solver.core.impl.solver.event.SolverLifecycleListener;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @see PhaseLifecycleListenerAdapter
*/
public interface PhaseLifecycleListener<Solution_> extends SolverLifecycleListener<Solution_> {
void phaseStarted(AbstractPhaseScope<Solution_> phaseScope);
void stepStarted(AbstractStepScope<Solution_> stepScope);
void stepEnded(AbstractStepScope<Solution_> stepScope);
void phaseEnded(AbstractPhaseScope<Solution_> phaseScope);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/event/PhaseLifecycleListenerAdapter.java | package ai.timefold.solver.core.impl.phase.event;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
import ai.timefold.solver.core.impl.solver.event.SolverLifecycleListenerAdapter;
/**
* An adapter for {@link PhaseLifecycleListener}.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class PhaseLifecycleListenerAdapter<Solution_> extends SolverLifecycleListenerAdapter<Solution_>
implements PhaseLifecycleListener<Solution_> {
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
// Hook method
}
@Override
public void stepStarted(AbstractStepScope<Solution_> stepScope) {
// Hook method
}
@Override
public void stepEnded(AbstractStepScope<Solution_> stepScope) {
// Hook method
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
// Hook method
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/event/PhaseLifecycleSupport.java | package ai.timefold.solver.core.impl.phase.event;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
import ai.timefold.solver.core.impl.solver.event.AbstractEventSupport;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
/**
* Internal API.
*/
public final class PhaseLifecycleSupport<Solution_> extends AbstractEventSupport<PhaseLifecycleListener<Solution_>> {
public void fireSolvingStarted(SolverScope<Solution_> solverScope) {
for (PhaseLifecycleListener<Solution_> listener : getEventListeners()) {
listener.solvingStarted(solverScope);
}
}
public void firePhaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
for (PhaseLifecycleListener<Solution_> listener : getEventListeners()) {
listener.phaseStarted(phaseScope);
}
}
public void fireStepStarted(AbstractStepScope<Solution_> stepScope) {
for (PhaseLifecycleListener<Solution_> listener : getEventListeners()) {
listener.stepStarted(stepScope);
}
}
public void fireStepEnded(AbstractStepScope<Solution_> stepScope) {
for (PhaseLifecycleListener<Solution_> listener : getEventListeners()) {
listener.stepEnded(stepScope);
}
}
public void firePhaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
for (PhaseLifecycleListener<Solution_> listener : getEventListeners()) {
listener.phaseEnded(phaseScope);
}
}
public void fireSolvingEnded(SolverScope<Solution_> solverScope) {
for (PhaseLifecycleListener<Solution_> listener : getEventListeners()) {
listener.solvingEnded(solverScope);
}
}
public void fireSolvingError(SolverScope<Solution_> solverScope, Exception exception) {
for (PhaseLifecycleListener<Solution_> listener : getEventListeners()) {
listener.solvingError(solverScope, exception);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/scope/AbstractMoveScope.java | package ai.timefold.solver.core.impl.phase.scope;
import java.util.Random;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.score.director.InnerScore;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.preview.api.move.Move;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class AbstractMoveScope<Solution_> {
protected final AbstractStepScope<Solution_> stepScope;
protected final int moveIndex;
protected final Move<Solution_> move;
protected InnerScore<?> score = null;
protected AbstractMoveScope(AbstractStepScope<Solution_> stepScope, int moveIndex, Move<Solution_> move) {
this.stepScope = stepScope;
this.moveIndex = moveIndex;
this.move = move;
}
public AbstractStepScope<Solution_> getStepScope() {
return stepScope;
}
public int getMoveIndex() {
return moveIndex;
}
public Move<Solution_> getMove() {
return move;
}
@SuppressWarnings("unchecked")
public <Score_ extends Score<Score_>> InnerScore<Score_> getScore() {
return (InnerScore<Score_>) score;
}
public <Score_ extends Score<Score_>> void setInitializedScore(Score_ score) {
setScore(InnerScore.fullyAssigned(score));
}
public void setScore(InnerScore<?> score) {
this.score = score;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
public int getStepIndex() {
return getStepScope().getStepIndex();
}
public <Score_ extends Score<Score_>> InnerScoreDirector<Solution_, Score_> getScoreDirector() {
return getStepScope().getScoreDirector();
}
public Solution_ getWorkingSolution() {
return getStepScope().getWorkingSolution();
}
public Random getWorkingRandom() {
return getStepScope().getWorkingRandom();
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + getStepScope().getStepIndex() + "/" + moveIndex + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/scope/AbstractPhaseScope.java | package ai.timefold.solver.core.impl.phase.scope;
import java.util.Random;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.config.solver.monitoring.SolverMetric;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.score.director.InnerScore;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.termination.PhaseTermination;
import ai.timefold.solver.core.preview.api.move.Move;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class AbstractPhaseScope<Solution_> {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected final SolverScope<Solution_> solverScope;
protected final int phaseIndex;
protected final boolean phaseSendingBestSolutionEvents;
protected Long startingSystemTimeMillis;
protected Long startingScoreCalculationCount;
protected Long startingMoveEvaluationCount;
protected InnerScore<?> startingScore;
protected Long endingSystemTimeMillis;
protected Long endingScoreCalculationCount;
protected Long endingMoveEvaluationCount;
protected long childThreadsScoreCalculationCount = 0L;
protected int bestSolutionStepIndex;
/**
* The phase termination configuration
*/
private PhaseTermination<Solution_> termination;
/**
* As defined by #AbstractPhaseScope(SolverScope, int, boolean)
* with the phaseSendingBestSolutionEvents parameter set to true.
*/
protected AbstractPhaseScope(SolverScope<Solution_> solverScope, int phaseIndex) {
this(solverScope, phaseIndex, true);
}
/**
*
* @param solverScope never null
* @param phaseIndex the index of the phase, >= 0
* @param phaseSendingBestSolutionEvents set to false if the phase only sends one best solution event at the end,
* or none at all;
* this is typical for construction heuristics,
* whose result only matters when it reached its natural end.
*/
protected AbstractPhaseScope(SolverScope<Solution_> solverScope, int phaseIndex, boolean phaseSendingBestSolutionEvents) {
this.solverScope = solverScope;
this.phaseIndex = phaseIndex;
this.phaseSendingBestSolutionEvents = phaseSendingBestSolutionEvents;
}
public SolverScope<Solution_> getSolverScope() {
return solverScope;
}
public int getPhaseIndex() {
return phaseIndex;
}
public boolean isPhaseSendingBestSolutionEvents() {
return phaseSendingBestSolutionEvents;
}
public Long getStartingSystemTimeMillis() {
return startingSystemTimeMillis;
}
@SuppressWarnings("unchecked")
public <Score_ extends Score<Score_>> InnerScore<Score_> getStartingScore() {
return (InnerScore<Score_>) startingScore;
}
public Long getEndingSystemTimeMillis() {
return endingSystemTimeMillis;
}
public int getBestSolutionStepIndex() {
return bestSolutionStepIndex;
}
public void setBestSolutionStepIndex(int bestSolutionStepIndex) {
this.bestSolutionStepIndex = bestSolutionStepIndex;
}
public abstract AbstractStepScope<Solution_> getLastCompletedStepScope();
// ************************************************************************
// Calculated methods
// ************************************************************************
public void reset() {
bestSolutionStepIndex = -1;
// solverScope.getBestScore() is null with an uninitialized score
startingScore = solverScope.getBestScore() == null ? solverScope.calculateScore() : solverScope.getBestScore();
if (getLastCompletedStepScope().getStepIndex() < 0) {
getLastCompletedStepScope().setScore(startingScore);
}
}
public void startingNow() {
startingSystemTimeMillis = getSolverScope().getClock().millis();
startingScoreCalculationCount = getScoreDirector().getCalculationCount();
startingMoveEvaluationCount = getSolverScope().getMoveEvaluationCount();
}
public void endingNow() {
endingSystemTimeMillis = getSolverScope().getClock().millis();
endingScoreCalculationCount = getScoreDirector().getCalculationCount();
endingMoveEvaluationCount = getSolverScope().getMoveEvaluationCount();
}
public SolutionDescriptor<Solution_> getSolutionDescriptor() {
return solverScope.getSolutionDescriptor();
}
public long calculateSolverTimeMillisSpentUpToNow() {
return solverScope.calculateTimeMillisSpentUpToNow();
}
public long calculatePhaseTimeMillisSpentUpToNow() {
long now = getSolverScope().getClock().millis();
return now - startingSystemTimeMillis;
}
public long getPhaseTimeMillisSpent() {
return endingSystemTimeMillis - startingSystemTimeMillis;
}
public void addChildThreadsScoreCalculationCount(long addition) {
solverScope.addChildThreadsScoreCalculationCount(addition);
childThreadsScoreCalculationCount += addition;
}
public void addMoveEvaluationCount(Move<Solution_> move, long count) {
solverScope.addMoveEvaluationCount(1);
addMoveEvaluationCountPerType(move, count);
}
public void addMoveEvaluationCountPerType(Move<Solution_> move, long count) {
if (solverScope.isMetricEnabled(SolverMetric.MOVE_COUNT_PER_TYPE)) {
solverScope.addMoveEvaluationCountPerType(move.describe(), count);
}
}
public long getPhaseScoreCalculationCount() {
return endingScoreCalculationCount - startingScoreCalculationCount + childThreadsScoreCalculationCount;
}
public long getPhaseMoveEvaluationCount() {
var currentMoveEvaluationCount = endingMoveEvaluationCount;
if (endingMoveEvaluationCount == null) {
currentMoveEvaluationCount = getSolverScope().getMoveEvaluationCount();
}
return currentMoveEvaluationCount - startingMoveEvaluationCount;
}
/**
* @return at least 0, per second
*/
public long getPhaseScoreCalculationSpeed() {
return getMetricCalculationSpeed(getPhaseScoreCalculationCount());
}
/**
* @return at least 0, per second
*/
public long getPhaseMoveEvaluationSpeed() {
return getMetricCalculationSpeed(getPhaseMoveEvaluationCount());
}
private long getMetricCalculationSpeed(long metric) {
long timeMillisSpent = getPhaseTimeMillisSpent();
// Avoid divide by zero exception on a fast CPU
return metric * 1000L / (timeMillisSpent == 0L ? 1L : timeMillisSpent);
}
public <Score_ extends Score<Score_>> InnerScoreDirector<Solution_, Score_> getScoreDirector() {
return solverScope.getScoreDirector();
}
public void setTermination(PhaseTermination<Solution_> termination) {
this.termination = termination;
}
public PhaseTermination<Solution_> getTermination() {
return termination;
}
public Solution_ getWorkingSolution() {
return solverScope.getWorkingSolution();
}
public int getWorkingEntityCount() {
return solverScope.getWorkingEntityCount();
}
public <Score_ extends Score<Score_>> InnerScore<Score_> calculateScore() {
return solverScope.calculateScore();
}
public <Score_ extends Score<Score_>> void assertExpectedWorkingScore(InnerScore<Score_> expectedWorkingScore,
Object completedAction) {
InnerScoreDirector<Solution_, Score_> innerScoreDirector = getScoreDirector();
innerScoreDirector.assertExpectedWorkingScore(expectedWorkingScore, completedAction);
}
public <Score_ extends Score<Score_>> void assertWorkingScoreFromScratch(InnerScore<Score_> workingScore,
Object completedAction) {
InnerScoreDirector<Solution_, Score_> innerScoreDirector = getScoreDirector();
innerScoreDirector.assertWorkingScoreFromScratch(workingScore, completedAction);
}
public <Score_ extends Score<Score_>> void assertPredictedScoreFromScratch(InnerScore<Score_> workingScore,
Object completedAction) {
InnerScoreDirector<Solution_, Score_> innerScoreDirector = getScoreDirector();
innerScoreDirector.assertPredictedScoreFromScratch(workingScore, completedAction);
}
public <Score_ extends Score<Score_>> void assertShadowVariablesAreNotStale(InnerScore<Score_> workingScore,
Object completedAction) {
InnerScoreDirector<Solution_, Score_> innerScoreDirector = getScoreDirector();
innerScoreDirector.assertShadowVariablesAreNotStale(workingScore, completedAction);
}
public Random getWorkingRandom() {
return getSolverScope().getWorkingRandom();
}
public boolean isBestSolutionInitialized() {
return solverScope.isBestSolutionInitialized();
}
public <Score_ extends Score<Score_>> InnerScore<Score_> getBestScore() {
return solverScope.getBestScore();
}
public long getPhaseBestSolutionTimeMillis() {
long bestSolutionTimeMillis = solverScope.getBestSolutionTimeMillis();
// If the termination is explicitly phase configured, previous phases must not affect it
if (bestSolutionTimeMillis < startingSystemTimeMillis) {
bestSolutionTimeMillis = startingSystemTimeMillis;
}
return bestSolutionTimeMillis;
}
public int getNextStepIndex() {
return getLastCompletedStepScope().getStepIndex() + 1;
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + phaseIndex + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/scope/AbstractStepScope.java | package ai.timefold.solver.core.impl.phase.scope;
import java.util.Random;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.move.director.MoveDirector;
import ai.timefold.solver.core.impl.score.director.InnerScore;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class AbstractStepScope<Solution_> {
protected final int stepIndex;
protected InnerScore<?> score = null;
protected boolean bestScoreImproved = false;
// Stays null if there is no need to clone it
protected Solution_ clonedSolution = null;
public AbstractStepScope(int stepIndex) {
this.stepIndex = stepIndex;
}
public abstract AbstractPhaseScope<Solution_> getPhaseScope();
public int getStepIndex() {
return stepIndex;
}
@SuppressWarnings("unchecked")
public <Score_ extends Score<Score_>> InnerScore<Score_> getScore() {
return (InnerScore<Score_>) score;
}
@SuppressWarnings("rawtypes")
public void setInitializedScore(Score<?> score) {
setScore(InnerScore.fullyAssigned((Score) score));
}
public void setScore(InnerScore<?> score) {
this.score = score;
}
public boolean getBestScoreImproved() {
return bestScoreImproved;
}
public void setBestScoreImproved(Boolean bestScoreImproved) {
this.bestScoreImproved = bestScoreImproved;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
public <Score_ extends Score<Score_>> InnerScoreDirector<Solution_, Score_> getScoreDirector() {
return getPhaseScope().getScoreDirector();
}
public <Score_ extends Score<Score_>> MoveDirector<Solution_, Score_> getMoveDirector() {
return this.<Score_> getScoreDirector().getMoveDirector();
}
public Solution_ getWorkingSolution() {
return getPhaseScope().getWorkingSolution();
}
public Random getWorkingRandom() {
return getPhaseScope().getWorkingRandom();
}
public Solution_ createOrGetClonedSolution() {
if (clonedSolution == null) {
clonedSolution = getScoreDirector().cloneWorkingSolution();
}
return clonedSolution;
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + stepIndex + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/phase/scope/SolverLifecyclePoint.java | package ai.timefold.solver.core.impl.phase.scope;
import java.util.ArrayList;
import java.util.Objects;
/**
* Identifies which move thread, which phase, step and move/move tree the solver is currently executing.
*
* @param moveThreadIndex the index of the move thread, or -1 if moveThreadCount = NONE.
* @param phaseIndex the index of the phase.
* @param stepIndex the index of the step.
* @param moveIndex the index of the move, or -1 if exhaustive search.
* @param treeId the id of the move tree if exhaustive search, null otherwise.
*/
public record SolverLifecyclePoint(int moveThreadIndex, int phaseIndex, int stepIndex, int moveIndex, String treeId) {
public static SolverLifecyclePoint of(AbstractMoveScope<?> moveScope) { // General purpose.
var stepScope = moveScope.getStepScope();
return new SolverLifecyclePoint(-1, stepScope.getPhaseScope().getPhaseIndex(), stepScope.getStepIndex(),
moveScope.moveIndex, null);
}
public static SolverLifecyclePoint of(AbstractStepScope<?> stepScope, String treeId) { // Used in exhaustive search.
return new SolverLifecyclePoint(-1, stepScope.getPhaseScope().getPhaseIndex(), stepScope.getStepIndex(), -1,
Objects.requireNonNull(treeId));
}
public static SolverLifecyclePoint of(int moveThreadIndex, int phaseIndex, int stepIndex, int moveIndex) {
// Used in multi-threaded solving.
return new SolverLifecyclePoint(moveThreadIndex, phaseIndex, stepIndex, moveIndex, null);
}
@Override
public String toString() {
var stringList = new ArrayList<String>();
stringList.add("Phase index (%d)".formatted(phaseIndex));
if (moveThreadIndex >= 0) {
stringList.add("move thread index (%d)".formatted(moveThreadIndex));
}
stringList.add("step index (%d)".formatted(stepIndex));
if (moveIndex == -1) {
stringList.add("move tree id (%s)".formatted(treeId));
} else {
stringList.add("move index (%d)".formatted(moveIndex));
}
return String.join(", ", stringList) + ".";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/DefaultScoreExplanation.java | package ai.timefold.solver.core.impl.score;
import static java.util.Comparator.comparing;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.ScoreExplanation;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatch;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal;
import ai.timefold.solver.core.api.score.constraint.Indictment;
import ai.timefold.solver.core.api.score.stream.ConstraintJustification;
import ai.timefold.solver.core.impl.score.director.InnerScore;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import org.jspecify.annotations.NonNull;
public final class DefaultScoreExplanation<Solution_, Score_ extends Score<Score_>>
implements ScoreExplanation<Solution_, Score_> {
private static final int DEFAULT_SCORE_EXPLANATION_INDICTMENT_LIMIT = 5;
private static final int DEFAULT_SCORE_EXPLANATION_CONSTRAINT_MATCH_LIMIT = 2;
private final Solution_ solution;
private final InnerScore<Score_> innerScore;
private final Map<String, ConstraintMatchTotal<Score_>> constraintMatchTotalMap;
private final List<ConstraintJustification> constraintJustificationList;
private final Map<Object, Indictment<Score_>> indictmentMap;
private final AtomicReference<String> summary = new AtomicReference<>(); // Will be calculated lazily.
public static <Score_ extends Score<Score_>> String explainScore(InnerScore<Score_> workingScore,
Collection<ConstraintMatchTotal<Score_>> constraintMatchTotalCollection,
Collection<Indictment<Score_>> indictmentCollection) {
return explainScore(workingScore, constraintMatchTotalCollection, indictmentCollection,
DEFAULT_SCORE_EXPLANATION_INDICTMENT_LIMIT, DEFAULT_SCORE_EXPLANATION_CONSTRAINT_MATCH_LIMIT);
}
public static <Score_ extends Score<Score_>> String explainScore(InnerScore<Score_> workingScore,
Collection<ConstraintMatchTotal<Score_>> constraintMatchTotalCollection,
Collection<Indictment<Score_>> indictmentCollection, int indictmentLimit, int constraintMatchLimit) {
var scoreExplanation = new StringBuilder((constraintMatchTotalCollection.size() + 4 + 2 * indictmentLimit) * 80);
scoreExplanation.append("""
Explanation of score (%s)%s:
Constraint matches:
""".formatted(workingScore, workingScore.isFullyAssigned() ? "" : " for an uninitialized solution"));
Comparator<ConstraintMatchTotal<Score_>> constraintMatchTotalComparator = comparing(ConstraintMatchTotal::getScore);
Comparator<ConstraintMatch<Score_>> constraintMatchComparator = comparing(ConstraintMatch::getScore);
constraintMatchTotalCollection.stream()
.sorted(constraintMatchTotalComparator)
.forEach(constraintMatchTotal -> {
var constraintMatchSet = constraintMatchTotal.getConstraintMatchSet();
scoreExplanation.append("""
%s: constraint (%s) has %s matches:
""".formatted(constraintMatchTotal.getScore().toShortString(),
constraintMatchTotal.getConstraintRef().constraintName(), constraintMatchSet.size()));
constraintMatchSet.stream()
.sorted(constraintMatchComparator)
.limit(constraintMatchLimit)
.forEach(constraintMatch -> {
if (constraintMatch.getJustification() == null) {
scoreExplanation.append("""
%s: unjustified
""".formatted(constraintMatch.getScore().toShortString()));
} else {
scoreExplanation.append("""
%s: justified with (%s)
""".formatted(constraintMatch.getScore().toShortString(),
constraintMatch.getJustification()));
}
});
if (constraintMatchSet.size() > constraintMatchLimit) {
scoreExplanation.append("""
...
""");
}
});
var indictmentCount = indictmentCollection.size();
if (indictmentLimit < indictmentCount) {
scoreExplanation.append("""
Indictments (top %s of %s):
""".formatted(indictmentLimit, indictmentCount));
} else {
scoreExplanation.append("""
Indictments:
""");
}
Comparator<Indictment<Score_>> indictmentComparator = comparing(Indictment::getScore);
Comparator<ConstraintMatch<Score_>> constraintMatchScoreComparator = comparing(ConstraintMatch::getScore);
indictmentCollection.stream()
.sorted(indictmentComparator)
.limit(indictmentLimit)
.forEach(indictment -> {
var constraintMatchSet = indictment.getConstraintMatchSet();
scoreExplanation.append("""
%s: indicted with (%s) has %s matches:
""".formatted(indictment.getScore().toShortString(), indictment.getIndictedObject(),
constraintMatchSet.size()));
constraintMatchSet.stream()
.sorted(constraintMatchScoreComparator)
.limit(constraintMatchLimit)
.forEach(constraintMatch -> scoreExplanation.append("""
%s: constraint (%s)
""".formatted(constraintMatch.getScore().toShortString(),
constraintMatch.getConstraintRef().constraintName())));
if (constraintMatchSet.size() > constraintMatchLimit) {
scoreExplanation.append("""
...
""");
}
});
if (indictmentCount > indictmentLimit) {
scoreExplanation.append("""
...
""");
}
return scoreExplanation.toString();
}
public DefaultScoreExplanation(InnerScoreDirector<Solution_, Score_> scoreDirector) {
this(scoreDirector.getWorkingSolution(), scoreDirector.calculateScore(), scoreDirector.getConstraintMatchTotalMap(),
scoreDirector.getIndictmentMap());
}
public DefaultScoreExplanation(Solution_ solution, InnerScore<Score_> innerScore,
Map<String, ConstraintMatchTotal<Score_>> constraintMatchTotalMap,
Map<Object, Indictment<Score_>> indictmentMap) {
this.solution = solution;
this.innerScore = innerScore;
this.constraintMatchTotalMap = constraintMatchTotalMap;
List<ConstraintJustification> workingConstraintJustificationList = new ArrayList<>();
for (ConstraintMatchTotal<Score_> constraintMatchTotal : constraintMatchTotalMap.values()) {
for (ConstraintMatch<Score_> constraintMatch : constraintMatchTotal.getConstraintMatchSet()) {
ConstraintJustification justification = constraintMatch.getJustification();
if (justification != null) {
workingConstraintJustificationList.add(justification);
}
}
}
this.constraintJustificationList =
workingConstraintJustificationList.isEmpty() ? Collections.emptyList() : workingConstraintJustificationList;
this.indictmentMap = indictmentMap;
}
@Override
public @NonNull Solution_ getSolution() {
return solution;
}
@Override
public @NonNull Score_ getScore() {
return innerScore.raw();
}
@Override
public boolean isInitialized() {
return innerScore.isFullyAssigned();
}
@Override
public @NonNull Map<String, ConstraintMatchTotal<Score_>> getConstraintMatchTotalMap() {
return constraintMatchTotalMap;
}
@Override
public @NonNull List<ConstraintJustification> getJustificationList() {
return constraintJustificationList;
}
@Override
public @NonNull Map<Object, Indictment<Score_>> getIndictmentMap() {
return indictmentMap;
}
@Override
public @NonNull String getSummary() {
return summary.updateAndGet(currentSummary -> Objects.requireNonNullElseGet(currentSummary,
() -> explainScore(innerScore, constraintMatchTotalMap.values(), indictmentMap.values())));
}
@Override
public String toString() {
return getSummary(); // So that this class can be used in strings directly.
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/DefaultScoreManager.java | package ai.timefold.solver.core.impl.score;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.ScoreExplanation;
import ai.timefold.solver.core.api.score.ScoreManager;
import ai.timefold.solver.core.api.solver.SolutionManager;
import ai.timefold.solver.core.api.solver.SolutionUpdatePolicy;
import ai.timefold.solver.core.impl.solver.DefaultSolutionManager;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @deprecated Use {@link DefaultSolutionManager} instead.
*/
@Deprecated(forRemoval = true)
public final class DefaultScoreManager<Solution_, Score_ extends Score<Score_>>
implements ScoreManager<Solution_, Score_> {
private final SolutionManager<Solution_, Score_> solutionManager;
public DefaultScoreManager(SolutionManager<Solution_, Score_> solutionManager) {
this.solutionManager = Objects.requireNonNull(solutionManager);
}
@Override
public Score_ updateScore(Solution_ solution) {
return solutionManager.update(solution, SolutionUpdatePolicy.UPDATE_SCORE_ONLY);
}
@Override
public String getSummary(Solution_ solution) {
return explainScore(solution)
.getSummary();
}
@Override
public ScoreExplanation<Solution_, Score_> explainScore(Solution_ solution) {
return solutionManager.explain(solution, SolutionUpdatePolicy.UPDATE_SCORE_ONLY);
}
@Override
public Score_ update(Solution_ solution, SolutionUpdatePolicy solutionUpdatePolicy) {
return solutionManager.update(solution, solutionUpdatePolicy);
}
@Override
public ScoreExplanation<Solution_, Score_> explain(Solution_ solution, SolutionUpdatePolicy solutionUpdatePolicy) {
return solutionManager.explain(solution, solutionUpdatePolicy);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/ScoreUtil.java | package ai.timefold.solver.core.impl.score;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.function.Predicate;
import ai.timefold.solver.core.api.score.IBendableScore;
import ai.timefold.solver.core.api.score.Score;
public final class ScoreUtil {
public static final String HARD_LABEL = "hard";
public static final String MEDIUM_LABEL = "medium";
public static final String SOFT_LABEL = "soft";
public static final String[] LEVEL_SUFFIXES = new String[] { HARD_LABEL, SOFT_LABEL };
public static String[] parseScoreTokens(Class<? extends Score<?>> scoreClass, String scoreString, String... levelSuffixes) {
var scoreTokens = new String[levelSuffixes.length];
var suffixedScoreTokens = scoreString.split("/");
if (suffixedScoreTokens.length != levelSuffixes.length) {
throw new IllegalArgumentException("""
The scoreString (%s) for the scoreClass (%s) doesn't follow the correct pattern (%s): \
the suffixedScoreTokens length (%d) differs from the levelSuffixes length (%d or %d)."""
.formatted(scoreString, scoreClass.getSimpleName(), buildScorePattern(false, levelSuffixes),
suffixedScoreTokens.length, levelSuffixes.length, levelSuffixes.length + 1));
}
for (var i = 0; i < levelSuffixes.length; i++) {
var suffixedScoreToken = suffixedScoreTokens[i];
var levelSuffix = levelSuffixes[i];
if (!suffixedScoreToken.endsWith(levelSuffix)) {
throw new IllegalArgumentException("""
The scoreString (%s) for the scoreClass (%s) doesn't follow the correct pattern (%s): \
the suffixedScoreToken (%s) does not end with levelSuffix (%s)."""
.formatted(scoreString, scoreClass.getSimpleName(), buildScorePattern(false, levelSuffixes),
suffixedScoreToken, levelSuffix));
}
scoreTokens[i] = suffixedScoreToken.substring(0, suffixedScoreToken.length() - levelSuffix.length());
}
return scoreTokens;
}
public static int parseLevelAsInt(Class<? extends Score<?>> scoreClass, String scoreString, String levelString) {
if (levelString.equals("*")) {
return Integer.MIN_VALUE;
}
try {
return Integer.parseInt(levelString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"The scoreString (%s) for the scoreClass (%s) has a levelString (%s) which is not a valid integer."
.formatted(scoreString, scoreClass.getSimpleName(), levelString),
e);
}
}
public static long parseLevelAsLong(Class<? extends Score<?>> scoreClass, String scoreString, String levelString) {
if (levelString.equals("*")) {
return Long.MIN_VALUE;
}
try {
return Long.parseLong(levelString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"The scoreString (%s) for the scoreClass (%s) has a levelString (%s) which is not a valid long."
.formatted(scoreString, scoreClass.getSimpleName(), levelString),
e);
}
}
public static BigDecimal parseLevelAsBigDecimal(Class<? extends Score<?>> scoreClass, String scoreString,
String levelString) {
if (levelString.equals("*")) {
throw new IllegalArgumentException("""
The scoreString (%s) for the scoreClass (%s) has a wildcard (*) as levelString (%s) \
which is not supported for BigDecimal score values, because there is no general MIN_VALUE for BigDecimal."""
.formatted(scoreString, scoreClass.getSimpleName(), levelString));
}
try {
return new BigDecimal(levelString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"The scoreString (%s) for the scoreClass (%s) has a levelString (%s) which is not a valid BigDecimal."
.formatted(scoreString, scoreClass.getSimpleName(), levelString),
e);
}
}
public static String buildScorePattern(boolean bendable, String... levelSuffixes) {
var scorePattern = new StringBuilder(levelSuffixes.length * 10);
var first = true;
for (var levelSuffix : levelSuffixes) {
if (first) {
first = false;
} else {
scorePattern.append("/");
}
if (bendable) {
scorePattern.append("[999/.../999]");
} else {
scorePattern.append("999");
}
scorePattern.append(levelSuffix);
}
return scorePattern.toString();
}
public static <Score_ extends Score<Score_>> String buildShortString(Score<Score_> score, Predicate<Number> notZero,
String... levelLabels) {
var shortString = new StringBuilder();
var i = 0;
for (var levelNumber : score.toLevelNumbers()) {
if (notZero.test(levelNumber)) {
if (!shortString.isEmpty()) {
shortString.append("/");
}
shortString.append(levelNumber).append(levelLabels[i]);
}
i++;
}
if (shortString.isEmpty()) {
// Even for BigDecimals we use "0" over "0.0" because different levels can have different scales
return "0";
}
return shortString.toString();
}
public static String[][] parseBendableScoreTokens(Class<? extends IBendableScore<?>> scoreClass, String scoreString) {
var scoreTokens = new String[2][];
var startIndex = 0;
for (var i = 0; i < LEVEL_SUFFIXES.length; i++) {
var levelSuffix = LEVEL_SUFFIXES[i];
var endIndex = scoreString.indexOf(levelSuffix, startIndex);
if (endIndex < 0) {
throw new IllegalArgumentException("""
The scoreString (%s) for the scoreClass (%s) doesn't follow the correct pattern (%s): \
the levelSuffix (%s) isn't in the scoreSubstring (%s)."""
.formatted(scoreString, scoreClass.getSimpleName(), buildScorePattern(true, LEVEL_SUFFIXES),
levelSuffix, scoreString.substring(startIndex)));
}
var scoreSubString = scoreString.substring(startIndex, endIndex);
if (!scoreSubString.startsWith("[") || !scoreSubString.endsWith("]")) {
throw new IllegalArgumentException("""
The scoreString (%s) for the scoreClass (%s) doesn't follow the correct pattern (%s): \
the scoreSubString (%s) does not start and end with "[" and "]"."""
.formatted(scoreString, scoreClass.getSimpleName(), buildScorePattern(true, LEVEL_SUFFIXES),
scoreString));
}
scoreTokens[i] = scoreSubString.equals("[]") ? new String[0]
: scoreSubString.substring(1, scoreSubString.length() - 1).split("/");
startIndex = endIndex + levelSuffix.length() + "/".length();
}
if (startIndex != scoreString.length() + "/".length()) {
throw new IllegalArgumentException("""
The scoreString (%s) for the scoreClass (%s) doesn't follow the correct pattern (%s): \
the suffix (%s) is unsupported."""
.formatted(scoreString, scoreClass.getSimpleName(), buildScorePattern(true, LEVEL_SUFFIXES),
scoreString.substring(startIndex - 1)));
}
return scoreTokens;
}
public static <Score_ extends IBendableScore<Score_>> String buildBendableShortString(IBendableScore<Score_> score,
Predicate<Number> notZero) {
var shortString = new StringBuilder();
var levelNumbers = score.toLevelNumbers();
var hardLevelsSize = score.hardLevelsSize();
if (Arrays.stream(levelNumbers).limit(hardLevelsSize).anyMatch(notZero)) {
if (!shortString.isEmpty()) {
shortString.append("/");
}
shortString.append("[");
var first = true;
for (var i = 0; i < hardLevelsSize; i++) {
if (first) {
first = false;
} else {
shortString.append("/");
}
shortString.append(levelNumbers[i]);
}
shortString.append("]").append(HARD_LABEL);
}
var softLevelsSize = score.softLevelsSize();
if (Arrays.stream(levelNumbers).skip(hardLevelsSize).anyMatch(notZero)) {
if (!shortString.isEmpty()) {
shortString.append("/");
}
shortString.append("[");
var first = true;
for (var i = 0; i < softLevelsSize; i++) {
if (first) {
first = false;
} else {
shortString.append("/");
}
shortString.append(levelNumbers[hardLevelsSize + i]);
}
shortString.append("]").append(SOFT_LABEL);
}
if (shortString.isEmpty()) {
// Even for BigDecimals we use "0" over "0.0" because different levels can have different scales
return "0";
}
return shortString.toString();
}
private ScoreUtil() {
// No external instances.
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/buildin/BendableBigDecimalScoreDefinition.java | package ai.timefold.solver.core.impl.score.buildin;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.stream.Stream;
import ai.timefold.solver.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore;
import ai.timefold.solver.core.impl.score.definition.AbstractBendableScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
public class BendableBigDecimalScoreDefinition extends AbstractBendableScoreDefinition<BendableBigDecimalScore> {
public BendableBigDecimalScoreDefinition(int hardLevelsSize, int softLevelsSize) {
super(hardLevelsSize, softLevelsSize);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Class<BendableBigDecimalScore> getScoreClass() {
return BendableBigDecimalScore.class;
}
@Override
public BendableBigDecimalScore getZeroScore() {
return BendableBigDecimalScore.zero(hardLevelsSize, softLevelsSize);
}
@Override
public final BendableBigDecimalScore getOneSoftestScore() {
return BendableBigDecimalScore.ofSoft(hardLevelsSize, softLevelsSize, softLevelsSize - 1, BigDecimal.ONE);
}
@Override
public BendableBigDecimalScore parseScore(String scoreString) {
var score = BendableBigDecimalScore.parseScore(scoreString);
if (score.hardLevelsSize() != hardLevelsSize) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + BendableBigDecimalScore.class.getSimpleName()
+ ") doesn't follow the correct pattern:"
+ " the hardLevelsSize (" + score.hardLevelsSize()
+ ") doesn't match the scoreDefinition's hardLevelsSize (" + hardLevelsSize + ").");
}
if (score.softLevelsSize() != softLevelsSize) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + BendableBigDecimalScore.class.getSimpleName()
+ ") doesn't follow the correct pattern:"
+ " the softLevelsSize (" + score.softLevelsSize()
+ ") doesn't match the scoreDefinition's softLevelsSize (" + softLevelsSize + ").");
}
return score;
}
@Override
public BendableBigDecimalScore fromLevelNumbers(Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
var hardScores = new BigDecimal[hardLevelsSize];
for (var i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (BigDecimal) levelNumbers[i];
}
var softScores = new BigDecimal[softLevelsSize];
for (var i = 0; i < softLevelsSize; i++) {
softScores[i] = (BigDecimal) levelNumbers[hardLevelsSize + i];
}
return BendableBigDecimalScore.of(hardScores, softScores);
}
public BendableBigDecimalScore createScore(BigDecimal... scores) {
var levelsSize = hardLevelsSize + softLevelsSize;
if (scores.length != levelsSize) {
throw new IllegalArgumentException("The scores (" + Arrays.toString(scores)
+ ")'s length (" + scores.length
+ ") is not levelsSize (" + levelsSize + ").");
}
return BendableBigDecimalScore.of(Arrays.copyOfRange(scores, 0, hardLevelsSize),
Arrays.copyOfRange(scores, hardLevelsSize, levelsSize));
}
@Override
public BendableBigDecimalScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend,
BendableBigDecimalScore score) {
throw new UnsupportedOperationException(
"BigDecimalScore does not support bounds because a BigDecimal cannot represent infinity.");
}
@Override
public BendableBigDecimalScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend,
BendableBigDecimalScore score) {
throw new UnsupportedOperationException(
"BigDecimalScore does not support bounds because a BigDecimal cannot represent infinity.");
}
@Override
public BendableBigDecimalScore divideBySanitizedDivisor(BendableBigDecimalScore dividend,
BendableBigDecimalScore divisor) {
var hardScores = new BigDecimal[hardLevelsSize];
for (var i = 0; i < hardLevelsSize; i++) {
hardScores[i] = divide(dividend.hardScore(i), sanitize(divisor.hardScore(i)));
}
var softScores = new BigDecimal[softLevelsSize];
for (var i = 0; i < softLevelsSize; i++) {
softScores[i] = divide(dividend.softScore(i), sanitize(divisor.softScore(i)));
}
var levels = Stream.concat(Arrays.stream(hardScores), Arrays.stream(softScores))
.toArray(BigDecimal[]::new);
return createScore(levels);
}
@Override
public Class<?> getNumericType() {
return BigDecimal.class;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/buildin/BendableLongScoreDefinition.java | package ai.timefold.solver.core.impl.score.buildin;
import java.util.Arrays;
import java.util.stream.LongStream;
import ai.timefold.solver.core.api.score.buildin.bendablelong.BendableLongScore;
import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel;
import ai.timefold.solver.core.impl.score.definition.AbstractBendableScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
public class BendableLongScoreDefinition extends AbstractBendableScoreDefinition<BendableLongScore> {
public BendableLongScoreDefinition(int hardLevelsSize, int softLevelsSize) {
super(hardLevelsSize, softLevelsSize);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Class<BendableLongScore> getScoreClass() {
return BendableLongScore.class;
}
@Override
public BendableLongScore getZeroScore() {
return BendableLongScore.zero(hardLevelsSize, softLevelsSize);
}
@Override
public final BendableLongScore getOneSoftestScore() {
return BendableLongScore.ofSoft(hardLevelsSize, softLevelsSize, softLevelsSize - 1, 1L);
}
@Override
public BendableLongScore parseScore(String scoreString) {
var score = BendableLongScore.parseScore(scoreString);
if (score.hardLevelsSize() != hardLevelsSize) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + BendableLongScore.class.getSimpleName()
+ ") doesn't follow the correct pattern:"
+ " the hardLevelsSize (" + score.hardLevelsSize()
+ ") doesn't match the scoreDefinition's hardLevelsSize (" + hardLevelsSize + ").");
}
if (score.softLevelsSize() != softLevelsSize) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + BendableLongScore.class.getSimpleName()
+ ") doesn't follow the correct pattern:"
+ " the softLevelsSize (" + score.softLevelsSize()
+ ") doesn't match the scoreDefinition's softLevelsSize (" + softLevelsSize + ").");
}
return score;
}
@Override
public BendableLongScore fromLevelNumbers(Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
var hardScores = new long[hardLevelsSize];
for (var i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (Long) levelNumbers[i];
}
var softScores = new long[softLevelsSize];
for (var i = 0; i < softLevelsSize; i++) {
softScores[i] = (Long) levelNumbers[hardLevelsSize + i];
}
return BendableLongScore.of(hardScores, softScores);
}
public BendableLongScore createScore(long... scores) {
var levelsSize = hardLevelsSize + softLevelsSize;
if (scores.length != levelsSize) {
throw new IllegalArgumentException("The scores (" + Arrays.toString(scores)
+ ")'s length (" + scores.length
+ ") is not levelsSize (" + levelsSize + ").");
}
return BendableLongScore.of(Arrays.copyOfRange(scores, 0, hardLevelsSize),
Arrays.copyOfRange(scores, hardLevelsSize, levelsSize));
}
@Override
public BendableLongScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend,
BendableLongScore score) {
var trendLevels = initializingScoreTrend.trendLevels();
var hardScores = new long[hardLevelsSize];
for (var i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (trendLevels[i] == InitializingScoreTrendLevel.ONLY_DOWN)
? score.hardScore(i)
: Long.MAX_VALUE;
}
var softScores = new long[softLevelsSize];
for (var i = 0; i < softLevelsSize; i++) {
softScores[i] = (trendLevels[hardLevelsSize + i] == InitializingScoreTrendLevel.ONLY_DOWN)
? score.softScore(i)
: Long.MAX_VALUE;
}
return BendableLongScore.of(hardScores, softScores);
}
@Override
public BendableLongScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend,
BendableLongScore score) {
var trendLevels = initializingScoreTrend.trendLevels();
var hardScores = new long[hardLevelsSize];
for (var i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (trendLevels[i] == InitializingScoreTrendLevel.ONLY_UP)
? score.hardScore(i)
: Long.MIN_VALUE;
}
var softScores = new long[softLevelsSize];
for (var i = 0; i < softLevelsSize; i++) {
softScores[i] = (trendLevels[hardLevelsSize + i] == InitializingScoreTrendLevel.ONLY_UP)
? score.softScore(i)
: Long.MIN_VALUE;
}
return BendableLongScore.of(hardScores, softScores);
}
@Override
public BendableLongScore divideBySanitizedDivisor(BendableLongScore dividend, BendableLongScore divisor) {
var hardScores = new long[hardLevelsSize];
for (var i = 0; i < hardLevelsSize; i++) {
hardScores[i] = divide(dividend.hardScore(i), sanitize(divisor.hardScore(i)));
}
var softScores = new long[softLevelsSize];
for (var i = 0; i < softLevelsSize; i++) {
softScores[i] = divide(dividend.softScore(i), sanitize(divisor.softScore(i)));
}
var levels = LongStream.concat(Arrays.stream(hardScores), Arrays.stream(softScores)).toArray();
return createScore(levels);
}
@Override
public Class<?> getNumericType() {
return long.class;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/buildin/BendableScoreDefinition.java | package ai.timefold.solver.core.impl.score.buildin;
import java.util.Arrays;
import java.util.stream.IntStream;
import ai.timefold.solver.core.api.score.buildin.bendable.BendableScore;
import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel;
import ai.timefold.solver.core.impl.score.definition.AbstractBendableScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
public class BendableScoreDefinition extends AbstractBendableScoreDefinition<BendableScore> {
public BendableScoreDefinition(int hardLevelsSize, int softLevelsSize) {
super(hardLevelsSize, softLevelsSize);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Class<BendableScore> getScoreClass() {
return BendableScore.class;
}
@Override
public BendableScore getZeroScore() {
return BendableScore.zero(hardLevelsSize, softLevelsSize);
}
@Override
public final BendableScore getOneSoftestScore() {
return BendableScore.ofSoft(hardLevelsSize, softLevelsSize, softLevelsSize - 1, 1);
}
@Override
public BendableScore parseScore(String scoreString) {
var score = BendableScore.parseScore(scoreString);
if (score.hardLevelsSize() != hardLevelsSize) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + BendableScore.class.getSimpleName()
+ ") doesn't follow the correct pattern:"
+ " the hardLevelsSize (" + score.hardLevelsSize()
+ ") doesn't match the scoreDefinition's hardLevelsSize (" + hardLevelsSize + ").");
}
if (score.softLevelsSize() != softLevelsSize) {
throw new IllegalArgumentException("The scoreString (" + scoreString
+ ") for the scoreClass (" + BendableScore.class.getSimpleName()
+ ") doesn't follow the correct pattern:"
+ " the softLevelsSize (" + score.softLevelsSize()
+ ") doesn't match the scoreDefinition's softLevelsSize (" + softLevelsSize + ").");
}
return score;
}
@Override
public BendableScore fromLevelNumbers(Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
var hardScores = new int[hardLevelsSize];
for (var i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (Integer) levelNumbers[i];
}
var softScores = new int[softLevelsSize];
for (var i = 0; i < softLevelsSize; i++) {
softScores[i] = (Integer) levelNumbers[hardLevelsSize + i];
}
return BendableScore.of(hardScores, softScores);
}
public BendableScore createScore(int... scores) {
var levelsSize = hardLevelsSize + softLevelsSize;
if (scores.length != levelsSize) {
throw new IllegalArgumentException("The scores (" + Arrays.toString(scores)
+ ")'s length (" + scores.length
+ ") is not levelsSize (" + levelsSize + ").");
}
return BendableScore.of(Arrays.copyOfRange(scores, 0, hardLevelsSize),
Arrays.copyOfRange(scores, hardLevelsSize, levelsSize));
}
@Override
public BendableScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, BendableScore score) {
var trendLevels = initializingScoreTrend.trendLevels();
var hardScores = new int[hardLevelsSize];
for (var i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (trendLevels[i] == InitializingScoreTrendLevel.ONLY_DOWN)
? score.hardScore(i)
: Integer.MAX_VALUE;
}
var softScores = new int[softLevelsSize];
for (var i = 0; i < softLevelsSize; i++) {
softScores[i] = (trendLevels[hardLevelsSize + i] == InitializingScoreTrendLevel.ONLY_DOWN)
? score.softScore(i)
: Integer.MAX_VALUE;
}
return BendableScore.of(hardScores, softScores);
}
@Override
public BendableScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, BendableScore score) {
var trendLevels = initializingScoreTrend.trendLevels();
var hardScores = new int[hardLevelsSize];
for (var i = 0; i < hardLevelsSize; i++) {
hardScores[i] = (trendLevels[i] == InitializingScoreTrendLevel.ONLY_UP)
? score.hardScore(i)
: Integer.MIN_VALUE;
}
var softScores = new int[softLevelsSize];
for (var i = 0; i < softLevelsSize; i++) {
softScores[i] = (trendLevels[hardLevelsSize + i] == InitializingScoreTrendLevel.ONLY_UP)
? score.softScore(i)
: Integer.MIN_VALUE;
}
return BendableScore.of(hardScores, softScores);
}
@Override
public BendableScore divideBySanitizedDivisor(BendableScore dividend, BendableScore divisor) {
var hardScores = new int[hardLevelsSize];
for (var i = 0; i < hardLevelsSize; i++) {
hardScores[i] = divide(dividend.hardScore(i), sanitize(divisor.hardScore(i)));
}
var softScores = new int[softLevelsSize];
for (var i = 0; i < softLevelsSize; i++) {
softScores[i] = divide(dividend.softScore(i), sanitize(divisor.softScore(i)));
}
var levels = IntStream.concat(Arrays.stream(hardScores), Arrays.stream(softScores)).toArray();
return createScore(levels);
}
@Override
public Class<?> getNumericType() {
return int.class;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/buildin/HardMediumSoftBigDecimalScoreDefinition.java | package ai.timefold.solver.core.impl.score.buildin;
import java.math.BigDecimal;
import java.util.Arrays;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoftbigdecimal.HardMediumSoftBigDecimalScore;
import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
public class HardMediumSoftBigDecimalScoreDefinition extends AbstractScoreDefinition<HardMediumSoftBigDecimalScore> {
public HardMediumSoftBigDecimalScoreDefinition() {
super(new String[] { "hard score", "medium score", "soft score" });
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getLevelsSize() {
return 3;
}
@Override
public int getFeasibleLevelsSize() {
return 1;
}
@Override
public Class<HardMediumSoftBigDecimalScore> getScoreClass() {
return HardMediumSoftBigDecimalScore.class;
}
@Override
public HardMediumSoftBigDecimalScore getZeroScore() {
return HardMediumSoftBigDecimalScore.ZERO;
}
@Override
public HardMediumSoftBigDecimalScore getOneSoftestScore() {
return HardMediumSoftBigDecimalScore.ONE_SOFT;
}
@Override
public HardMediumSoftBigDecimalScore parseScore(String scoreString) {
return HardMediumSoftBigDecimalScore.parseScore(scoreString);
}
@Override
public HardMediumSoftBigDecimalScore fromLevelNumbers(Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
return HardMediumSoftBigDecimalScore.of((BigDecimal) levelNumbers[0], (BigDecimal) levelNumbers[1],
(BigDecimal) levelNumbers[2]);
}
@Override
public HardMediumSoftBigDecimalScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend,
HardMediumSoftBigDecimalScore score) {
throw new UnsupportedOperationException(
"BigDecimalScore does not support bounds because a BigDecimal cannot represent infinity.");
}
@Override
public HardMediumSoftBigDecimalScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend,
HardMediumSoftBigDecimalScore score) {
throw new UnsupportedOperationException(
"BigDecimalScore does not support bounds because a BigDecimal cannot represent infinity.");
}
@Override
public HardMediumSoftBigDecimalScore divideBySanitizedDivisor(HardMediumSoftBigDecimalScore dividend,
HardMediumSoftBigDecimalScore divisor) {
var dividendHardScore = dividend.hardScore();
var divisorHardScore = sanitize(divisor.hardScore());
var dividendMediumScore = dividend.mediumScore();
var divisorMediumScore = sanitize(divisor.mediumScore());
var dividendSoftScore = dividend.softScore();
var divisorSoftScore = sanitize(divisor.softScore());
return fromLevelNumbers(
new Number[] {
divide(dividendHardScore, divisorHardScore),
divide(dividendMediumScore, divisorMediumScore),
divide(dividendSoftScore, divisorSoftScore)
});
}
@Override
public Class<?> getNumericType() {
return BigDecimal.class;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/buildin/HardMediumSoftLongScoreDefinition.java | package ai.timefold.solver.core.impl.score.buildin;
import java.util.Arrays;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoftlong.HardMediumSoftLongScore;
import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel;
import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
public class HardMediumSoftLongScoreDefinition extends AbstractScoreDefinition<HardMediumSoftLongScore> {
public HardMediumSoftLongScoreDefinition() {
super(new String[] { "hard score", "medium score", "soft score" });
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getLevelsSize() {
return 3;
}
@Override
public int getFeasibleLevelsSize() {
return 1;
}
@Override
public Class<HardMediumSoftLongScore> getScoreClass() {
return HardMediumSoftLongScore.class;
}
@Override
public HardMediumSoftLongScore getZeroScore() {
return HardMediumSoftLongScore.ZERO;
}
@Override
public HardMediumSoftLongScore getOneSoftestScore() {
return HardMediumSoftLongScore.ONE_SOFT;
}
@Override
public HardMediumSoftLongScore parseScore(String scoreString) {
return HardMediumSoftLongScore.parseScore(scoreString);
}
@Override
public HardMediumSoftLongScore fromLevelNumbers(Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
return HardMediumSoftLongScore.of((Long) levelNumbers[0], (Long) levelNumbers[1], (Long) levelNumbers[2]);
}
@Override
public HardMediumSoftLongScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend,
HardMediumSoftLongScore score) {
var trendLevels = initializingScoreTrend.trendLevels();
return HardMediumSoftLongScore.of(
trendLevels[0] == InitializingScoreTrendLevel.ONLY_DOWN ? score.hardScore() : Long.MAX_VALUE,
trendLevels[1] == InitializingScoreTrendLevel.ONLY_DOWN ? score.mediumScore() : Long.MAX_VALUE,
trendLevels[2] == InitializingScoreTrendLevel.ONLY_DOWN ? score.softScore() : Long.MAX_VALUE);
}
@Override
public HardMediumSoftLongScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend,
HardMediumSoftLongScore score) {
var trendLevels = initializingScoreTrend.trendLevels();
return HardMediumSoftLongScore.of(
trendLevels[0] == InitializingScoreTrendLevel.ONLY_UP ? score.hardScore() : Long.MIN_VALUE,
trendLevels[1] == InitializingScoreTrendLevel.ONLY_UP ? score.mediumScore() : Long.MIN_VALUE,
trendLevels[2] == InitializingScoreTrendLevel.ONLY_UP ? score.softScore() : Long.MIN_VALUE);
}
@Override
public HardMediumSoftLongScore divideBySanitizedDivisor(HardMediumSoftLongScore dividend,
HardMediumSoftLongScore divisor) {
var dividendHardScore = dividend.hardScore();
var divisorHardScore = sanitize(divisor.hardScore());
var dividendMediumScore = dividend.mediumScore();
var divisorMediumScore = sanitize(divisor.mediumScore());
var dividendSoftScore = dividend.softScore();
var divisorSoftScore = sanitize(divisor.softScore());
return fromLevelNumbers(
new Number[] {
divide(dividendHardScore, divisorHardScore),
divide(dividendMediumScore, divisorMediumScore),
divide(dividendSoftScore, divisorSoftScore)
});
}
@Override
public Class<?> getNumericType() {
return long.class;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/buildin/HardMediumSoftScoreDefinition.java | package ai.timefold.solver.core.impl.score.buildin;
import java.util.Arrays;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore;
import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel;
import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
public class HardMediumSoftScoreDefinition extends AbstractScoreDefinition<HardMediumSoftScore> {
public HardMediumSoftScoreDefinition() {
super(new String[] { "hard score", "medium score", "soft score" });
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getLevelsSize() {
return 3;
}
@Override
public int getFeasibleLevelsSize() {
return 1;
}
@Override
public Class<HardMediumSoftScore> getScoreClass() {
return HardMediumSoftScore.class;
}
@Override
public HardMediumSoftScore getZeroScore() {
return HardMediumSoftScore.ZERO;
}
@Override
public HardMediumSoftScore getOneSoftestScore() {
return HardMediumSoftScore.ONE_SOFT;
}
@Override
public HardMediumSoftScore parseScore(String scoreString) {
return HardMediumSoftScore.parseScore(scoreString);
}
@Override
public HardMediumSoftScore fromLevelNumbers(Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
return HardMediumSoftScore.of((Integer) levelNumbers[0], (Integer) levelNumbers[1], (Integer) levelNumbers[2]);
}
@Override
public HardMediumSoftScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend,
HardMediumSoftScore score) {
var trendLevels = initializingScoreTrend.trendLevels();
return HardMediumSoftScore.of(
trendLevels[0] == InitializingScoreTrendLevel.ONLY_DOWN ? score.hardScore() : Integer.MAX_VALUE,
trendLevels[1] == InitializingScoreTrendLevel.ONLY_DOWN ? score.mediumScore() : Integer.MAX_VALUE,
trendLevels[2] == InitializingScoreTrendLevel.ONLY_DOWN ? score.softScore() : Integer.MAX_VALUE);
}
@Override
public HardMediumSoftScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend,
HardMediumSoftScore score) {
var trendLevels = initializingScoreTrend.trendLevels();
return HardMediumSoftScore.of(
trendLevels[0] == InitializingScoreTrendLevel.ONLY_UP ? score.hardScore() : Integer.MIN_VALUE,
trendLevels[1] == InitializingScoreTrendLevel.ONLY_UP ? score.mediumScore() : Integer.MIN_VALUE,
trendLevels[2] == InitializingScoreTrendLevel.ONLY_UP ? score.softScore() : Integer.MIN_VALUE);
}
@Override
public HardMediumSoftScore divideBySanitizedDivisor(HardMediumSoftScore dividend, HardMediumSoftScore divisor) {
var dividendHardScore = dividend.hardScore();
var divisorHardScore = sanitize(divisor.hardScore());
var dividendMediumScore = dividend.mediumScore();
var divisorMediumScore = sanitize(divisor.mediumScore());
var dividendSoftScore = dividend.softScore();
var divisorSoftScore = sanitize(divisor.softScore());
return fromLevelNumbers(
new Number[] {
divide(dividendHardScore, divisorHardScore),
divide(dividendMediumScore, divisorMediumScore),
divide(dividendSoftScore, divisorSoftScore)
});
}
@Override
public Class<?> getNumericType() {
return int.class;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/buildin/HardSoftBigDecimalScoreDefinition.java | package ai.timefold.solver.core.impl.score.buildin;
import java.math.BigDecimal;
import java.util.Arrays;
import ai.timefold.solver.core.api.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScore;
import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
public class HardSoftBigDecimalScoreDefinition extends AbstractScoreDefinition<HardSoftBigDecimalScore> {
public HardSoftBigDecimalScoreDefinition() {
super(new String[] { "hard score", "soft score" });
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getLevelsSize() {
return 2;
}
@Override
public int getFeasibleLevelsSize() {
return 1;
}
@Override
public Class<HardSoftBigDecimalScore> getScoreClass() {
return HardSoftBigDecimalScore.class;
}
@Override
public HardSoftBigDecimalScore getZeroScore() {
return HardSoftBigDecimalScore.ZERO;
}
@Override
public HardSoftBigDecimalScore getOneSoftestScore() {
return HardSoftBigDecimalScore.ONE_SOFT;
}
@Override
public HardSoftBigDecimalScore parseScore(String scoreString) {
return HardSoftBigDecimalScore.parseScore(scoreString);
}
@Override
public HardSoftBigDecimalScore fromLevelNumbers(Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
return HardSoftBigDecimalScore.of((BigDecimal) levelNumbers[0], (BigDecimal) levelNumbers[1]);
}
@Override
public HardSoftBigDecimalScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend,
HardSoftBigDecimalScore score) {
throw new UnsupportedOperationException(
"BigDecimalScore does not support bounds because a BigDecimal cannot represent infinity.");
}
@Override
public HardSoftBigDecimalScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend,
HardSoftBigDecimalScore score) {
throw new UnsupportedOperationException(
"BigDecimalScore does not support bounds because a BigDecimal cannot represent infinity.");
}
@Override
public HardSoftBigDecimalScore divideBySanitizedDivisor(HardSoftBigDecimalScore dividend,
HardSoftBigDecimalScore divisor) {
var dividendHardScore = dividend.hardScore();
var divisorHardScore = sanitize(divisor.hardScore());
var dividendSoftScore = dividend.softScore();
var divisorSoftScore = sanitize(divisor.softScore());
return fromLevelNumbers(
new Number[] {
divide(dividendHardScore, divisorHardScore),
divide(dividendSoftScore, divisorSoftScore)
});
}
@Override
public Class<?> getNumericType() {
return BigDecimal.class;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/buildin/HardSoftLongScoreDefinition.java | package ai.timefold.solver.core.impl.score.buildin;
import java.util.Arrays;
import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel;
import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
public class HardSoftLongScoreDefinition extends AbstractScoreDefinition<HardSoftLongScore> {
public HardSoftLongScoreDefinition() {
super(new String[] { "hard score", "soft score" });
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getLevelsSize() {
return 2;
}
@Override
public int getFeasibleLevelsSize() {
return 1;
}
@Override
public Class<HardSoftLongScore> getScoreClass() {
return HardSoftLongScore.class;
}
@Override
public HardSoftLongScore getZeroScore() {
return HardSoftLongScore.ZERO;
}
@Override
public HardSoftLongScore getOneSoftestScore() {
return HardSoftLongScore.ONE_SOFT;
}
@Override
public HardSoftLongScore parseScore(String scoreString) {
return HardSoftLongScore.parseScore(scoreString);
}
@Override
public HardSoftLongScore fromLevelNumbers(Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
return HardSoftLongScore.of((Long) levelNumbers[0], (Long) levelNumbers[1]);
}
@Override
public HardSoftLongScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend,
HardSoftLongScore score) {
var trendLevels = initializingScoreTrend.trendLevels();
return HardSoftLongScore.of(
trendLevels[0] == InitializingScoreTrendLevel.ONLY_DOWN ? score.hardScore() : Long.MAX_VALUE,
trendLevels[1] == InitializingScoreTrendLevel.ONLY_DOWN ? score.softScore() : Long.MAX_VALUE);
}
@Override
public HardSoftLongScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend,
HardSoftLongScore score) {
var trendLevels = initializingScoreTrend.trendLevels();
return HardSoftLongScore.of(trendLevels[0] == InitializingScoreTrendLevel.ONLY_UP ? score.hardScore() : Long.MIN_VALUE,
trendLevels[1] == InitializingScoreTrendLevel.ONLY_UP ? score.softScore() : Long.MIN_VALUE);
}
@Override
public HardSoftLongScore divideBySanitizedDivisor(HardSoftLongScore dividend, HardSoftLongScore divisor) {
var dividendHardScore = dividend.hardScore();
var divisorHardScore = sanitize(divisor.hardScore());
var dividendSoftScore = dividend.softScore();
var divisorSoftScore = sanitize(divisor.softScore());
return fromLevelNumbers(
new Number[] {
divide(dividendHardScore, divisorHardScore),
divide(dividendSoftScore, divisorSoftScore)
});
}
@Override
public Class<?> getNumericType() {
return long.class;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/buildin/HardSoftScoreDefinition.java | package ai.timefold.solver.core.impl.score.buildin;
import java.util.Arrays;
import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel;
import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
public class HardSoftScoreDefinition extends AbstractScoreDefinition<HardSoftScore> {
public HardSoftScoreDefinition() {
super(new String[] { "hard score", "soft score" });
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getFeasibleLevelsSize() {
return 1;
}
@Override
public Class<HardSoftScore> getScoreClass() {
return HardSoftScore.class;
}
@Override
public HardSoftScore getZeroScore() {
return HardSoftScore.ZERO;
}
@Override
public HardSoftScore getOneSoftestScore() {
return HardSoftScore.ONE_SOFT;
}
@Override
public HardSoftScore parseScore(String scoreString) {
return HardSoftScore.parseScore(scoreString);
}
@Override
public HardSoftScore fromLevelNumbers(Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
return HardSoftScore.of((Integer) levelNumbers[0], (Integer) levelNumbers[1]);
}
@Override
public HardSoftScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, HardSoftScore score) {
var trendLevels = initializingScoreTrend.trendLevels();
return HardSoftScore.of(trendLevels[0] == InitializingScoreTrendLevel.ONLY_DOWN ? score.hardScore() : Integer.MAX_VALUE,
trendLevels[1] == InitializingScoreTrendLevel.ONLY_DOWN ? score.softScore() : Integer.MAX_VALUE);
}
@Override
public HardSoftScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, HardSoftScore score) {
var trendLevels = initializingScoreTrend.trendLevels();
return HardSoftScore.of(trendLevels[0] == InitializingScoreTrendLevel.ONLY_UP ? score.hardScore() : Integer.MIN_VALUE,
trendLevels[1] == InitializingScoreTrendLevel.ONLY_UP ? score.softScore() : Integer.MIN_VALUE);
}
@Override
public HardSoftScore divideBySanitizedDivisor(HardSoftScore dividend, HardSoftScore divisor) {
var dividendHardScore = dividend.hardScore();
var divisorHardScore = sanitize(divisor.hardScore());
var dividendSoftScore = dividend.softScore();
var divisorSoftScore = sanitize(divisor.softScore());
return fromLevelNumbers(
new Number[] {
divide(dividendHardScore, divisorHardScore),
divide(dividendSoftScore, divisorSoftScore)
});
}
@Override
public Class<?> getNumericType() {
return int.class;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/buildin/SimpleBigDecimalScoreDefinition.java | package ai.timefold.solver.core.impl.score.buildin;
import java.math.BigDecimal;
import java.util.Arrays;
import ai.timefold.solver.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore;
import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
public class SimpleBigDecimalScoreDefinition extends AbstractScoreDefinition<SimpleBigDecimalScore> {
public SimpleBigDecimalScoreDefinition() {
super(new String[] { "score" });
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getLevelsSize() {
return 1;
}
@Override
public int getFeasibleLevelsSize() {
return 0;
}
@Override
public Class<SimpleBigDecimalScore> getScoreClass() {
return SimpleBigDecimalScore.class;
}
@Override
public SimpleBigDecimalScore getZeroScore() {
return SimpleBigDecimalScore.ZERO;
}
@Override
public SimpleBigDecimalScore getOneSoftestScore() {
return SimpleBigDecimalScore.ONE;
}
@Override
public SimpleBigDecimalScore parseScore(String scoreString) {
return SimpleBigDecimalScore.parseScore(scoreString);
}
@Override
public SimpleBigDecimalScore fromLevelNumbers(Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
return SimpleBigDecimalScore.of((BigDecimal) levelNumbers[0]);
}
@Override
public SimpleBigDecimalScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend,
SimpleBigDecimalScore score) {
throw new UnsupportedOperationException(
"BigDecimalScore does not support bounds because a BigDecimal cannot represent infinity.");
}
@Override
public SimpleBigDecimalScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend,
SimpleBigDecimalScore score) {
throw new UnsupportedOperationException(
"BigDecimalScore does not support bounds because a BigDecimal cannot represent infinity.");
}
@Override
public SimpleBigDecimalScore divideBySanitizedDivisor(SimpleBigDecimalScore dividend,
SimpleBigDecimalScore divisor) {
var dividendScore = dividend.score();
var divisorScore = sanitize(divisor.score());
return fromLevelNumbers(
new Number[] {
divide(dividendScore, divisorScore)
});
}
@Override
public Class<?> getNumericType() {
return BigDecimal.class;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/buildin/SimpleLongScoreDefinition.java | package ai.timefold.solver.core.impl.score.buildin;
import java.util.Arrays;
import ai.timefold.solver.core.api.score.buildin.simplelong.SimpleLongScore;
import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel;
import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
public class SimpleLongScoreDefinition extends AbstractScoreDefinition<SimpleLongScore> {
public SimpleLongScoreDefinition() {
super(new String[] { "score" });
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getFeasibleLevelsSize() {
return 0;
}
@Override
public Class<SimpleLongScore> getScoreClass() {
return SimpleLongScore.class;
}
@Override
public SimpleLongScore getZeroScore() {
return SimpleLongScore.ZERO;
}
@Override
public SimpleLongScore getOneSoftestScore() {
return SimpleLongScore.ONE;
}
@Override
public SimpleLongScore parseScore(String scoreString) {
return SimpleLongScore.parseScore(scoreString);
}
@Override
public SimpleLongScore fromLevelNumbers(Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
return SimpleLongScore.of((Long) levelNumbers[0]);
}
@Override
public SimpleLongScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, SimpleLongScore score) {
var trendLevels = initializingScoreTrend.trendLevels();
return SimpleLongScore.of(trendLevels[0] == InitializingScoreTrendLevel.ONLY_DOWN ? score.score() : Long.MAX_VALUE);
}
@Override
public SimpleLongScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, SimpleLongScore score) {
var trendLevels = initializingScoreTrend.trendLevels();
return SimpleLongScore.of(trendLevels[0] == InitializingScoreTrendLevel.ONLY_UP ? score.score() : Long.MIN_VALUE);
}
@Override
public SimpleLongScore divideBySanitizedDivisor(SimpleLongScore dividend, SimpleLongScore divisor) {
var dividendScore = dividend.score();
var divisorScore = sanitize(divisor.score());
return fromLevelNumbers(
new Number[] {
divide(dividendScore, divisorScore)
});
}
@Override
public Class<?> getNumericType() {
return long.class;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/buildin/SimpleScoreDefinition.java | package ai.timefold.solver.core.impl.score.buildin;
import java.util.Arrays;
import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore;
import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel;
import ai.timefold.solver.core.impl.score.definition.AbstractScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
public class SimpleScoreDefinition extends AbstractScoreDefinition<SimpleScore> {
public SimpleScoreDefinition() {
super(new String[] { "score" });
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getLevelsSize() {
return 1;
}
@Override
public int getFeasibleLevelsSize() {
return 0;
}
@Override
public Class<SimpleScore> getScoreClass() {
return SimpleScore.class;
}
@Override
public SimpleScore getZeroScore() {
return SimpleScore.ZERO;
}
@Override
public SimpleScore getOneSoftestScore() {
return SimpleScore.ONE;
}
@Override
public SimpleScore parseScore(String scoreString) {
return SimpleScore.parseScore(scoreString);
}
@Override
public SimpleScore fromLevelNumbers(Number[] levelNumbers) {
if (levelNumbers.length != getLevelsSize()) {
throw new IllegalStateException("The levelNumbers (" + Arrays.toString(levelNumbers)
+ ")'s length (" + levelNumbers.length + ") must equal the levelSize (" + getLevelsSize() + ").");
}
return SimpleScore.of((Integer) levelNumbers[0]);
}
@Override
public SimpleScore buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, SimpleScore score) {
var trendLevels = initializingScoreTrend.trendLevels();
return SimpleScore.of(trendLevels[0] == InitializingScoreTrendLevel.ONLY_DOWN ? score.score() : Integer.MAX_VALUE);
}
@Override
public SimpleScore buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, SimpleScore score) {
var trendLevels = initializingScoreTrend.trendLevels();
return SimpleScore.of(trendLevels[0] == InitializingScoreTrendLevel.ONLY_UP ? score.score() : Integer.MIN_VALUE);
}
@Override
public SimpleScore divideBySanitizedDivisor(SimpleScore dividend, SimpleScore divisor) {
var dividendScore = dividend.score();
var divisorScore = sanitize(divisor.score());
return fromLevelNumbers(
new Number[] {
divide(dividendScore, divisorScore)
});
}
@Override
public Class<?> getNumericType() {
return int.class;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/constraint/ConstraintMatchPolicy.java | package ai.timefold.solver.core.impl.score.constraint;
import ai.timefold.solver.core.api.solver.ScoreAnalysisFetchPolicy;
import org.jspecify.annotations.NullMarked;
/**
* Determines whether constraint match is enabled and whether constraint match justification is enabled.
*
* @see ai.timefold.solver.core.api.score.constraint.ConstraintMatch
* @see ai.timefold.solver.core.api.score.stream.ConstraintJustification
*/
@NullMarked
public enum ConstraintMatchPolicy {
DISABLED(false, false),
ENABLED_WITHOUT_JUSTIFICATIONS(true, false),
ENABLED(true, true);
/**
* To achieve the most performance out of the underlying solver,
* the policy should match whatever policy was used for score analysis.
* For example, if the fetch policy specifies that only match counts are necessary and not matches themselves
* ({@link ScoreAnalysisFetchPolicy#FETCH_MATCH_COUNT}),
* we can configure the solver to not produce justifications ({@link #ENABLED_WITHOUT_JUSTIFICATIONS}).
*
* @param scoreAnalysisFetchPolicy
* @return Match policy best suited for the given fetch policy.
*/
public static ConstraintMatchPolicy match(ScoreAnalysisFetchPolicy scoreAnalysisFetchPolicy) {
return switch (scoreAnalysisFetchPolicy) {
case FETCH_MATCH_COUNT, FETCH_SHALLOW -> ENABLED_WITHOUT_JUSTIFICATIONS;
case FETCH_ALL -> ENABLED;
};
}
private final boolean enabled;
private final boolean justificationEnabled;
ConstraintMatchPolicy(boolean enabled, boolean justificationEnabled) {
this.enabled = enabled;
this.justificationEnabled = justificationEnabled;
}
public boolean isEnabled() {
return enabled;
}
public boolean isJustificationEnabled() {
return justificationEnabled;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/constraint/DefaultConstraintMatchTotal.java | package ai.timefold.solver.core.impl.score.constraint;
import static java.util.Objects.requireNonNull;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatch;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal;
import ai.timefold.solver.core.api.score.constraint.ConstraintRef;
import ai.timefold.solver.core.api.score.stream.Constraint;
import ai.timefold.solver.core.api.score.stream.ConstraintJustification;
import ai.timefold.solver.core.api.score.stream.DefaultConstraintJustification;
import ai.timefold.solver.core.api.solver.SolutionManager;
import org.jspecify.annotations.NonNull;
/**
* If possible, prefer using {@link SolutionManager#analyze(Object)} instead.
*
* @param <Score_>
*/
public final class DefaultConstraintMatchTotal<Score_ extends Score<Score_>> implements ConstraintMatchTotal<Score_>,
Comparable<DefaultConstraintMatchTotal<Score_>> {
private final ConstraintRef constraintRef;
private final Score_ constraintWeight;
private final Set<ConstraintMatch<Score_>> constraintMatchSet = new LinkedHashSet<>();
private Score_ score;
/**
* @deprecated Prefer {@link #DefaultConstraintMatchTotal(ConstraintRef, Score_)}.
*/
@Deprecated(forRemoval = true, since = "1.4.0")
public DefaultConstraintMatchTotal(String constraintPackage, String constraintName) {
this(ConstraintRef.of(constraintPackage, constraintName));
}
/**
*
* @deprecated Prefer {@link #DefaultConstraintMatchTotal(ConstraintRef, Score_)}.
*/
@Deprecated(forRemoval = true, since = "1.5.0")
public DefaultConstraintMatchTotal(ConstraintRef constraintRef) {
this.constraintRef = requireNonNull(constraintRef);
this.constraintWeight = null;
}
/**
* @deprecated Prefer {@link #DefaultConstraintMatchTotal(ConstraintRef, Score_)}.
*/
@Deprecated(forRemoval = true, since = "1.4.0")
public DefaultConstraintMatchTotal(Constraint constraint, Score_ constraintWeight) {
this(constraint.getConstraintRef(), constraintWeight);
}
/**
* @deprecated Prefer {@link #DefaultConstraintMatchTotal(ConstraintRef, Score_)}.
*/
@Deprecated(forRemoval = true, since = "1.4.0")
public DefaultConstraintMatchTotal(String constraintPackage, String constraintName, Score_ constraintWeight) {
this(ConstraintRef.of(constraintPackage, constraintName), constraintWeight);
}
public DefaultConstraintMatchTotal(ConstraintRef constraintRef, Score_ constraintWeight) {
this.constraintRef = requireNonNull(constraintRef);
this.constraintWeight = requireNonNull(constraintWeight);
this.score = constraintWeight.zero();
}
@Override
public @NonNull ConstraintRef getConstraintRef() {
return constraintRef;
}
@Override
public @NonNull Score_ getConstraintWeight() {
return constraintWeight;
}
@Override
public @NonNull Set<ConstraintMatch<Score_>> getConstraintMatchSet() {
return constraintMatchSet;
}
@Override
public @NonNull Score_ getScore() {
return score;
}
// ************************************************************************
// Worker methods
// ************************************************************************
/**
* Creates a {@link ConstraintMatch} and adds it to the collection returned by {@link #getConstraintMatchSet()}.
* It will use {@link DefaultConstraintJustification},
* whose {@link DefaultConstraintJustification#getFacts()} method will return the given list of justifications.
* Additionally, the constraint match will indict the objects in the given list of justifications.
*
* @param justifications never null, never empty
* @param score never null
* @return never null
*/
public ConstraintMatch<Score_> addConstraintMatch(List<Object> justifications, Score_ score) {
return addConstraintMatch(DefaultConstraintJustification.of(score, justifications), justifications, score);
}
/**
* Creates a {@link ConstraintMatch} and adds it to the collection returned by {@link #getConstraintMatchSet()}.
* It will be justified with the provided {@link ConstraintJustification}.
* Additionally, the constraint match will indict the objects in the given list of indicted objects.
*
* @param indictedObjects never null, may be empty
* @param score never null
* @return never null
*/
public ConstraintMatch<Score_> addConstraintMatch(ConstraintJustification justification, Collection<Object> indictedObjects,
Score_ score) {
ConstraintMatch<Score_> constraintMatch = new ConstraintMatch<>(constraintRef, justification, indictedObjects, score);
addConstraintMatch(constraintMatch);
return constraintMatch;
}
public void addConstraintMatch(ConstraintMatch<Score_> constraintMatch) {
Score_ constraintMatchScore = constraintMatch.getScore();
this.score = this.score == null ? constraintMatchScore : this.score.add(constraintMatchScore);
constraintMatchSet.add(constraintMatch);
}
public void removeConstraintMatch(ConstraintMatch<Score_> constraintMatch) {
score = score.subtract(constraintMatch.getScore());
boolean removed = constraintMatchSet.remove(constraintMatch);
if (!removed) {
throw new IllegalStateException("The constraintMatchTotal (" + this
+ ") could not remove constraintMatch (" + constraintMatch
+ ") from its constraintMatchSet (" + constraintMatchSet + ").");
}
}
// ************************************************************************
// Infrastructure methods
// ************************************************************************
@Override
public int compareTo(DefaultConstraintMatchTotal<Score_> other) {
return constraintRef.compareTo(other.constraintRef);
}
@Override
public boolean equals(Object o) {
if (o instanceof DefaultConstraintMatchTotal<?> other) {
return constraintRef.equals(other.constraintRef);
}
return false;
}
@Override
public int hashCode() {
return constraintRef.hashCode();
}
@Override
public String toString() {
return constraintRef + "=" + score;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/constraint/DefaultIndictment.java | package ai.timefold.solver.core.impl.score.constraint;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatch;
import ai.timefold.solver.core.api.score.constraint.Indictment;
import ai.timefold.solver.core.api.score.stream.ConstraintJustification;
import ai.timefold.solver.core.impl.util.CollectionUtils;
import org.jspecify.annotations.NonNull;
public final class DefaultIndictment<Score_ extends Score<Score_>> implements Indictment<Score_> {
private final Object indictedObject;
private final Set<ConstraintMatch<Score_>> constraintMatchSet = new LinkedHashSet<>();
private List<ConstraintJustification> constraintJustificationList;
private Score_ score;
public DefaultIndictment(Object indictedObject, Score_ zeroScore) {
this.indictedObject = indictedObject;
this.score = zeroScore;
}
@Override
public <IndictedObject_> @NonNull IndictedObject_ getIndictedObject() {
return (IndictedObject_) indictedObject;
}
@Override
public @NonNull Set<ConstraintMatch<Score_>> getConstraintMatchSet() {
return constraintMatchSet;
}
@Override
public @NonNull List<ConstraintJustification> getJustificationList() {
if (constraintJustificationList == null) {
constraintJustificationList = buildConstraintJustificationList();
}
return constraintJustificationList;
}
private List<ConstraintJustification> buildConstraintJustificationList() {
var constraintMatchSetSize = constraintMatchSet.size();
switch (constraintMatchSetSize) {
case 0 -> {
return Collections.emptyList();
}
case 1 -> {
return Collections.singletonList(constraintMatchSet.iterator().next().getJustification());
}
default -> {
Set<ConstraintJustification> justificationSet = CollectionUtils.newLinkedHashSet(constraintMatchSetSize);
for (ConstraintMatch<Score_> constraintMatch : constraintMatchSet) {
justificationSet.add(constraintMatch.getJustification());
}
return CollectionUtils.toDistinctList(justificationSet);
}
}
}
@Override
public @NonNull Score_ getScore() {
return score;
}
// ************************************************************************
// Worker methods
// ************************************************************************
public void addConstraintMatch(ConstraintMatch<Score_> constraintMatch) {
boolean added = addConstraintMatchWithoutFail(constraintMatch);
if (!added) {
throw new IllegalStateException("The indictment (" + this
+ ") could not add constraintMatch (" + constraintMatch
+ ") to its constraintMatchSet (" + constraintMatchSet + ").");
}
}
public boolean addConstraintMatchWithoutFail(ConstraintMatch<Score_> constraintMatch) {
boolean added = constraintMatchSet.add(constraintMatch);
if (added) {
score = score.add(constraintMatch.getScore());
constraintJustificationList = null; // Rebuild later.
}
return added;
}
public void removeConstraintMatch(ConstraintMatch<Score_> constraintMatch) {
score = score.subtract(constraintMatch.getScore());
boolean removed = constraintMatchSet.remove(constraintMatch);
if (!removed) {
throw new IllegalStateException("The indictment (" + this
+ ") could not remove constraintMatch (" + constraintMatch
+ ") from its constraintMatchSet (" + constraintMatchSet + ").");
}
constraintJustificationList = null; // Rebuild later.
}
// ************************************************************************
// Infrastructure methods
// ************************************************************************
@Override
public boolean equals(Object o) {
if (o instanceof DefaultIndictment other) {
return indictedObject.equals(other.indictedObject);
}
return false;
}
@Override
public int hashCode() {
return indictedObject.hashCode();
}
@Override
public String toString() {
return indictedObject + "=" + score;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/definition/AbstractBendableScoreDefinition.java | package ai.timefold.solver.core.impl.score.definition;
import ai.timefold.solver.core.api.score.IBendableScore;
import ai.timefold.solver.core.api.score.Score;
public abstract class AbstractBendableScoreDefinition<Score_ extends Score<Score_>>
extends AbstractScoreDefinition<Score_>
implements ScoreDefinition<Score_> {
protected static String[] generateLevelLabels(int hardLevelsSize, int softLevelsSize) {
if (hardLevelsSize < 0 || softLevelsSize < 0) {
throw new IllegalArgumentException("The hardLevelsSize (" + hardLevelsSize
+ ") and softLevelsSize (" + softLevelsSize + ") should be positive.");
}
var levelLabels = new String[hardLevelsSize + softLevelsSize];
for (var i = 0; i < levelLabels.length; i++) {
String labelPrefix;
if (i < hardLevelsSize) {
labelPrefix = "hard " + i;
} else {
labelPrefix = "soft " + (i - hardLevelsSize);
}
levelLabels[i] = labelPrefix + " score";
}
return levelLabels;
}
protected final int hardLevelsSize;
protected final int softLevelsSize;
public AbstractBendableScoreDefinition(int hardLevelsSize, int softLevelsSize) {
super(generateLevelLabels(hardLevelsSize, softLevelsSize));
this.hardLevelsSize = hardLevelsSize;
this.softLevelsSize = softLevelsSize;
}
public int getHardLevelsSize() {
return hardLevelsSize;
}
public int getSoftLevelsSize() {
return softLevelsSize;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public int getLevelsSize() {
return hardLevelsSize + softLevelsSize;
}
@Override
public int getFeasibleLevelsSize() {
return hardLevelsSize;
}
@Override
public boolean isCompatibleArithmeticArgument(Score_ score) {
if (super.isCompatibleArithmeticArgument(score)) {
var bendableScore = (IBendableScore<?>) score;
return getLevelsSize() == bendableScore.levelsSize()
&& getHardLevelsSize() == bendableScore.hardLevelsSize()
&& getSoftLevelsSize() == bendableScore.softLevelsSize();
}
return false;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/definition/AbstractScoreDefinition.java | package ai.timefold.solver.core.impl.score.definition;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.score.buildin.HardSoftScoreDefinition;
/**
* Abstract superclass for {@link ScoreDefinition}.
*
* @see ScoreDefinition
* @see HardSoftScoreDefinition
*/
public abstract class AbstractScoreDefinition<Score_ extends Score<Score_>>
implements ScoreDefinition<Score_> {
private final String[] levelLabels;
protected static int sanitize(int number) {
return number == 0 ? 1 : number;
}
protected static long sanitize(long number) {
return number == 0L ? 1L : number;
}
protected static BigDecimal sanitize(BigDecimal number) {
return number.signum() == 0 ? BigDecimal.ONE : number;
}
protected static int divide(int dividend, int divisor) {
return (int) Math.floor(divide(dividend, (double) divisor));
}
protected static long divide(long dividend, long divisor) {
return (long) Math.floor(divide(dividend, (double) divisor));
}
protected static double divide(double dividend, double divisor) {
return dividend / divisor;
}
protected static BigDecimal divide(BigDecimal dividend, BigDecimal divisor) {
return dividend.divide(divisor, dividend.scale() - divisor.scale(), RoundingMode.FLOOR);
}
/**
* @param levelLabels never null, as defined by {@link ScoreDefinition#getLevelLabels()}
*/
public AbstractScoreDefinition(String[] levelLabels) {
this.levelLabels = levelLabels;
}
@Override
public int getLevelsSize() {
return levelLabels.length;
}
@Override
public String[] getLevelLabels() {
return levelLabels;
}
@Override
public boolean isCompatibleArithmeticArgument(Score_ score) {
return Objects.equals(score.getClass(), getScoreClass());
}
@Override
public String toString() {
return getClass().getSimpleName();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/definition/ScoreDefinition.java | package ai.timefold.solver.core.impl.score.definition;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore;
import ai.timefold.solver.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore;
import ai.timefold.solver.core.impl.score.buildin.HardSoftScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
/**
* A ScoreDefinition knows how to compare {@link Score}s and what the perfect maximum/minimum {@link Score} is.
*
* @see AbstractScoreDefinition
* @see HardSoftScoreDefinition
* @param <Score_> the {@link Score} type
*/
public interface ScoreDefinition<Score_ extends Score<Score_>> {
/**
* Returns the length of {@link Score#toLevelNumbers()} for every {@link Score} of this definition.
* For example: returns 2 on {@link HardSoftScoreDefinition}.
*
* @return at least 1
*/
int getLevelsSize();
/**
* Returns the number of levels of {@link Score#toLevelNumbers()}.
* that are used to determine {@link Score#isFeasible()}.
*
* @return at least 0, at most {@link #getLevelsSize()}
*/
int getFeasibleLevelsSize();
/**
* Returns a label for each score level. Each label includes the suffix "score" and must start in lower case.
* For example: returns {@code {"hard score", "soft score "}} on {@link HardSoftScoreDefinition}.
*
* @return never null, array with length of {@link #getLevelsSize()}, each element is never null
*/
String[] getLevelLabels();
/**
* Returns the {@link Class} of the actual {@link Score} implementation.
* For example: returns {@link HardSoftScore HardSoftScore.class} on {@link HardSoftScoreDefinition}.
*
* @return never null
*/
Class<Score_> getScoreClass();
/**
* The score that represents zero.
*
* @return never null
*/
Score_ getZeroScore();
/**
* The score that represents the softest possible one.
*
* @return never null
*/
Score_ getOneSoftestScore();
/**
* @param score never null
* @return true if the score is higher or equal to {@link #getZeroScore()}
*/
default boolean isPositiveOrZero(Score_ score) {
return score.compareTo(getZeroScore()) >= 0;
}
/**
* @param score never null
* @return true if the score is lower or equal to {@link #getZeroScore()}
*/
default boolean isNegativeOrZero(Score_ score) {
return score.compareTo(getZeroScore()) <= 0;
}
/**
* Parses the {@link String} and returns a {@link Score}.
*
* @param scoreString never null
* @return never null
*/
Score_ parseScore(String scoreString);
/**
* The opposite of {@link Score#toLevelNumbers()}.
*
* @param levelNumbers never null
* @return never null
*/
Score_ fromLevelNumbers(Number[] levelNumbers);
/**
* Builds a {@link Score} which is equal or better than any other {@link Score} with more variables initialized
* (while the already variables don't change).
*
* @param initializingScoreTrend never null, with {@link InitializingScoreTrend#getLevelsSize()}
* equal to {@link #getLevelsSize()}.
* @param score never null, considered initialized
* @return never null
*/
Score_ buildOptimisticBound(InitializingScoreTrend initializingScoreTrend, Score_ score);
/**
* Builds a {@link Score} which is equal or worse than any other {@link Score} with more variables initialized
* (while the already variables don't change).
*
* @param initializingScoreTrend never null, with {@link InitializingScoreTrend#getLevelsSize()}
* equal to {@link #getLevelsSize()}.
* @param score never null, considered initialized
* @return never null
*/
Score_ buildPessimisticBound(InitializingScoreTrend initializingScoreTrend, Score_ score);
/**
* Return {@link Score} whose every level is the result of dividing the matching levels in this and the divisor.
* When rounding is needed, it is floored (as defined by {@link Math#floor(double)}).
* <p>
* If any of the levels in the divisor are equal to zero, the method behaves as if they were equal to one instead.
*
* @param divisor value by which this Score is to be divided
* @return this / divisor
*/
Score_ divideBySanitizedDivisor(Score_ dividend, Score_ divisor);
/**
* @param score never null
* @return true if the otherScore is accepted as a parameter of {@link Score#add(Score)},
* {@link Score#subtract(Score)} and {@link Score#compareTo(Object)} for scores of this score definition.
*/
boolean isCompatibleArithmeticArgument(Score_ score);
/**
* Return the type of number that the score implementation operates on.
* Examples:
* <ul>
* <li>int.class for {@link SimpleScore}</li>
* <li>BigDecimal.class for {@link SimpleBigDecimalScore}</li>
* </ul>
*
* @return never null
*/
Class<?> getNumericType();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/director/AbstractScoreDirector.java | package ai.timefold.solver.core.impl.score.director;
import static java.util.Objects.requireNonNull;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner;
import ai.timefold.solver.core.api.domain.variable.VariableListener;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.analysis.ConstraintAnalysis;
import ai.timefold.solver.core.api.score.analysis.MatchAnalysis;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.api.solver.ScoreAnalysisFetchPolicy;
import ai.timefold.solver.core.api.solver.change.ProblemChange;
import ai.timefold.solver.core.api.solver.change.ProblemChangeDirector;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.lookup.LookUpManager;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.listener.support.VariableListenerSupport;
import ai.timefold.solver.core.impl.domain.variable.listener.support.violation.SolutionTracker;
import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
import ai.timefold.solver.core.impl.move.MoveRepository;
import ai.timefold.solver.core.impl.move.MoveStreamsBasedMoveRepository;
import ai.timefold.solver.core.impl.move.director.MoveDirector;
import ai.timefold.solver.core.impl.phase.scope.SolverLifecyclePoint;
import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
import ai.timefold.solver.core.impl.solver.exception.CloningCorruptionException;
import ai.timefold.solver.core.impl.solver.exception.ScoreCorruptionException;
import ai.timefold.solver.core.impl.solver.exception.UndoScoreCorruptionException;
import ai.timefold.solver.core.impl.solver.exception.VariableCorruptionException;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
import ai.timefold.solver.core.preview.api.move.Move;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract superclass for {@link ScoreDirector}.
* <p>
* Implementation note: Extending classes should follow these guidelines:
* <ul>
* <li>{@link #setWorkingSolutionWithoutUpdatingShadows(Object)} should delegate to
* {@link #setWorkingSolutionWithoutUpdatingShadows(Object, Consumer)}</li>
* <li>before* method: last statement should be a call to the super method</li>
* <li>after* method: first statement should be a call to the super method</li>
* </ul>
*/
public abstract class AbstractScoreDirector<Solution_, Score_ extends Score<Score_>, Factory_ extends AbstractScoreDirectorFactory<Solution_, Score_, Factory_>>
implements InnerScoreDirector<Solution_, Score_>, Cloneable {
private static final int CONSTRAINT_MATCH_DISPLAY_LIMIT = 8;
protected final Logger logger = LoggerFactory.getLogger(getClass());
private final boolean lookUpEnabled;
private final LookUpManager lookUpManager;
protected final ConstraintMatchPolicy constraintMatchPolicy;
protected final Factory_ scoreDirectorFactory;
private final VariableDescriptorCache<Solution_> variableDescriptorCache;
protected final VariableListenerSupport<Solution_> variableListenerSupport;
private boolean expectShadowVariablesInCorrectState;
private long workingEntityListRevision = 0L;
private int workingGenuineEntityCount = 0;
private boolean allChangesWillBeUndoneBeforeStepEnds = false;
private long calculationCount = 0L;
protected Solution_ workingSolution;
private int workingInitScore = 0;
private final @Nullable SolutionTracker<Solution_> solutionTracker; // Null when tracking disabled.
/**
* Must never be shared between score directors,
* because it contains state based on the current clone of the working solution.
* Creating these value range caches is expensive,
* but they are only created on first access to each
* and operations which do not perform moves do not require them.
*/
private final ValueRangeManager<Solution_> valueRangeManager;
private final MoveDirector<Solution_, Score_> moveDirector = new MoveDirector<>(this);
private @Nullable MoveRepository<Solution_> moveRepository;
private final ListVariableStateSupply<Solution_> listVariableStateSupply; // Null when no list variable.
protected AbstractScoreDirector(AbstractScoreDirectorBuilder<Solution_, Score_, Factory_, ?> builder) {
this.scoreDirectorFactory = builder.scoreDirectorFactory;
var solutionDescriptor = this.scoreDirectorFactory.getSolutionDescriptor();
this.lookUpEnabled = builder.lookUpEnabled;
this.lookUpManager = lookUpEnabled
? new LookUpManager(solutionDescriptor.getLookUpStrategyResolver())
: null;
this.constraintMatchPolicy = builder.constraintMatchPolicy;
this.expectShadowVariablesInCorrectState = builder.expectShadowVariablesInCorrectState;
this.variableDescriptorCache = new VariableDescriptorCache<>(solutionDescriptor);
this.variableListenerSupport = VariableListenerSupport.create(this);
this.variableListenerSupport.linkVariableListeners();
this.solutionTracker = this.scoreDirectorFactory.isTrackingWorkingSolution()
? new SolutionTracker<>(getSolutionDescriptor(), getSupplyManager())
: null;
this.valueRangeManager = new ValueRangeManager<>(solutionDescriptor);
var listVariableDescriptor = solutionDescriptor.getListVariableDescriptor();
if (listVariableDescriptor == null) {
this.listVariableStateSupply = null;
} else {
this.listVariableStateSupply = getSupplyManager().demand(listVariableDescriptor.getStateDemand());
}
}
@Override
public final ConstraintMatchPolicy getConstraintMatchPolicy() {
return constraintMatchPolicy;
}
@Override
public Factory_ getScoreDirectorFactory() {
return scoreDirectorFactory;
}
@Override
public SolutionDescriptor<Solution_> getSolutionDescriptor() {
return scoreDirectorFactory.getSolutionDescriptor();
}
@Override
public ScoreDefinition<Score_> getScoreDefinition() {
return scoreDirectorFactory.getScoreDefinition();
}
@Override
public VariableDescriptorCache<Solution_> getVariableDescriptorCache() {
return variableDescriptorCache;
}
@Override
public ListVariableStateSupply<Solution_> getListVariableStateSupply(ListVariableDescriptor<Solution_> variableDescriptor) {
var originalListVariableDescriptor = getSolutionDescriptor().getListVariableDescriptor();
if (variableDescriptor != originalListVariableDescriptor) {
throw new IllegalStateException(
"The variableDescriptor (%s) is not the same as the solution's variableDescriptor (%s)."
.formatted(variableDescriptor, originalListVariableDescriptor));
}
return Objects.requireNonNull(listVariableStateSupply);
}
@Override
public boolean expectShadowVariablesInCorrectState() {
return expectShadowVariablesInCorrectState;
}
@Override
public @NonNull Solution_ getWorkingSolution() {
return workingSolution;
}
@Override
public int getWorkingInitScore() {
return workingInitScore;
}
@Override
public long getWorkingEntityListRevision() {
return workingEntityListRevision;
}
@Override
public int getWorkingGenuineEntityCount() {
return workingGenuineEntityCount;
}
@Override
public void setAllChangesWillBeUndoneBeforeStepEnds(boolean allChangesWillBeUndoneBeforeStepEnds) {
this.allChangesWillBeUndoneBeforeStepEnds = allChangesWillBeUndoneBeforeStepEnds;
}
@Override
public long getCalculationCount() {
return calculationCount;
}
@Override
public void resetCalculationCount() {
this.calculationCount = 0L;
}
@Override
public void incrementCalculationCount() {
this.calculationCount++;
}
@Override
public SupplyManager getSupplyManager() {
return variableListenerSupport;
}
@Override
public ValueRangeManager<Solution_> getValueRangeManager() {
return valueRangeManager;
}
@Override
public MoveDirector<Solution_, Score_> getMoveDirector() {
return moveDirector;
}
// ************************************************************************
// Complex methods
// ************************************************************************
/**
* Note: resetting the working solution does NOT substitute the calls to before/after methods of
* the {@link ProblemChangeDirector} during {@link ProblemChange problem changes},
* as these calls are propagated to {@link VariableListener variable listeners},
* which update shadow variables in the {@link PlanningSolution working solution} to keep it consistent.
*
* @param workingSolution the working solution to set
* @param entityAndFactVisitor maybe null; a function to apply to all problem facts and problem entities
*/
protected void setWorkingSolutionWithoutUpdatingShadows(Solution_ workingSolution, Consumer<Object> entityAndFactVisitor) {
this.workingSolution = requireNonNull(workingSolution);
var solutionDescriptor = getSolutionDescriptor();
/*
* Both problem facts and entities need to be asserted,
* which requires iterating over all of them,
* possibly many thousands of objects.
* Providing the init score and genuine entity count requires another pass over the entities.
* The following code does all of those operations in a single pass.
* It will also run the optional entityAndFactVisitor from the calling code,
* as that would have also resulted in another pass over all entities and facts.
*/
if (lookUpEnabled) {
lookUpManager.reset();
Consumer<Object> workingObjectLookupVisitor = lookUpManager::addWorkingObject;
entityAndFactVisitor = entityAndFactVisitor == null ? workingObjectLookupVisitor
: entityAndFactVisitor.andThen(workingObjectLookupVisitor);
}
// This visits all the facts, applying the visitor if non-null.
if (entityAndFactVisitor != null) {
solutionDescriptor.visitAllProblemFacts(workingSolution, entityAndFactVisitor);
}
Consumer<Object> entityValidator = entity -> scoreDirectorFactory.validateEntity(this, entity);
entityAndFactVisitor = entityAndFactVisitor == null ? entityValidator : entityAndFactVisitor.andThen(entityValidator);
setWorkingEntityListDirty(workingSolution);
// This visits all the entities.
var initializationStatistics = valueRangeManager.getInitializationStatistics(entityAndFactVisitor);
workingInitScore =
-(initializationStatistics.unassignedValueCount() + initializationStatistics.uninitializedVariableCount());
assertInitScoreZeroOrLess();
workingGenuineEntityCount = initializationStatistics.genuineEntityCount();
variableListenerSupport.resetWorkingSolution();
if (moveRepository != null) {
moveRepository.initialize(new SessionContext<>(this));
}
}
/**
* Note: Initial Solution may have stale shadow variables!
*
* @param workingSolution the initial solution
*/
@Override
public final void setWorkingSolution(Solution_ workingSolution) {
var originalShouldAssert = expectShadowVariablesInCorrectState;
expectShadowVariablesInCorrectState = false;
setWorkingSolutionWithoutUpdatingShadows(workingSolution);
variableListenerSupport.resetWorkingSolution();
forceTriggerVariableListeners();
expectShadowVariablesInCorrectState = originalShouldAssert;
}
@Override
public void setMoveRepository(@Nullable MoveRepository<Solution_> moveRepository) {
this.moveRepository = moveRepository;
if (moveRepository != null) {
moveRepository.initialize(new SessionContext<>(this));
}
}
private void assertInitScoreZeroOrLess() {
if (workingInitScore > 0) {
throw new IllegalStateException("""
workingInitScore > 0 (%d).
Maybe a custom move is removing more entities than were ever added?
""".formatted(workingInitScore));
}
}
@Override
public void executeMove(Move<Solution_> move) {
moveDirector.execute(move);
}
@Override
public InnerScore<Score_> executeTemporaryMove(Move<Solution_> move, boolean assertMoveScoreFromScratch) {
// This change and resulting before/after events will not be propagated to move stream session,
// as they will be immediately undone.
// Moves will only be re-generated once the solution has actually changed,
// which will happen at the end of the step, after executeMove(...) was called.
allChangesWillBeUndoneBeforeStepEnds = true;
if (solutionTracker != null) {
solutionTracker.setBeforeMoveSolution(workingSolution);
}
var moveScore = assertMoveScoreFromScratch ? moveDirector.executeTemporary(move,
(score, undoMove) -> {
if (solutionTracker != null) {
solutionTracker.setAfterMoveSolution(workingSolution);
}
assertWorkingScoreFromScratch(score, move);
return score;
}) : moveDirector.executeTemporary(move);
allChangesWillBeUndoneBeforeStepEnds = false;
return moveScore;
}
@Override
public boolean isWorkingEntityListDirty(long expectedWorkingEntityListRevision) {
return workingEntityListRevision != expectedWorkingEntityListRevision;
}
@Override
public boolean isWorkingSolutionInitialized() {
return workingInitScore == 0;
}
private void setWorkingEntityListDirty(@Nullable Solution_ solution) {
workingEntityListRevision++;
valueRangeManager.reset(solution);
}
@Override
public Solution_ cloneSolution(Solution_ originalSolution) {
SolutionDescriptor<Solution_> solutionDescriptor = getSolutionDescriptor();
var originalScore = solutionDescriptor.getScore(originalSolution);
var cloneSolution = solutionDescriptor.getSolutionCloner().cloneSolution(originalSolution);
var cloneScore = solutionDescriptor.getScore(cloneSolution);
if (scoreDirectorFactory.isAssertClonedSolution()) {
if (!Objects.equals(originalScore, cloneScore)) {
throw new CloningCorruptionException("""
Cloning corruption: the original's score (%s) is different from the clone's score (%s).
Check the %s."""
.formatted(originalScore, cloneScore, SolutionCloner.class.getSimpleName()));
}
var originalEntityMap = new IdentityHashMap<>();
solutionDescriptor.visitAllEntities(originalSolution,
originalEntity -> originalEntityMap.put(originalEntity, null));
solutionDescriptor.visitAllEntities(cloneSolution, cloneEntity -> {
if (originalEntityMap.containsKey(cloneEntity)) {
throw new CloningCorruptionException("""
Cloning corruption: the same entity (%s) is present in both the original and the clone.
So when a planning variable in the original solution changes, the cloned solution will change too.
Check the %s."""
.formatted(cloneEntity, SolutionCloner.class.getSimpleName()));
}
});
}
return cloneSolution;
}
@Override
public void triggerVariableListeners() {
variableListenerSupport.triggerVariableListenersInNotificationQueues();
}
/**
* This function clears all listener events that have been generated without triggering any of them.
* Using this method requires caution because clearing the event queue can lead to inconsistent states.
* This occurs when the shadow variables are not updated,
* causing constraints reliant on these variables to be inaccurately evaluated.
*/
protected void clearVariableListenerEvents() {
variableListenerSupport.clearAllVariableListenerEvents();
}
@Override
public void forceTriggerVariableListeners() {
variableListenerSupport.forceTriggerAllVariableListeners(getWorkingSolution());
}
protected void setCalculatedScore(Score_ score) {
getSolutionDescriptor().setScore(workingSolution, score);
calculationCount++;
}
/**
* @deprecated Unused, but kept for backward compatibility.
*/
@Deprecated(forRemoval = true, since = "1.14.0")
@Override
public AbstractScoreDirector<Solution_, Score_, Factory_> clone() {
throw new UnsupportedOperationException("Cloning score directors is not supported.");
}
@Override
public InnerScoreDirector<Solution_, Score_> createChildThreadScoreDirector(ChildThreadType childThreadType) {
// Most score directors don't need derived status; CS will override this.
if (childThreadType == ChildThreadType.PART_THREAD) {
var childThreadScoreDirector = scoreDirectorFactory.createScoreDirectorBuilder()
.withLookUpEnabled(lookUpEnabled)
.withConstraintMatchPolicy(constraintMatchPolicy)
.buildDerived();
// ScoreCalculationCountTermination takes into account previous phases
// but the calculationCount of partitions is maxed, not summed.
childThreadScoreDirector.calculationCount = calculationCount;
return childThreadScoreDirector;
} else if (childThreadType == ChildThreadType.MOVE_THREAD) {
var childThreadScoreDirector = scoreDirectorFactory.createScoreDirectorBuilder()
.withLookUpEnabled(true)
.withConstraintMatchPolicy(constraintMatchPolicy)
.buildDerived();
childThreadScoreDirector.setWorkingSolution(cloneWorkingSolution());
return childThreadScoreDirector;
} else {
throw new IllegalStateException("The childThreadType (" + childThreadType + ") is not implemented.");
}
}
@Override
public void close() {
workingSolution = null;
workingInitScore = 0;
if (lookUpEnabled) {
lookUpManager.reset();
}
if (listVariableStateSupply != null) {
getSupplyManager().cancel(listVariableStateSupply.getSourceVariableDescriptor().getStateDemand());
}
variableListenerSupport.close();
}
// ************************************************************************
// Entity/variable add/change/remove methods
// ************************************************************************
public void beforeEntityAdded(EntityDescriptor<Solution_> entityDescriptor, Object entity) {
variableListenerSupport.beforeEntityAdded(entityDescriptor, entity);
}
public void afterEntityAdded(EntityDescriptor<Solution_> entityDescriptor, Object entity) {
workingInitScore -= entityDescriptor.countUninitializedVariables(entity);
if (entityDescriptor.isGenuine()) {
workingGenuineEntityCount++;
}
if (lookUpEnabled) {
lookUpManager.addWorkingObject(entity);
}
if (!allChangesWillBeUndoneBeforeStepEnds) {
if (moveRepository instanceof MoveStreamsBasedMoveRepository<Solution_> moveStreamsBasedMoveRepository) {
moveStreamsBasedMoveRepository.insert(entity);
}
// Some selectors depend on this revision value to detect changes in entity value ranges.
// Therefore, we need to reset the value range state, but the working solution does not change.
setWorkingEntityListDirty(null);
}
}
@Override
public void beforeVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity) {
if (variableDescriptor.isGenuineAndUninitialized(entity)) {
workingInitScore++;
}
assertInitScoreZeroOrLess();
variableListenerSupport.beforeVariableChanged(variableDescriptor, entity);
}
@Override
public void afterVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity) {
if (variableDescriptor.isGenuineAndUninitialized(entity)) {
workingInitScore--;
}
if (moveRepository instanceof MoveStreamsBasedMoveRepository<Solution_> moveStreamsBasedMoveRepository) {
moveStreamsBasedMoveRepository.update(entity);
}
variableListenerSupport.afterVariableChanged(variableDescriptor, entity);
}
@Override
public void beforeListVariableElementAssigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) {
}
@Override
public void afterListVariableElementAssigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) {
if (!variableDescriptor.allowsUnassignedValues()) { // Unassigned elements don't count towards the initScore here.
workingInitScore++;
assertInitScoreZeroOrLess();
}
if (moveRepository instanceof MoveStreamsBasedMoveRepository<Solution_> moveStreamsBasedMoveRepository) {
moveStreamsBasedMoveRepository.update(element);
}
}
@Override
public void beforeListVariableElementUnassigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) {
// Do nothing
}
@Override
public void afterListVariableElementUnassigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) {
if (!variableDescriptor.allowsUnassignedValues()) { // Unassigned elements don't count towards the initScore here.
workingInitScore--;
}
variableListenerSupport.afterElementUnassigned(variableDescriptor, element);
if (moveRepository instanceof MoveStreamsBasedMoveRepository<Solution_> moveStreamsBasedMoveRepository) {
moveStreamsBasedMoveRepository.update(element);
}
}
@Override
public void beforeListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex,
int toIndex) {
// Pinning is implemented in generic moves, but custom moves need to take it into account as well.
// This fail-fast exists to detect situations where pinned things are being moved, in case of user error.
if (variableDescriptor.isElementPinned(getWorkingSolution(), entity, fromIndex)) {
throw new IllegalStateException(
"""
Attempting to change list variable (%s) on an entity (%s) in range [%d, %d), which is partially or entirely pinned.
This is most likely a bug in a move.
Maybe you are using an improperly implemented custom move?"""
.formatted(variableDescriptor, entity, fromIndex, toIndex));
}
variableListenerSupport.beforeListVariableChanged(variableDescriptor, entity, fromIndex, toIndex);
}
@Override
public void afterListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor,
Object entity, int fromIndex, int toIndex) {
variableListenerSupport.afterListVariableChanged(variableDescriptor, entity, fromIndex, toIndex);
if (moveRepository instanceof MoveStreamsBasedMoveRepository<Solution_> moveStreamsBasedMoveRepository) {
moveStreamsBasedMoveRepository.update(entity);
}
}
public void beforeEntityRemoved(EntityDescriptor<Solution_> entityDescriptor, Object entity) {
workingInitScore += entityDescriptor.countUninitializedVariables(entity);
assertInitScoreZeroOrLess();
variableListenerSupport.beforeEntityRemoved(entityDescriptor, entity);
}
public void afterEntityRemoved(EntityDescriptor<Solution_> entityDescriptor, Object entity) {
if (entityDescriptor.isGenuine()) {
workingGenuineEntityCount--;
}
if (lookUpEnabled) {
lookUpManager.removeWorkingObject(entity);
}
if (!allChangesWillBeUndoneBeforeStepEnds) {
if (moveRepository instanceof MoveStreamsBasedMoveRepository<Solution_> moveStreamsBasedMoveRepository) {
moveStreamsBasedMoveRepository.retract(entity);
}
// Some selectors depend on this revision value to detect changes in entity value ranges.
// Therefore, we need to reset the value range state, but the working solution does not change.
setWorkingEntityListDirty(null);
}
}
// ************************************************************************
// Problem fact add/change/remove methods
// ************************************************************************
@Override
public void beforeProblemFactAdded(Object problemFact) {
// Do nothing
}
@Override
public void afterProblemFactAdded(Object problemFact) {
if (lookUpEnabled) {
lookUpManager.addWorkingObject(problemFact);
}
variableListenerSupport.resetWorkingSolution(); // TODO do not nuke the variable listeners
if (moveRepository instanceof MoveStreamsBasedMoveRepository<Solution_> moveStreamsBasedMoveRepository) {
moveStreamsBasedMoveRepository.insert(problemFact);
}
}
@Override
public void beforeProblemPropertyChanged(Object problemFactOrEntity) {
// Do nothing
}
@Override
public void afterProblemPropertyChanged(Object problemFactOrEntity) {
if (isConstraintConfiguration(problemFactOrEntity)) {
setWorkingSolution(workingSolution); // Nuke everything and recalculate, constraint weights have changed.
} else {
variableListenerSupport.resetWorkingSolution(); // TODO do not nuke the variable listeners
if (moveRepository instanceof MoveStreamsBasedMoveRepository<Solution_> moveStreamsBasedMoveRepository) {
moveStreamsBasedMoveRepository.update(problemFactOrEntity);
}
}
}
@Override
public void beforeProblemFactRemoved(Object problemFact) {
if (isConstraintConfiguration(problemFact)) {
throw new IllegalStateException("""
Attempted to remove constraint configuration (%s) from solution (%s).
Maybe use before/afterProblemPropertyChanged(...) instead.""".formatted(problemFact, workingSolution));
}
}
@Override
public void afterProblemFactRemoved(Object problemFact) {
if (lookUpEnabled) {
lookUpManager.removeWorkingObject(problemFact);
}
variableListenerSupport.resetWorkingSolution(); // TODO do not nuke the variable listeners
if (moveRepository instanceof MoveStreamsBasedMoveRepository<Solution_> moveStreamsBasedMoveRepository) {
moveStreamsBasedMoveRepository.retract(problemFact);
}
}
@Override
public <E> @Nullable E lookUpWorkingObject(@Nullable E externalObject) {
if (!lookUpEnabled) {
throw new IllegalStateException(
"When lookUpEnabled (%s) is disabled in the constructor, this method should not be called."
.formatted(lookUpEnabled));
}
return lookUpManager.lookUpWorkingObject(externalObject);
}
@Override
public <E> @Nullable E lookUpWorkingObjectOrReturnNull(@Nullable E externalObject) {
if (!lookUpEnabled) {
throw new IllegalStateException(
"When lookUpEnabled (%s) is disabled in the constructor, this method should not be called."
.formatted(lookUpEnabled));
}
return lookUpManager.lookUpWorkingObjectOrReturnNull(externalObject);
}
// ************************************************************************
// Assert methods
// ************************************************************************
@Override
public void assertExpectedWorkingScore(InnerScore<Score_> expectedWorkingScore, Object completedAction) {
InnerScore<Score_> workingScore = calculateScore();
if (!expectedWorkingScore.equals(workingScore)) {
throw new ScoreCorruptionException("""
Score corruption (%s): the expectedWorkingScore (%s) is not the workingScore (%s) \
after completedAction (%s)."""
.formatted(expectedWorkingScore.raw().subtract(workingScore.raw()).toShortString(),
expectedWorkingScore, workingScore, completedAction));
}
}
@Override
public void assertShadowVariablesAreNotStale(InnerScore<Score_> expectedWorkingScore, Object completedAction) {
var violationMessage = variableListenerSupport.createShadowVariablesViolationMessage();
if (violationMessage != null) {
throw new VariableCorruptionException("""
%s corruption after completedAction (%s):
%s"""
.formatted(VariableListener.class.getSimpleName(), completedAction, violationMessage));
}
var workingScore = calculateScore();
if (!expectedWorkingScore.equals(workingScore)) {
assertWorkingScoreFromScratch(workingScore,
"assertShadowVariablesAreNotStale(" + expectedWorkingScore + ", " + completedAction + ")");
throw new VariableCorruptionException("""
Impossible %s corruption (%s): the expectedWorkingScore (%s) is not the workingScore (%s) \
after all %s were triggered without changes to the genuine variables after completedAction (%s).
All the shadow variable values are still the same, so this is impossible.
Maybe run with %s if you haven't already, to fail earlier."""
.formatted(VariableListener.class.getSimpleName(),
expectedWorkingScore.raw().subtract(workingScore.raw()).toShortString(),
expectedWorkingScore, workingScore, VariableListener.class.getSimpleName(), completedAction,
EnvironmentMode.TRACKED_FULL_ASSERT));
}
}
/**
* @param predicted true if the score was predicted and might have been calculated on another thread
* @return never null
*/
protected String buildShadowVariableAnalysis(boolean predicted) {
var violationMessage = variableListenerSupport.createShadowVariablesViolationMessage();
var workingLabel = predicted ? "working" : "corrupted";
if (violationMessage == null) {
return """
Shadow variable corruption in the %s scoreDirector:
None"""
.formatted(workingLabel);
}
return """
Shadow variable corruption in the %s scoreDirector:
%s
Maybe there is a bug in the %s of those shadow variable(s)."""
.formatted(workingLabel, violationMessage, VariableListener.class.getSimpleName());
}
@Override
public void assertWorkingScoreFromScratch(InnerScore<Score_> workingScore, Object completedAction) {
assertScoreFromScratch(workingScore, completedAction, false);
}
@Override
public void assertPredictedScoreFromScratch(InnerScore<Score_> workingScore, Object completedAction) {
assertScoreFromScratch(workingScore, completedAction, true);
}
private void assertScoreFromScratch(InnerScore<Score_> innerScore, Object completedAction, boolean predicted) {
var assertionScoreDirectorFactory = scoreDirectorFactory.getAssertionScoreDirectorFactory();
if (assertionScoreDirectorFactory == null) {
assertionScoreDirectorFactory = scoreDirectorFactory;
}
// Most score directors don't need derived status; CS will override this.
try (var uncorruptedScoreDirector = assertionScoreDirectorFactory.createScoreDirectorBuilder()
.withConstraintMatchPolicy(ConstraintMatchPolicy.ENABLED)
.buildDerived()) {
uncorruptedScoreDirector.setWorkingSolution(workingSolution);
var uncorruptedInnerScore = uncorruptedScoreDirector.calculateScore();
if (!innerScore.equals(uncorruptedInnerScore)) {
String scoreCorruptionAnalysis = buildScoreCorruptionAnalysis(uncorruptedScoreDirector, predicted);
String shadowVariableAnalysis = buildShadowVariableAnalysis(predicted);
throw new ScoreCorruptionException("""
Score corruption (%s): the %s (%s) is not the uncorruptedScore (%s) after completedAction (%s):
%s
%s"""
.formatted(innerScore.raw().subtract(uncorruptedInnerScore.raw()).toShortString(),
predicted ? "predictedScore" : "workingScore", innerScore, uncorruptedInnerScore,
completedAction, scoreCorruptionAnalysis, shadowVariableAnalysis));
}
}
}
@Override
public void assertExpectedUndoMoveScore(Move<Solution_> move, InnerScore<Score_> beforeMoveInnerScore,
SolverLifecyclePoint executionPoint) {
var undoInnerScore = calculateScore();
if (Objects.equals(undoInnerScore, beforeMoveInnerScore)) {
return;
}
logger.trace(" Corruption detected. Diagnosing...");
var trackingWorkingSolution = solutionTracker != null;
if (trackingWorkingSolution) {
solutionTracker.setAfterUndoSolution(workingSolution);
}
// Precondition: assert that there are probably no corrupted constraints
var undoMoveToString = "Undo(%s)".formatted(move);
assertWorkingScoreFromScratch(undoInnerScore, undoMoveToString);
// Precondition: assert that shadow variables aren't stale after doing the undoMove
assertShadowVariablesAreNotStale(undoInnerScore, undoMoveToString);
var corruptionDiagnosis = "";
if (trackingWorkingSolution) {
// Recalculate all shadow variables from scratch.
// We cannot set all shadow variables to null, since some variable listeners
// may expect them to be non-null.
// Instead, we just simulate a change to all genuine variables.
variableListenerSupport.forceTriggerAllVariableListeners(workingSolution);
solutionTracker.setUndoFromScratchSolution(workingSolution);
// Also calculate from scratch for the before solution, since it might
// have been corrupted but was only detected now
solutionTracker.restoreBeforeSolution();
variableListenerSupport.forceTriggerAllVariableListeners(workingSolution);
solutionTracker.setBeforeFromScratchSolution(workingSolution);
corruptionDiagnosis = solutionTracker.buildScoreCorruptionMessage();
}
var scoreDifference = undoInnerScore.raw().subtract(beforeMoveInnerScore.raw()).toShortString();
var corruptionMessage = """
UndoMove corruption (%s):
the beforeMoveScore (%s) is not the undoScore (%s),
which is the uncorruptedScore (%s) of the workingSolution.
Corruption diagnosis:
%s
1) Enable EnvironmentMode %s (if you haven't already)
to fail-faster in case of a score corruption or variable listener corruption.
Let the solver run until it reaches the same point in its lifecycle (%s),
even though it may take a very long time.
If the solver throws an exception before reaching that point,
there may be yet another problem that needs to be fixed.
2) If you use custom moves, check the Move.createUndoMove(...) method of the custom move class (%s).
The move (%s) might have a corrupted undoMove (%s).
3) If you use custom %ss,
check them for shadow variables that are used by score constraints
that could cause the scoreDifference (%s)."""
.formatted(scoreDifference, beforeMoveInnerScore, undoInnerScore, undoInnerScore,
corruptionDiagnosis,
EnvironmentMode.TRACKED_FULL_ASSERT, executionPoint,
move.getClass().getSimpleName(), move, undoMoveToString,
VariableListener.class.getSimpleName(), scoreDifference);
if (trackingWorkingSolution) {
throw new UndoScoreCorruptionException(corruptionMessage,
solutionTracker.getBeforeMoveSolution(),
solutionTracker.getAfterMoveSolution(),
solutionTracker.getAfterUndoSolution());
} else {
throw new ScoreCorruptionException(corruptionMessage);
}
}
public SolutionTracker.SolutionCorruptionResult getSolutionCorruptionAfterUndo(Move<Solution_> move,
InnerScore<Score_> undoInnerScore) {
var trackingWorkingSolution = solutionTracker != null;
if (trackingWorkingSolution) {
solutionTracker.setAfterUndoSolution(workingSolution);
}
// Precondition: assert that there are probably no corrupted constraints
var undoMoveToString = "Undo(%s)".formatted(move);
assertWorkingScoreFromScratch(undoInnerScore, undoMoveToString);
// Precondition: assert that shadow variables aren't stale after doing the undoMove
assertShadowVariablesAreNotStale(undoInnerScore, undoMoveToString);
if (trackingWorkingSolution) {
// Recalculate all shadow variables from scratch.
// We cannot set all shadow variables to null, since some variable listeners
// may expect them to be non-null.
// Instead, we just simulate a change to all genuine variables.
variableListenerSupport.forceTriggerAllVariableListeners(workingSolution);
solutionTracker.setUndoFromScratchSolution(workingSolution);
// Also calculate from scratch for the before solution, since it might
// have been corrupted but was only detected now
solutionTracker.restoreBeforeSolution();
variableListenerSupport.forceTriggerAllVariableListeners(workingSolution);
solutionTracker.setBeforeFromScratchSolution(workingSolution);
return solutionTracker.buildSolutionCorruptionResult();
}
return SolutionTracker.SolutionCorruptionResult.untracked();
}
/**
* @param uncorruptedScoreDirector never null
* @param predicted true if the score was predicted and might have been calculated on another thread
* @return never null
*/
protected String buildScoreCorruptionAnalysis(InnerScoreDirector<Solution_, Score_> uncorruptedScoreDirector,
boolean predicted) {
if (!getConstraintMatchPolicy().isEnabled() || !uncorruptedScoreDirector.getConstraintMatchPolicy().isEnabled()) {
return """
Score corruption analysis could not be generated because either corrupted constraintMatchPolicy (%s) \
or uncorrupted constraintMatchPolicy (%s) is %s.
Check your score constraints manually."""
.formatted(constraintMatchPolicy, uncorruptedScoreDirector.getConstraintMatchPolicy(),
ConstraintMatchPolicy.DISABLED);
}
var corruptedAnalysis = buildScoreAnalysis(ScoreAnalysisFetchPolicy.FETCH_ALL);
var uncorruptedAnalysis = uncorruptedScoreDirector.buildScoreAnalysis(ScoreAnalysisFetchPolicy.FETCH_ALL);
var excessSet = new LinkedHashSet<MatchAnalysis<Score_>>();
var missingSet = new LinkedHashSet<MatchAnalysis<Score_>>();
uncorruptedAnalysis.constraintMap().forEach((constraintRef, uncorruptedConstraintAnalysis) -> {
var uncorruptedConstraintMatches = emptyMatchAnalysisIfNull(uncorruptedConstraintAnalysis);
var corruptedConstraintMatches = emptyMatchAnalysisIfNull(corruptedAnalysis.constraintMap()
.get(constraintRef));
if (corruptedConstraintMatches.isEmpty()) {
missingSet.addAll(uncorruptedConstraintMatches);
} else {
updateExcessAndMissingConstraintMatches(uncorruptedConstraintMatches, corruptedConstraintMatches, excessSet,
missingSet);
}
});
corruptedAnalysis.constraintMap().forEach((constraintRef, corruptedConstraintAnalysis) -> {
var corruptedConstraintMatches = emptyMatchAnalysisIfNull(corruptedConstraintAnalysis);
var uncorruptedConstraintMatches = emptyMatchAnalysisIfNull(uncorruptedAnalysis.constraintMap()
.get(constraintRef));
if (uncorruptedConstraintMatches.isEmpty()) {
excessSet.addAll(corruptedConstraintMatches);
} else {
updateExcessAndMissingConstraintMatches(uncorruptedConstraintMatches, corruptedConstraintMatches, excessSet,
missingSet);
}
});
var analysis = new StringBuilder();
analysis.append("Score corruption analysis:\n");
// If predicted, the score calculation might have happened on another thread, so a different ScoreDirector
// so there is no guarantee that the working ScoreDirector is the corrupted ScoreDirector
var workingLabel = predicted ? "working" : "corrupted";
appendAnalysis(analysis, workingLabel, "should not be there", excessSet);
appendAnalysis(analysis, workingLabel, "are missing", missingSet);
if (!missingSet.isEmpty() || !excessSet.isEmpty()) {
analysis.append("""
Maybe there is a bug in the score constraints of those ConstraintMatch(s).
Maybe a score constraint doesn't select all the entities it depends on,
but discovers some transitively through a reference from the selected entity.
This corrupts incremental score calculation,
because the constraint is not re-evaluated if the transitively discovered entity changes.
""".stripTrailing());
} else {
if (predicted) {
analysis.append("""
If multi-threaded solving is active:
- the working scoreDirector is probably not the corrupted scoreDirector.
- maybe the rebase() method of the move is bugged.
- maybe a VariableListener affected the moveThread's workingSolution after doing and undoing a move,
but this didn't happen here on the solverThread, so we can't detect it.
""".stripTrailing());
} else {
analysis.append(" Impossible state. Maybe this is a bug in the scoreDirector (%s)."
.formatted(getClass()));
}
}
return analysis.toString();
}
private static <Score_ extends Score<Score_>> List<MatchAnalysis<Score_>>
emptyMatchAnalysisIfNull(ConstraintAnalysis<Score_> constraintAnalysis) {
if (constraintAnalysis == null) {
return Collections.emptyList();
}
return Objects.requireNonNullElse(constraintAnalysis.matches(), Collections.emptyList());
}
private void appendAnalysis(StringBuilder analysis, String workingLabel, String suffix,
Set<MatchAnalysis<Score_>> matches) {
if (matches.isEmpty()) {
analysis.append("""
The %s scoreDirector has no ConstraintMatch(es) which %s.
""".formatted(workingLabel, suffix));
} else {
analysis.append("""
The %s scoreDirector has %s ConstraintMatch(es) which %s:
""".formatted(workingLabel, matches.size(), suffix));
matches.stream().sorted().limit(CONSTRAINT_MATCH_DISPLAY_LIMIT)
.forEach(match -> analysis.append("""
%s/%s=%s
""".formatted(match.constraintRef().constraintId(), match.justification(), match.score())));
if (matches.size() >= CONSTRAINT_MATCH_DISPLAY_LIMIT) {
analysis.append("""
... %s more
""".formatted(matches.size() - CONSTRAINT_MATCH_DISPLAY_LIMIT));
}
}
}
private void updateExcessAndMissingConstraintMatches(List<MatchAnalysis<Score_>> uncorruptedList,
List<MatchAnalysis<Score_>> corruptedList, Set<MatchAnalysis<Score_>> excessSet,
Set<MatchAnalysis<Score_>> missingSet) {
iterateAndAddIfFound(corruptedList, uncorruptedList, excessSet);
iterateAndAddIfFound(uncorruptedList, corruptedList, missingSet);
}
private void iterateAndAddIfFound(List<MatchAnalysis<Score_>> referenceList, List<MatchAnalysis<Score_>> lookupList,
Set<MatchAnalysis<Score_>> targetSet) {
if (referenceList.isEmpty()) {
return;
}
var lookupSet = new LinkedHashSet<>(lookupList); // Guaranteed to not contain duplicates anyway.
for (var reference : referenceList) {
if (!lookupSet.contains(reference)) {
targetSet.add(reference);
}
}
}
protected boolean isConstraintConfiguration(Object problemFactOrEntity) {
var solutionDescriptor = scoreDirectorFactory.getSolutionDescriptor();
var constraintWeightSupplier = solutionDescriptor.getConstraintWeightSupplier();
if (constraintWeightSupplier == null) {
return false;
}
return constraintWeightSupplier.getProblemFactClass()
.isInstance(problemFactOrEntity);
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + calculationCount + ")";
}
/**
* An abstract builder for creating instances of {@link InnerScoreDirector}.
* This class provides methods to configure the behavior of the score director before building it.
* Unless the appropriate withers are called, the score director will be built:
*
* <ul>
* <li>With {@link ConstraintMatchPolicy#DISABLED}.</li>
* <li>With lookup disabled.</li>
* <li>Expecting shadow variables in their correct state.</li>
* </ul>
*
* @param <Solution_> The type of the planning solution.
* @param <Score_> The type of the score associated with the solution.
* @param <Factory_> The type of the score director factory used to create the score director.
* @param <Builder_> The type of the builder, used for fluent configuration.
*/
@NullMarked
public abstract static class AbstractScoreDirectorBuilder<Solution_, Score_ extends Score<Score_>, Factory_ extends AbstractScoreDirectorFactory<Solution_, Score_, Factory_>, Builder_ extends AbstractScoreDirectorBuilder<Solution_, Score_, Factory_, Builder_>> {
protected final Factory_ scoreDirectorFactory;
protected ConstraintMatchPolicy constraintMatchPolicy = ConstraintMatchPolicy.DISABLED;
protected boolean lookUpEnabled = false;
protected boolean expectShadowVariablesInCorrectState = true;
protected AbstractScoreDirectorBuilder(Factory_ scoreDirectorFactory) {
this.scoreDirectorFactory = Objects.requireNonNull(scoreDirectorFactory);
}
@SuppressWarnings("unchecked")
public Builder_ withConstraintMatchPolicy(ConstraintMatchPolicy constraintMatchPolicy) {
this.constraintMatchPolicy = constraintMatchPolicy;
return (Builder_) this;
}
@SuppressWarnings("unchecked")
public Builder_ withLookUpEnabled(boolean lookUpEnabled) {
this.lookUpEnabled = lookUpEnabled;
return (Builder_) this;
}
@SuppressWarnings("unchecked")
public Builder_ withExpectShadowVariablesInCorrectState(boolean expectShadowVariablesInCorrectState) {
this.expectShadowVariablesInCorrectState = expectShadowVariablesInCorrectState;
return (Builder_) this;
}
public abstract AbstractScoreDirector<Solution_, Score_, Factory_> build();
/**
* Optionally makes the score director a derived one; most score directors do not require this.
* Derived score directors may make choices which the main score director cannot make, such as reducing logging.
* Derived score directors are typically used for multithreaded solving, testing and assert modes.
* Derived score directors do not support move streams, as they are only used to calculate the score.
*
* @return this
*/
public AbstractScoreDirector<Solution_, Score_, Factory_> buildDerived() {
return build();
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/director/AbstractScoreDirectorFactory.java | package ai.timefold.solver.core.impl.score.director;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract superclass for {@link ScoreDirectorFactory}.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @param <Score_> the score type to go with the solution
* @see ScoreDirectorFactory
*/
public abstract class AbstractScoreDirectorFactory<Solution_, Score_ extends Score<Score_>, Factory_ extends AbstractScoreDirectorFactory<Solution_, Score_, Factory_>>
implements ScoreDirectorFactory<Solution_, Score_> {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected final SolutionDescriptor<Solution_> solutionDescriptor;
protected final ListVariableDescriptor<Solution_> listVariableDescriptor;
protected InitializingScoreTrend initializingScoreTrend;
protected ScoreDirectorFactory<Solution_, Score_> assertionScoreDirectorFactory = null;
protected boolean assertClonedSolution = false;
protected boolean trackingWorkingSolution = false;
public AbstractScoreDirectorFactory(SolutionDescriptor<Solution_> solutionDescriptor) {
this.solutionDescriptor = solutionDescriptor;
this.listVariableDescriptor = solutionDescriptor.getListVariableDescriptor();
}
@Override
public SolutionDescriptor<Solution_> getSolutionDescriptor() {
return solutionDescriptor;
}
@Override
public ScoreDefinition<Score_> getScoreDefinition() {
return solutionDescriptor.getScoreDefinition();
}
@Override
public InitializingScoreTrend getInitializingScoreTrend() {
return initializingScoreTrend;
}
public void setInitializingScoreTrend(InitializingScoreTrend initializingScoreTrend) {
this.initializingScoreTrend = initializingScoreTrend;
}
public ScoreDirectorFactory<Solution_, Score_> getAssertionScoreDirectorFactory() {
return assertionScoreDirectorFactory;
}
public void setAssertionScoreDirectorFactory(ScoreDirectorFactory<Solution_, Score_> assertionScoreDirectorFactory) {
this.assertionScoreDirectorFactory = assertionScoreDirectorFactory;
}
public boolean isAssertClonedSolution() {
return assertClonedSolution;
}
public void setAssertClonedSolution(boolean assertClonedSolution) {
this.assertClonedSolution = assertClonedSolution;
}
/**
* When true, a snapshot of the solution is created before, after and after the undo of a move.
* In {@link EnvironmentMode#TRACKED_FULL_ASSERT},
* the snapshots are compared when corruption is detected,
* allowing us to report exactly what variables are different.
*/
public boolean isTrackingWorkingSolution() {
return trackingWorkingSolution;
}
public void setTrackingWorkingSolution(boolean trackingWorkingSolution) {
this.trackingWorkingSolution = trackingWorkingSolution;
}
@Override
public void assertScoreFromScratch(Solution_ solution) {
// Get the score before uncorruptedScoreDirector.calculateScore() modifies it
var score = getSolutionDescriptor().<Score_> getScore(solution);
// Most score directors don't need derived status; CS will override this.
try (var uncorruptedScoreDirector = createScoreDirectorBuilder()
.withConstraintMatchPolicy(ConstraintMatchPolicy.ENABLED)
.buildDerived()) {
uncorruptedScoreDirector.setWorkingSolution(solution);
var uncorruptedScore = uncorruptedScoreDirector.calculateScore()
.raw();
if (!score.equals(uncorruptedScore)) {
throw new IllegalStateException(
"Score corruption (%s): the solution's score (%s) is not the uncorruptedScore (%s)."
.formatted(score.subtract(uncorruptedScore).toShortString(), score, uncorruptedScore));
}
}
}
public void validateEntity(ScoreDirector<Solution_> scoreDirector, Object entity) {
if (listVariableDescriptor == null) { // Only basic variables.
var entityDescriptor = solutionDescriptor.findEntityDescriptorOrFail(entity.getClass());
if (entityDescriptor.isMovable(scoreDirector.getWorkingSolution(), entity)) {
return;
}
for (var variableDescriptor : entityDescriptor.getGenuineVariableDescriptorList()) {
var basicVariableDescriptor = (BasicVariableDescriptor<Solution_>) variableDescriptor;
if (basicVariableDescriptor.allowsUnassigned()) {
continue;
}
var value = basicVariableDescriptor.getValue(entity);
if (value == null) {
throw new IllegalStateException(
"The entity (%s) has a variable (%s) pinned to null, even though unassigned values are not allowed."
.formatted(entity, basicVariableDescriptor.getVariableName()));
}
}
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/director/InnerScore.java | package ai.timefold.solver.core.impl.score.director;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
import ai.timefold.solver.core.api.score.Score;
import org.jspecify.annotations.NullMarked;
/**
* Carries information on if the {@link PlanningSolution} of this score was fully initialized when it was calculated.
* This only works for solutions where:
* <ul>
* <li>{@link PlanningVariable basic variables} are used,
* and {@link PlanningVariable#allowsUnassigned() unassigning} is not allowed.</li>
* <li>{@link PlanningListVariable list variables} are used,
* and {@link PlanningListVariable#allowsUnassignedValues() unassigned values} are not allowed.</li>
* </ul>
*
* For solutions which do allow unassigning values, {@link #unassignedCount} is always zero.
*/
@NullMarked
public record InnerScore<Score_ extends Score<Score_>>(Score_ raw, int unassignedCount)
implements
Comparable<InnerScore<Score_>> {
public static <Score_ extends Score<Score_>> InnerScore<Score_> fullyAssigned(Score_ score) {
return new InnerScore<>(score, 0);
}
public static <Score_ extends Score<Score_>> InnerScore<Score_> withUnassignedCount(Score_ score, int unassignedCount) {
return new InnerScore<>(score, unassignedCount);
}
public InnerScore {
Objects.requireNonNull(raw);
if (unassignedCount < 0) {
throw new IllegalArgumentException("The unassignedCount (%d) must be >= 0."
.formatted(unassignedCount));
}
}
public boolean isFullyAssigned() {
return unassignedCount == 0;
}
@Override
public int compareTo(InnerScore<Score_> other) {
var uninitializedCountComparison = Integer.compare(unassignedCount, other.unassignedCount);
if (uninitializedCountComparison != 0) {
return -uninitializedCountComparison;
} else {
return raw.compareTo(other.raw);
}
}
@Override
public String toString() {
return isFullyAssigned() ? raw.toString() : "-%dinit/%s".formatted(unassignedCount, raw);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/director/InnerScoreDirector.java | package ai.timefold.solver.core.impl.score.director;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
import ai.timefold.solver.core.api.domain.variable.VariableListener;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.analysis.ConstraintAnalysis;
import ai.timefold.solver.core.api.score.analysis.MatchAnalysis;
import ai.timefold.solver.core.api.score.analysis.ScoreAnalysis;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatch;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal;
import ai.timefold.solver.core.api.score.constraint.ConstraintRef;
import ai.timefold.solver.core.api.score.constraint.Indictment;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.api.score.stream.Constraint;
import ai.timefold.solver.core.api.score.stream.ConstraintJustification;
import ai.timefold.solver.core.api.solver.ScoreAnalysisFetchPolicy;
import ai.timefold.solver.core.api.solver.SolutionManager;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
import ai.timefold.solver.core.impl.move.MoveRepository;
import ai.timefold.solver.core.impl.move.director.MoveDirector;
import ai.timefold.solver.core.impl.phase.scope.SolverLifecyclePoint;
import ai.timefold.solver.core.impl.score.constraint.ConstraintMatchPolicy;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
import ai.timefold.solver.core.preview.api.move.Move;
import org.jspecify.annotations.Nullable;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @param <Score_> the score type to go with the solution
*/
public interface InnerScoreDirector<Solution_, Score_ extends Score<Score_>>
extends VariableDescriptorAwareScoreDirector<Solution_>, AutoCloseable {
static <Score_ extends Score<Score_>> ConstraintAnalysis<Score_> getConstraintAnalysis(
ConstraintMatchTotal<Score_> constraintMatchTotal, ScoreAnalysisFetchPolicy scoreAnalysisFetchPolicy) {
return switch (scoreAnalysisFetchPolicy) {
case FETCH_ALL -> {
// Justification can not be null here, because they are enabled by FETCH_ALL.
var deduplicatedConstraintMatchMap = constraintMatchTotal.getConstraintMatchSet()
.stream()
.collect(groupingBy(
c -> (ConstraintJustification) c.getJustification(),
toList()));
var matchAnalyses = sumMatchesWithSameJustification(constraintMatchTotal, deduplicatedConstraintMatchMap);
yield new ConstraintAnalysis<>(constraintMatchTotal.getConstraintRef(),
constraintMatchTotal.getConstraintWeight(), constraintMatchTotal.getScore(), matchAnalyses);
}
case FETCH_MATCH_COUNT -> new ConstraintAnalysis<>(constraintMatchTotal.getConstraintRef(),
constraintMatchTotal.getConstraintWeight(), constraintMatchTotal.getScore(), null,
constraintMatchTotal.getConstraintMatchCount());
case FETCH_SHALLOW ->
new ConstraintAnalysis<>(constraintMatchTotal.getConstraintRef(), constraintMatchTotal.getConstraintWeight(),
constraintMatchTotal.getScore(), null);
};
}
private static <Score_ extends Score<Score_>> List<MatchAnalysis<Score_>>
sumMatchesWithSameJustification(ConstraintMatchTotal<Score_> constraintMatchTotal,
Map<ConstraintJustification, List<ConstraintMatch<Score_>>> deduplicatedConstraintMatchMap) {
return deduplicatedConstraintMatchMap.entrySet().stream()
.map(entry -> {
var score = entry.getValue().stream()
.map(ConstraintMatch::getScore)
.reduce(constraintMatchTotal.getScore().zero(), Score::add);
return new MatchAnalysis<>(constraintMatchTotal.getConstraintRef(), score, entry.getKey());
})
.toList();
}
/**
* Sets the {@link PlanningSolution working solution} of the {@link ScoreDirector}
* to the given {@link PlanningSolution solution}, and force updates all the shadow variables on the given solution.
*
* @param workingSolution never null, must never be the same instance as the best solution.
*/
void setWorkingSolution(Solution_ workingSolution);
/**
* Sets the {@link PlanningSolution working solution} of the {@link ScoreDirector}
* to the given {@link PlanningSolution solution}, without updating any of the shadow variables on the given solution.
*
* @param workingSolution never null, must never be the same instance as the best solution.
*/
void setWorkingSolutionWithoutUpdatingShadows(Solution_ workingSolution);
/**
* Different phases may need different move repositories,
* as they may be based on different sets of moves.
* Therefore move repository cannot be injected at score director construction time.
*
* A phase may not need a move repository at all,
* such as construction heuristics, which currently does not support Move Streams.
*
* Each phase is responsible for calling this method to set its repository,
* and also calling it again at the end to null it out.
*/
void setMoveRepository(@Nullable MoveRepository<Solution_> moveRepository);
/**
* Calculates the {@link Score} and updates the {@link PlanningSolution working solution} accordingly.
*
* @return never null, the {@link Score} of the {@link PlanningSolution working solution}
*/
InnerScore<Score_> calculateScore();
/**
* @return {@link ConstraintMatchPolicy#ENABLED} if {@link #getConstraintMatchTotalMap()} and {@link #getIndictmentMap()}
* can be called.
* {@link ConstraintMatchPolicy#ENABLED_WITHOUT_JUSTIFICATIONS} if only the former can be called.
* {@link ConstraintMatchPolicy#DISABLED} if neither can be called.
*/
ConstraintMatchPolicy getConstraintMatchPolicy();
/**
* Explains the {@link Score} of {@link #calculateScore()} by splitting it up per {@link Constraint}.
* <p>
* The sum of {@link ConstraintMatchTotal#getScore()} equals {@link #calculateScore()}.
* <p>
* Call {@link #calculateScore()} before calling this method,
* unless that method has already been called since the last {@link PlanningVariable} changes.
*
* @return never null, the key is the constraintId
* (to create one, use {@link ConstraintRef#composeConstraintId(String, String)}).
* If a constraint is present in the problem but resulted in no matches,
* it will still be in the map with a {@link ConstraintMatchTotal#getConstraintMatchSet()} size of 0.
* @throws IllegalStateException if {@link #getConstraintMatchPolicy()} returns {@link ConstraintMatchPolicy#DISABLED}.
* @see #getIndictmentMap()
*/
Map<String, ConstraintMatchTotal<Score_>> getConstraintMatchTotalMap();
/**
* Explains the impact of each planning entity or problem fact on the {@link Score}.
* An {@link Indictment} is basically the inverse of a {@link ConstraintMatchTotal}:
* it is a {@link Score} total for each {@link ConstraintMatch#getJustification() constraint justification}.
* <p>
* The sum of {@link ConstraintMatchTotal#getScore()} differs from {@link #calculateScore()}
* because each {@link ConstraintMatch#getScore()} is counted
* for each {@link ConstraintMatch#getJustification() constraint justification}.
* <p>
* Call {@link #calculateScore()} before calling this method,
* unless that method has already been called since the last {@link PlanningVariable} changes.
*
* @return never null, the key is a {@link ProblemFactCollectionProperty problem fact} or a
* {@link PlanningEntity planning entity}
* @throws IllegalStateException unless {@link #getConstraintMatchPolicy()} returns {@link ConstraintMatchPolicy#ENABLED}.
* @see #getConstraintMatchTotalMap()
*/
Map<Object, Indictment<Score_>> getIndictmentMap();
/**
* @return used to check {@link #isWorkingEntityListDirty(long)} later on
*/
long getWorkingEntityListRevision();
int getWorkingGenuineEntityCount();
int getWorkingInitScore();
void executeMove(Move<Solution_> move);
/**
* Executes a move, finds out its score, and immediately undoes it.
*
* @param move never null
* @param assertMoveScoreFromScratch true will hurt performance
* @return never null
*/
InnerScore<Score_> executeTemporaryMove(Move<Solution_> move, boolean assertMoveScoreFromScratch);
/**
* @param expectedWorkingEntityListRevision an
* @return true if the entityList might have a different set of instances now
*/
boolean isWorkingEntityListDirty(long expectedWorkingEntityListRevision);
boolean isWorkingSolutionInitialized();
/**
* Some score directors keep a set of changes
* that they only apply when {@link #calculateScore()} is called.
* Until that happens, this set accumulates and could possibly act as a memory leak.
*
* @return true if the score director can potentially cause a memory leak due to unflushed changes.
*/
boolean requiresFlushing();
/**
* Inverse shadow variables have a fail-fast for cases
* where the shadow variable doesn't actually point to its correct inverse.
* This is very useful to pinpoint improperly initialized solutions.
* <p>
* However, {@link SolutionManager#update(Object)} exists precisely for the purpose of initializing solutions.
* And when this API is used, the fail-fast must not be triggered as it is guaranteed and expected
* that the inverse relationships will be wrong.
* In fact, they will be null.
* <p>
* For this case and this case only, this method is allowed to return false.
* All other cases must return true, otherwise a very valuable fail-fast is lost.
*
* @return false if the fail-fast on shadow variables should not be triggered
*/
boolean expectShadowVariablesInCorrectState();
/**
* @return never null
*/
ScoreDirectorFactory<Solution_, Score_> getScoreDirectorFactory();
/**
* @return never null
*/
SolutionDescriptor<Solution_> getSolutionDescriptor();
/**
* @return never null
*/
ScoreDefinition<Score_> getScoreDefinition();
/**
* Returns a planning clone of the solution,
* which is not a shallow clone nor a deep clone nor a partition clone.
*
* @return never null, planning clone
*/
default Solution_ cloneWorkingSolution() {
return cloneSolution(getWorkingSolution());
}
/**
* Returns a planning clone of the solution,
* which is not a shallow clone nor a deep clone nor a partition clone.
*
* @param originalSolution never null
* @return never null, planning clone
*/
Solution_ cloneSolution(Solution_ originalSolution);
/**
* @return at least 0L
*/
long getCalculationCount();
void resetCalculationCount();
void incrementCalculationCount();
/**
* @return never null
*/
SupplyManager getSupplyManager();
MoveDirector<Solution_, Score_> getMoveDirector();
ValueRangeManager<Solution_> getValueRangeManager();
ListVariableStateSupply<Solution_> getListVariableStateSupply(ListVariableDescriptor<Solution_> variableDescriptor);
InnerScoreDirector<Solution_, Score_> createChildThreadScoreDirector(ChildThreadType childThreadType);
/**
* Do not waste performance by propagating changes to step (or higher) mechanisms.
*
* @param allChangesWillBeUndoneBeforeStepEnds true if all changes will be undone
*/
void setAllChangesWillBeUndoneBeforeStepEnds(boolean allChangesWillBeUndoneBeforeStepEnds);
/**
* Asserts that if the {@link Score} is calculated for the current {@link PlanningSolution working solution}
* in the current {@link ScoreDirector} (with possibly incremental calculation residue),
* it is equal to the parameter {@link Score expectedWorkingScore}.
* <p>
* Used to assert that skipping {@link #calculateScore()} (when the score is otherwise determined) is correct.
*
* @param expectedWorkingScore never null
* @param completedAction sometimes null, when assertion fails then the completedAction's {@link Object#toString()}
* is included in the exception message
*/
void assertExpectedWorkingScore(InnerScore<Score_> expectedWorkingScore, Object completedAction);
/**
* Asserts that if all {@link VariableListener}s are forcibly triggered,
* and therefore all shadow variables are updated if needed,
* that none of the shadow variables of the {@link PlanningSolution working solution} change,
* Then also asserts that the {@link Score} calculated for the {@link PlanningSolution working solution} afterwards
* is equal to the parameter {@link Score expectedWorkingScore}.
* <p>
* Used to assert that the shadow variables' state is consistent with the genuine variables' state.
*
* @param expectedWorkingScore never null
* @param completedAction sometimes null, when assertion fails then the completedAction's {@link Object#toString()}
* is included in the exception message
*/
void assertShadowVariablesAreNotStale(InnerScore<Score_> expectedWorkingScore, Object completedAction);
/**
* Asserts that if the {@link Score} is calculated for the current {@link PlanningSolution working solution}
* in a fresh {@link ScoreDirector} (with no incremental calculation residue),
* it is equal to the parameter {@link Score workingScore}.
* <p>
* Furthermore, if the assert fails, a score corruption analysis might be included in the exception message.
*
* @param workingScore never null
* @param completedAction sometimes null, when assertion fails then the completedAction's {@link Object#toString()}
* is included in the exception message
* @see ScoreDirectorFactory#assertScoreFromScratch
*/
void assertWorkingScoreFromScratch(InnerScore<Score_> workingScore, Object completedAction);
/**
* Asserts that if the {@link Score} is calculated for the current {@link PlanningSolution working solution}
* in a fresh {@link ScoreDirector} (with no incremental calculation residue),
* it is equal to the parameter {@link Score predictedScore}.
* <p>
* Furthermore, if the assert fails, a score corruption analysis might be included in the exception message.
*
* @param predictedScore never null
* @param completedAction sometimes null, when assertion fails then the completedAction's {@link Object#toString()}
* is included in the exception message
* @see ScoreDirectorFactory#assertScoreFromScratch
*/
void assertPredictedScoreFromScratch(InnerScore<Score_> predictedScore, Object completedAction);
/**
* Asserts that if the {@link Score} is calculated for the current {@link PlanningSolution working solution}
* in the current {@link ScoreDirector} (with incremental calculation residue),
* it is equal to the parameter {@link Score beforeMoveScore}.
* <p>
* Furthermore, if the assert fails, a score corruption analysis might be included in the exception message.
*
* @param move never null
* @param beforeMoveScore never null
*/
void assertExpectedUndoMoveScore(Move<Solution_> move, InnerScore<Score_> beforeMoveScore,
SolverLifecyclePoint executionPoint);
/**
* Needs to be called after use because some implementations need to clean up their resources.
*/
@Override
void close();
/**
* Unlike {@link #triggerVariableListeners()} which only triggers notifications already in the queue,
* this triggers every variable listener on every genuine variable.
* This is useful in {@link SolutionManager#update(Object)} to fill in shadow variable values.
*/
void forceTriggerVariableListeners();
/**
* A derived score director is created from a root score director.
* The derived score director can be used to create separate* instances for use cases like multithreaded solving.
*/
default boolean isDerived() {
return false;
}
default ScoreAnalysis<Score_> buildScoreAnalysis(ScoreAnalysisFetchPolicy scoreAnalysisFetchPolicy) {
var state = calculateScore();
var constraintAnalysisMap = new TreeMap<ConstraintRef, ConstraintAnalysis<Score_>>();
for (var constraintMatchTotal : getConstraintMatchTotalMap().values()) {
var constraintAnalysis = getConstraintAnalysis(constraintMatchTotal, scoreAnalysisFetchPolicy);
constraintAnalysisMap.put(constraintMatchTotal.getConstraintRef(), constraintAnalysis);
}
return new ScoreAnalysis<>(state.raw(), constraintAnalysisMap, state.isFullyAssigned());
}
/*
* The following methods are copied here from ScoreDirector because they are deprecated there for removal.
* They will only be supported on this type, which serves for internal use only,
* as opposed to ScoreDirector, which is a public type.
* This way, we can ensure that these methods are used correctly and in a safe manner.
*/
default void beforeEntityAdded(Object entity) {
beforeEntityAdded(getSolutionDescriptor().findEntityDescriptorOrFail(entity.getClass()), entity);
}
void beforeEntityAdded(EntityDescriptor<Solution_> entityDescriptor, Object entity);
default void afterEntityAdded(Object entity) {
afterEntityAdded(getSolutionDescriptor().findEntityDescriptorOrFail(entity.getClass()), entity);
}
void afterEntityAdded(EntityDescriptor<Solution_> entityDescriptor, Object entity);
default void beforeEntityRemoved(Object entity) {
beforeEntityRemoved(getSolutionDescriptor().findEntityDescriptorOrFail(entity.getClass()), entity);
}
void beforeEntityRemoved(EntityDescriptor<Solution_> entityDescriptor, Object entity);
default void afterEntityRemoved(Object entity) {
afterEntityRemoved(getSolutionDescriptor().findEntityDescriptorOrFail(entity.getClass()), entity);
}
void afterEntityRemoved(EntityDescriptor<Solution_> entityDescriptor, Object entity);
void beforeProblemFactAdded(Object problemFact);
void afterProblemFactAdded(Object problemFact);
void beforeProblemPropertyChanged(Object problemFactOrEntity);
void afterProblemPropertyChanged(Object problemFactOrEntity);
void beforeProblemFactRemoved(Object problemFact);
void afterProblemFactRemoved(Object problemFact);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/director/RevertableScoreDirector.java | package ai.timefold.solver.core.impl.score.director;
import java.util.List;
public interface RevertableScoreDirector<Solution_> extends VariableDescriptorAwareScoreDirector<Solution_> {
/**
* Use this method to get a copy of all non-commited changes executed by the director so far.
*
* @param <Action_> The action type for recorded changes
*/
<Action_> List<Action_> copyChanges();
/**
* Use this method to revert all changes made by moves.
* The score director that implements this logic must be able to track every single change in the solution and
* restore it to its original state.
*/
void undoChanges();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/director/ScoreDirectorFactory.java | package ai.timefold.solver.core.impl.score.director;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @param <Score_> the score type to go with the solution
*/
public interface ScoreDirectorFactory<Solution_, Score_ extends Score<Score_>> {
/**
* @return never null
*/
SolutionDescriptor<Solution_> getSolutionDescriptor();
/**
* @return never null
*/
ScoreDefinition<Score_> getScoreDefinition();
AbstractScoreDirector.AbstractScoreDirectorBuilder<Solution_, Score_, ?, ?> createScoreDirectorBuilder();
default AbstractScoreDirector<Solution_, Score_, ?> buildScoreDirector() {
return createScoreDirectorBuilder().build();
}
/**
* @return never null
*/
InitializingScoreTrend getInitializingScoreTrend();
/**
* Asserts that if the {@link Score} is calculated for the parameter solution,
* it would be equal to the score of that parameter.
*
* @param solution never null
* @see InnerScoreDirector#assertWorkingScoreFromScratch(InnerScore, Object)
*/
void assertScoreFromScratch(Solution_ solution);
default boolean supportsConstraintMatching() {
return false;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/director/ScoreDirectorFactoryFactory.java | package ai.timefold.solver.core.impl.score.director;
import java.util.ArrayList;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.config.score.director.ScoreDirectorFactoryConfig;
import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.score.director.easy.EasyScoreDirectorFactory;
import ai.timefold.solver.core.impl.score.director.incremental.IncrementalScoreDirectorFactory;
import ai.timefold.solver.core.impl.score.director.stream.BavetConstraintStreamScoreDirectorFactory;
import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
public class ScoreDirectorFactoryFactory<Solution_, Score_ extends Score<Score_>> {
private final ScoreDirectorFactoryConfig config;
public ScoreDirectorFactoryFactory(ScoreDirectorFactoryConfig config) {
this.config = config;
}
public ScoreDirectorFactory<Solution_, Score_> buildScoreDirectorFactory(EnvironmentMode environmentMode,
SolutionDescriptor<Solution_> solutionDescriptor) {
var scoreDirectorFactory = decideMultipleScoreDirectorFactories(solutionDescriptor, environmentMode);
var assertionScoreDirectorFactory = config.getAssertionScoreDirectorFactory();
if (assertionScoreDirectorFactory != null) {
if (assertionScoreDirectorFactory.getAssertionScoreDirectorFactory() != null) {
throw new IllegalArgumentException(
"A assertionScoreDirectorFactory (%s) cannot have a non-null assertionScoreDirectorFactory (%s)."
.formatted(assertionScoreDirectorFactory,
assertionScoreDirectorFactory.getAssertionScoreDirectorFactory()));
}
if (environmentMode.compareTo(EnvironmentMode.STEP_ASSERT) > 0) {
throw new IllegalArgumentException(
"A non-null assertionScoreDirectorFactory (%s) requires an environmentMode (%s) of %s or lower."
.formatted(assertionScoreDirectorFactory, environmentMode, EnvironmentMode.STEP_ASSERT));
}
var assertionScoreDirectorFactoryFactory =
new ScoreDirectorFactoryFactory<Solution_, Score_>(assertionScoreDirectorFactory);
scoreDirectorFactory.setAssertionScoreDirectorFactory(assertionScoreDirectorFactoryFactory
.buildScoreDirectorFactory(EnvironmentMode.NON_REPRODUCIBLE, solutionDescriptor));
}
scoreDirectorFactory.setInitializingScoreTrend(InitializingScoreTrend.parseTrend(
config.getInitializingScoreTrend() == null ? InitializingScoreTrendLevel.ANY.name()
: config.getInitializingScoreTrend(),
solutionDescriptor.getScoreDefinition().getLevelsSize()));
if (environmentMode.isFullyAsserted()) {
scoreDirectorFactory.setAssertClonedSolution(true);
}
if (environmentMode.isTracking()) {
scoreDirectorFactory.setTrackingWorkingSolution(true);
}
return scoreDirectorFactory;
}
protected AbstractScoreDirectorFactory<Solution_, Score_, ?> decideMultipleScoreDirectorFactories(
SolutionDescriptor<Solution_> solutionDescriptor, EnvironmentMode environmentMode) {
if (!ConfigUtils.isEmptyCollection(config.getScoreDrlList())) {
throw new IllegalStateException(
"""
DRL constraints requested via scoreDrlList (%s), but this is no longer supported in Timefold Solver 0.9 and later.
Maybe upgrade from scoreDRL to ConstraintStreams using this recipe: https://timefold.ai/blog/migrating-score-drl-to-constraint-streams"""
.formatted(config.getScoreDrlList()));
}
assertCorrectDirectorFactory(config);
// At this point, we are guaranteed to have at most one score director factory selected.
if (config.getEasyScoreCalculatorClass() != null) {
return EasyScoreDirectorFactory.buildScoreDirectorFactory(solutionDescriptor, config);
} else if (config.getIncrementalScoreCalculatorClass() != null) {
return IncrementalScoreDirectorFactory.buildScoreDirectorFactory(solutionDescriptor, config);
} else if (config.getConstraintProviderClass() != null) {
return BavetConstraintStreamScoreDirectorFactory.buildScoreDirectorFactory(solutionDescriptor, config,
environmentMode);
} else {
throw new IllegalArgumentException(
"The scoreDirectorFactory lacks configuration for either constraintProviderClass, " +
"easyScoreCalculatorClass or incrementalScoreCalculatorClass.");
}
}
private static void assertCorrectDirectorFactory(ScoreDirectorFactoryConfig config) {
var easyScoreCalculatorClass = config.getEasyScoreCalculatorClass();
var hasEasyScoreCalculator = easyScoreCalculatorClass != null;
if (!hasEasyScoreCalculator && config.getEasyScoreCalculatorCustomProperties() != null) {
throw new IllegalStateException(
"If there is no easyScoreCalculatorClass (%s), then there can be no easyScoreCalculatorCustomProperties (%s) either."
.formatted(easyScoreCalculatorClass, config.getEasyScoreCalculatorCustomProperties()));
}
var incrementalScoreCalculatorClass = config.getIncrementalScoreCalculatorClass();
var hasIncrementalScoreCalculator = incrementalScoreCalculatorClass != null;
if (!hasIncrementalScoreCalculator && config.getIncrementalScoreCalculatorCustomProperties() != null) {
throw new IllegalStateException(
"If there is no incrementalScoreCalculatorClass (%s), then there can be no incrementalScoreCalculatorCustomProperties (%s) either."
.formatted(incrementalScoreCalculatorClass,
config.getIncrementalScoreCalculatorCustomProperties()));
}
var constraintProviderClass = config.getConstraintProviderClass();
var hasConstraintProvider = constraintProviderClass != null;
if (!hasConstraintProvider && config.getConstraintProviderCustomProperties() != null) {
throw new IllegalStateException(
"If there is no constraintProviderClass (%s), then there can be no constraintProviderCustomProperties (%s) either."
.formatted(constraintProviderClass, config.getConstraintProviderCustomProperties()));
}
if (hasEasyScoreCalculator && (hasIncrementalScoreCalculator || hasConstraintProvider)
|| (hasIncrementalScoreCalculator && hasConstraintProvider)) {
var scoreDirectorFactoryPropertyList = new ArrayList<String>(3);
if (hasEasyScoreCalculator) {
scoreDirectorFactoryPropertyList
.add("an easyScoreCalculatorClass (%s)".formatted(easyScoreCalculatorClass.getName()));
}
if (hasConstraintProvider) {
scoreDirectorFactoryPropertyList
.add("an constraintProviderClass (%s)".formatted(constraintProviderClass.getName()));
}
if (hasIncrementalScoreCalculator) {
scoreDirectorFactoryPropertyList.add("an incrementalScoreCalculatorClass (%s)"
.formatted(incrementalScoreCalculatorClass.getName()));
}
var joined = String.join(" and ", scoreDirectorFactoryPropertyList);
throw new IllegalArgumentException("The scoreDirectorFactory cannot have %s together."
.formatted(joined));
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/director/SessionContext.java | package ai.timefold.solver.core.impl.score.director;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.descriptor.ValueRangeDescriptor;
import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
import ai.timefold.solver.core.preview.api.move.SolutionView;
import org.jspecify.annotations.NullMarked;
/**
* Used throughout the solver to provide access to some internals of the score director
* required for initialization of Bavet nodes and other components.
* It is imperative that all of these values come from the same score director instance,
* because they are all tied to the same working solution.
* These values are only valid during the runtime of the session;
* new session requires a new {@link SessionContext} instance.
*/
@NullMarked
public record SessionContext<Solution_>(Solution_ workingSolution, SolutionView<Solution_> solutionView,
ValueRangeManager<Solution_> valueRangeManager, SupplyManager supplyManager) {
public SessionContext(InnerScoreDirector<Solution_, ?> scoreDirector) {
this(scoreDirector.getWorkingSolution(), scoreDirector.getMoveDirector(),
scoreDirector.getValueRangeManager(), scoreDirector.getSupplyManager());
}
public <T> CountableValueRange<T> getValueRange(ValueRangeDescriptor<Solution_> valueRangeDescriptor) {
return valueRangeManager.getFromSolution(valueRangeDescriptor);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/director/SolutionInitializationStatistics.java | package ai.timefold.solver.core.impl.score.director;
/**
* @param genuineEntityCount
* @param shadowEntityCount
* @param uninitializedEntityCount
* @param uninitializedVariableCount Zero if unassigned values are allowed.
* @param unassignedValueCount How many values aren't in any list variable,
* assuming unassigned values aren't allowed.
* Otherwise zero.
* @param notInAnyListValueCount How many values aren't in any list variable,
* regardless of whether unassigned values are allowed.
*/
public record SolutionInitializationStatistics(int genuineEntityCount, int shadowEntityCount, int uninitializedEntityCount,
int uninitializedVariableCount, int unassignedValueCount, int notInAnyListValueCount) {
public int getInitCount() {
return uninitializedVariableCount + uninitializedEntityCount;
}
public boolean isInitialized() {
return getInitCount() == 0;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/director/ValueRangeManager.java | package ai.timefold.solver.core.impl.score.director;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.api.solver.ProblemSizeStatistics;
import ai.timefold.solver.core.api.solver.change.ProblemChange;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.solution.descriptor.ProblemScaleTracker;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.domain.valuerange.buildin.bigdecimal.BigDecimalValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.buildin.composite.NullAllowingCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.buildin.primdouble.DoubleValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.descriptor.ValueRangeDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.common.ReachableValues;
import ai.timefold.solver.core.impl.heuristic.selector.common.ReachableValues.ReachableItemValue;
import ai.timefold.solver.core.impl.util.MathUtils;
import ai.timefold.solver.core.impl.util.MutableInt;
import ai.timefold.solver.core.impl.util.MutableLong;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Caches value ranges for the current working solution,
* allowing to quickly access these cached value ranges when needed.
*
* <p>
* Outside a {@link ProblemChange}, value ranges are not allowed to change.
* Call {@link #reset(Object)} every time the working solution changes through a problem fact,
* so that all caches can be invalidated.
*
* <p>
* Two score directors can never share the same instance of this class;
* this class contains state that is specific to a particular instance of a working solution.
* Even a clone of that same solution must not share the same instance of this class,
* unless {@link #reset(Object)} is called with the clone;
* failing to follow this rule will result in score corruptions as the cached value ranges reference
* objects from the original working solution pre-clone.
*
* @see CountableValueRange
* @see ValueRangeProvider
*/
@NullMarked
public final class ValueRangeManager<Solution_> {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final SolutionDescriptor<Solution_> solutionDescriptor;
private final CountableValueRange<?>[] fromSolution;
private final ReachableValues[] reachableValues;
private final Map<Object, CountableValueRange<?>[]> fromEntityMap =
new IdentityHashMap<>();
private @Nullable Solution_ cachedWorkingSolution = null;
private @Nullable SolutionInitializationStatistics cachedInitializationStatistics = null;
private @Nullable ProblemSizeStatistics cachedProblemSizeStatistics = null;
public static <Solution_> ValueRangeManager<Solution_> of(SolutionDescriptor<Solution_> solutionDescriptor,
Solution_ solution) {
var valueRangeManager = new ValueRangeManager<>(solutionDescriptor);
valueRangeManager.reset(solution);
return valueRangeManager;
}
/**
* It is not recommended for code other than {@link ScoreDirector} to create instances of this class.
* See class-level documentation for more details.
* For safety, prefer using {@link #of(SolutionDescriptor, Object)} to create an instance of this class
* with a solution already set.
*/
public ValueRangeManager(SolutionDescriptor<Solution_> solutionDescriptor) {
this.solutionDescriptor = Objects.requireNonNull(solutionDescriptor);
this.fromSolution = new CountableValueRange[solutionDescriptor.getValueRangeDescriptorCount()];
this.reachableValues = new ReachableValues[solutionDescriptor.getValueRangeDescriptorCount()];
}
public SolutionInitializationStatistics getInitializationStatistics() {
if (cachedWorkingSolution == null) {
throw new IllegalStateException(
"Impossible state: initialization statistics requested before the working solution is known.");
}
return getInitializationStatistics(null);
}
public SolutionInitializationStatistics getInitializationStatistics(@Nullable Consumer<Object> finisher) {
if (cachedWorkingSolution == null) {
throw new IllegalStateException(
"Impossible state: initialization statistics requested before the working solution is known.");
}
if (finisher == null) {
if (cachedInitializationStatistics == null) {
cachedInitializationStatistics = computeInitializationStatistics(cachedWorkingSolution, null);
}
} else {
// If a finisher is provided, we always recompute the statistics,
// because the finisher is expected to be called for every entity.
cachedInitializationStatistics = computeInitializationStatistics(cachedWorkingSolution, finisher);
}
return cachedInitializationStatistics;
}
public SolutionInitializationStatistics computeInitializationStatistics(Solution_ solution,
@Nullable Consumer<Object> finisher) {
/*
* The score director requires all of these data points,
* so we calculate them all in a single pass over the entities.
* This is an important performance improvement,
* as there are potentially thousands of entities.
*/
var uninitializedEntityCount = new MutableInt();
var uninitializedVariableCount = new MutableInt();
var unassignedValueCount = new MutableInt();
var notInAnyListValueCount = new MutableInt();
var genuineEntityCount = new MutableInt();
var shadowEntityCount = new MutableInt();
var listVariableDescriptor = solutionDescriptor.getListVariableDescriptor();
if (listVariableDescriptor != null) {
var countOnSolution = (int) countOnSolution(listVariableDescriptor.getValueRangeDescriptor(), solution);
notInAnyListValueCount.add(countOnSolution);
if (!listVariableDescriptor.allowsUnassignedValues()) {
// We count every possibly unassigned element in every list variable.
// And later we subtract the assigned elements.
unassignedValueCount.add(countOnSolution);
}
}
solutionDescriptor.visitAllEntities(solution, entity -> {
var entityDescriptor = solutionDescriptor.findEntityDescriptorOrFail(entity.getClass());
if (entityDescriptor.isGenuine()) {
genuineEntityCount.increment();
var uninitializedVariableCountForEntity = entityDescriptor.countUninitializedVariables(entity);
if (uninitializedVariableCountForEntity > 0) {
uninitializedEntityCount.increment();
uninitializedVariableCount.add(uninitializedVariableCountForEntity);
}
} else {
shadowEntityCount.increment();
}
if (finisher != null) {
finisher.accept(entity);
}
if (!entityDescriptor.hasAnyGenuineListVariables()) {
return;
}
var listVariableEntityDescriptor = listVariableDescriptor.getEntityDescriptor();
var countOnEntity = listVariableDescriptor.getListSize(entity);
notInAnyListValueCount.subtract(countOnEntity);
if (!listVariableDescriptor.allowsUnassignedValues() && listVariableEntityDescriptor.matchesEntity(entity)) {
unassignedValueCount.subtract(countOnEntity);
}
// TODO maybe detect duplicates and elements that are outside the value range
});
return new SolutionInitializationStatistics(genuineEntityCount.intValue(),
shadowEntityCount.intValue(),
uninitializedEntityCount.intValue(), uninitializedVariableCount.intValue(), unassignedValueCount.intValue(),
notInAnyListValueCount.intValue());
}
public ProblemSizeStatistics getProblemSizeStatistics() {
if (cachedWorkingSolution == null) {
throw new IllegalStateException("Impossible state: problem size requested before the working solution is known.");
} else if (cachedProblemSizeStatistics == null) {
cachedProblemSizeStatistics = new ProblemSizeStatistics(
solutionDescriptor.getGenuineEntityCount(cachedWorkingSolution),
solutionDescriptor.getGenuineVariableCount(cachedWorkingSolution),
getApproximateValueCount(),
getProblemScale());
}
return cachedProblemSizeStatistics;
}
long getApproximateValueCount() {
var genuineVariableDescriptorSet =
Collections.newSetFromMap(new IdentityHashMap<GenuineVariableDescriptor<Solution_>, Boolean>());
solutionDescriptor.visitAllEntities(cachedWorkingSolution, entity -> {
var entityDescriptor = solutionDescriptor.findEntityDescriptorOrFail(entity.getClass());
if (entityDescriptor.isGenuine()) {
genuineVariableDescriptorSet.addAll(entityDescriptor.getGenuineVariableDescriptorList());
}
});
var out = new MutableLong();
for (var variableDescriptor : genuineVariableDescriptorSet) {
var valueRangeDescriptor = variableDescriptor.getValueRangeDescriptor();
if (valueRangeDescriptor.canExtractValueRangeFromSolution()) {
out.add(countOnSolution(valueRangeDescriptor, cachedWorkingSolution));
} else {
solutionDescriptor.visitEntitiesByEntityClass(cachedWorkingSolution,
variableDescriptor.getEntityDescriptor().getEntityClass(),
entity -> {
out.add(countOnEntity(valueRangeDescriptor, entity));
return false;
});
}
}
return out.longValue();
}
/**
* Calculates an indication of the size of the problem instance.
* This is approximately the base 10 logarithm of the search space size.
*
* <p>
* The method uses a logarithmic scale to estimate the problem size,
* where the base of the logarithm is determined by the maximum value range size.
* It accounts for both basic variables and list variables in the solution,
* considering pinned values and value ranges on both entity and solution.
*
* @return A non-negative double value representing the approximate base 10 logarithm of the search space size.
* Returns {@code 0} if the calculation results in NaN or infinity.
*/
double getProblemScale() {
var logBase = Math.max(2, getMaximumValueRangeSize());
var problemScaleTracker = new ProblemScaleTracker(logBase);
solutionDescriptor.visitAllEntities(cachedWorkingSolution, entity -> {
var entityDescriptor = solutionDescriptor.findEntityDescriptorOrFail(entity.getClass());
if (entityDescriptor.isGenuine()) {
processProblemScale(entityDescriptor, entity, problemScaleTracker);
}
});
var result = problemScaleTracker.getBasicProblemScaleLog();
if (problemScaleTracker.getListTotalEntityCount() != 0L) {
// List variables do not support from entity value ranges
var totalListValueCount = problemScaleTracker.getListTotalValueCount();
var totalListMovableValueCount = totalListValueCount - problemScaleTracker.getListPinnedValueCount();
var possibleTargetsForListValue = problemScaleTracker.getListMovableEntityCount();
var listVariableDescriptor = solutionDescriptor.getListVariableDescriptor();
if (listVariableDescriptor != null && listVariableDescriptor.allowsUnassignedValues()) {
// Treat unassigned values as assigned to a single virtual vehicle for the sake of this calculation
possibleTargetsForListValue++;
}
result += MathUtils.getPossibleArrangementsScaledApproximateLog(MathUtils.LOG_PRECISION, logBase,
totalListMovableValueCount, possibleTargetsForListValue);
}
var scale = (result / (double) MathUtils.LOG_PRECISION) / MathUtils.getLogInBase(logBase, 10d);
if (Double.isNaN(scale) || Double.isInfinite(scale)) {
return 0;
}
return scale;
}
/**
* Calculates the maximum value range size across all entities in the working solution.
* <p>
* The "maximum value range size" is defined as the largest number of possible values
* for any genuine variable across all entities.
* This is determined by inspecting the value range descriptors of each variable in each entity.
*
* @return The maximum value range size, or 0 if no genuine variables are found.
*/
long getMaximumValueRangeSize() {
return solutionDescriptor.extractAllEntitiesStream(cachedWorkingSolution)
.mapToLong(entity -> {
var entityDescriptor = solutionDescriptor.findEntityDescriptorOrFail(entity.getClass());
return entityDescriptor.isGenuine()
? getMaximumValueCount(entityDescriptor, entity)
: 0L;
})
.max()
.orElse(0L);
}
private long getMaximumValueCount(EntityDescriptor<Solution_> entityDescriptor, Object entity) {
var maximumValueCount = 0L;
for (var variableDescriptor : entityDescriptor.getGenuineVariableDescriptorList()) {
if (variableDescriptor.canExtractValueRangeFromSolution()) {
maximumValueCount = Math.max(maximumValueCount,
countOnSolution(variableDescriptor.getValueRangeDescriptor(), cachedWorkingSolution));
} else {
maximumValueCount =
Math.max(maximumValueCount, countOnEntity(variableDescriptor.getValueRangeDescriptor(), entity));
}
}
return maximumValueCount;
}
private void processProblemScale(EntityDescriptor<Solution_> entityDescriptor, Object entity, ProblemScaleTracker tracker) {
for (var variableDescriptor : entityDescriptor.getGenuineVariableDescriptorList()) {
var valueCount = variableDescriptor.canExtractValueRangeFromSolution()
? countOnSolution(variableDescriptor.getValueRangeDescriptor(), cachedWorkingSolution)
: countOnEntity(variableDescriptor.getValueRangeDescriptor(), entity);
// TODO: When minimum Java supported is 21, this can be replaced with a sealed interface switch
if (variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor) {
if (basicVariableDescriptor.isChained()) {
// An entity is a value
tracker.addListValueCount(1);
if (!entityDescriptor.isMovable(cachedWorkingSolution, entity)) {
tracker.addPinnedListValueCount(1);
}
// Anchors are entities
var valueRange = variableDescriptor.canExtractValueRangeFromSolution()
? getFromSolution(variableDescriptor.getValueRangeDescriptor(), cachedWorkingSolution)
: getFromEntity(variableDescriptor.getValueRangeDescriptor(), entity);
var valueIterator = valueRange.createOriginalIterator();
while (valueIterator.hasNext()) {
var value = valueIterator.next();
if (variableDescriptor.isValuePotentialAnchor(value)) {
if (tracker.isAnchorVisited(value)) {
continue;
}
// Assumes anchors are not pinned
tracker.incrementListEntityCount(true);
}
}
} else {
if (entityDescriptor.isMovable(cachedWorkingSolution, entity)) {
tracker.addBasicProblemScale(valueCount);
}
}
} else if (variableDescriptor instanceof ListVariableDescriptor<Solution_> listVariableDescriptor) {
var size = countOnSolution(listVariableDescriptor.getValueRangeDescriptor(), cachedWorkingSolution);
tracker.setListTotalValueCount((int) size);
if (entityDescriptor.isMovable(cachedWorkingSolution, entity)) {
tracker.incrementListEntityCount(true);
tracker.addPinnedListValueCount(listVariableDescriptor.getFirstUnpinnedIndex(entity));
} else {
tracker.incrementListEntityCount(false);
tracker.addPinnedListValueCount(listVariableDescriptor.getListSize(entity));
}
} else {
throw new IllegalStateException(
"Unhandled subclass of %s encountered (%s).".formatted(VariableDescriptor.class.getSimpleName(),
variableDescriptor.getClass().getSimpleName()));
}
}
}
/**
* As {@link #getFromSolution(ValueRangeDescriptor, Object)}, but the solution is taken from the cached working solution.
* This requires {@link #reset(Object)} to be called before the first call to this method,
* and therefore this method will throw an exception if called before the score director is instantiated.
*
* @throws IllegalStateException if called before {@link #reset(Object)} is called
*/
public <T> CountableValueRange<T> getFromSolution(ValueRangeDescriptor<Solution_> valueRangeDescriptor) {
if (cachedWorkingSolution == null) {
throw new IllegalStateException(
"Impossible state: value range (%s) requested before the working solution is known."
.formatted(valueRangeDescriptor));
}
return getFromSolution(valueRangeDescriptor, cachedWorkingSolution);
}
@SuppressWarnings("unchecked")
public <T> CountableValueRange<T> getFromSolution(ValueRangeDescriptor<Solution_> valueRangeDescriptor,
Solution_ solution) {
var valueRange = fromSolution[valueRangeDescriptor.getOrdinal()];
if (valueRange == null) { // Avoid computeIfAbsent on the hot path; creates capturing lambda instances.
var extractedValueRange = valueRangeDescriptor.<T> extractAllValues(Objects.requireNonNull(solution));
if (!(extractedValueRange instanceof CountableValueRange<T> countableValueRange)) {
throw new UnsupportedOperationException("""
Impossible state: value range (%s) on planning solution (%s) is not countable.
Maybe replace %s with %s."""
.formatted(valueRangeDescriptor, solution, DoubleValueRange.class.getSimpleName(),
BigDecimalValueRange.class.getSimpleName()));
} else if (valueRangeDescriptor.acceptsNullInValueRange()) {
valueRange = new NullAllowingCountableValueRange<>(countableValueRange);
} else {
valueRange = countableValueRange;
}
fromSolution[valueRangeDescriptor.getOrdinal()] = valueRange;
}
return (CountableValueRange<T>) valueRange;
}
/**
* @throws IllegalStateException if called before {@link #reset(Object)} is called
*/
@SuppressWarnings("unchecked")
public <T> CountableValueRange<T> getFromEntity(ValueRangeDescriptor<Solution_> valueRangeDescriptor, Object entity) {
if (cachedWorkingSolution == null) {
throw new IllegalStateException(
"Impossible state: value range (%s) on planning entity (%s) requested before the working solution is known."
.formatted(valueRangeDescriptor, entity));
}
var valueRangeList =
fromEntityMap.computeIfAbsent(entity,
e -> new CountableValueRange[solutionDescriptor.getValueRangeDescriptorCount()]);
var valueRange = valueRangeList[valueRangeDescriptor.getOrdinal()];
if (valueRange == null) { // Avoid computeIfAbsent on the hot path; creates capturing lambda instances.
var extractedValueRange =
valueRangeDescriptor.<T> extractValuesFromEntity(cachedWorkingSolution, Objects.requireNonNull(entity));
if (!(extractedValueRange instanceof CountableValueRange<T> countableValueRange)) {
throw new UnsupportedOperationException("""
Impossible state: value range (%s) on planning entity (%s) is not countable.
Maybe replace %s with %s."""
.formatted(valueRangeDescriptor, entity, DoubleValueRange.class.getSimpleName(),
BigDecimalValueRange.class.getSimpleName()));
} else if (valueRangeDescriptor.acceptsNullInValueRange()) {
valueRange = new NullAllowingCountableValueRange<>(countableValueRange);
} else {
valueRange = countableValueRange;
}
valueRangeList[valueRangeDescriptor.getOrdinal()] = valueRange;
}
return (CountableValueRange<T>) valueRange;
}
public long countOnSolution(ValueRangeDescriptor<Solution_> valueRangeDescriptor, Solution_ solution) {
return getFromSolution(valueRangeDescriptor, solution)
.getSize();
}
public long countOnEntity(ValueRangeDescriptor<Solution_> valueRangeDescriptor, Object entity) {
return getFromEntity(valueRangeDescriptor, entity)
.getSize();
}
public ReachableValues getReachableValues(GenuineVariableDescriptor<Solution_> variableDescriptor) {
var values = reachableValues[variableDescriptor.getValueRangeDescriptor().getOrdinal()];
if (values != null) {
return values;
}
if (cachedWorkingSolution == null) {
throw new IllegalStateException(
"Impossible state: value reachability requested before the working solution is known.");
}
var entityDescriptor = variableDescriptor.getEntityDescriptor();
var entityList = entityDescriptor.extractEntities(cachedWorkingSolution);
var allValues = getFromSolution(variableDescriptor.getValueRangeDescriptor());
var valuesSize = allValues.getSize();
if (valuesSize > Integer.MAX_VALUE) {
throw new IllegalStateException(
"The matrix %s cannot be built for the entity %s (%s) because value range has a size (%d) which is higher than Integer.MAX_VALUE."
.formatted(ReachableValues.class.getSimpleName(),
entityDescriptor.getEntityClass().getSimpleName(),
variableDescriptor.getVariableName(), valuesSize));
}
Class<?> valueClass = null;
var idx = 0;
while (valueClass == null && idx < allValues.getSize()) {
var value = allValues.get(idx++);
if (value == null) {
continue;
}
valueClass = value.getClass();
break;
}
Map<Object, ReachableItemValue> reachableValuesMap = ConfigUtils.isGenericTypeImmutable(valueClass)
? new HashMap<>((int) valuesSize)
: new IdentityHashMap<>((int) valuesSize);
for (var entity : entityList) {
var range = getFromEntity(variableDescriptor.getValueRangeDescriptor(), entity);
for (var i = 0; i < range.getSize(); i++) {
var value = range.get(i);
if (value == null) {
continue;
}
var item = initReachableMap(reachableValuesMap, value, entityList.size(), (int) valuesSize);
item.addEntity(entity);
for (int j = i + 1; j < range.getSize(); j++) {
var otherValue = range.get(j);
if (otherValue == null) {
continue;
}
item.addValue(otherValue);
var otherValueItem =
initReachableMap(reachableValuesMap, otherValue, entityList.size(), (int) valuesSize);
otherValueItem.addValue(value);
}
}
}
values = new ReachableValues(reachableValuesMap, valueClass,
variableDescriptor.getValueRangeDescriptor().acceptsNullInValueRange());
reachableValues[variableDescriptor.getValueRangeDescriptor().getOrdinal()] = values;
return values;
}
private static ReachableItemValue initReachableMap(Map<Object, ReachableItemValue> reachableValuesMap, Object value,
int entityListSize, int valueListSize) {
var item = reachableValuesMap.get(value);
if (item == null) {
item = new ReachableItemValue(value, entityListSize, valueListSize);
reachableValuesMap.put(value, item);
}
return item;
}
public void reset(@Nullable Solution_ workingSolution) {
Arrays.fill(fromSolution, null);
Arrays.fill(reachableValues, null);
fromEntityMap.clear();
// We only update the cached solution if it is not null; null means to only reset the maps.
if (workingSolution != null) {
cachedWorkingSolution = workingSolution;
cachedInitializationStatistics = null;
cachedProblemSizeStatistics = null;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/director/VariableDescriptorAwareScoreDirector.java | package ai.timefold.solver.core.impl.score.director;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
public interface VariableDescriptorAwareScoreDirector<Solution_>
extends ScoreDirector<Solution_> {
SolutionDescriptor<Solution_> getSolutionDescriptor();
// ************************************************************************
// Basic variable
// ************************************************************************
void beforeVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity);
void afterVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity);
default void changeVariableFacade(VariableDescriptor<Solution_> variableDescriptor, Object entity, Object newValue) {
beforeVariableChanged(variableDescriptor, entity);
variableDescriptor.setValue(entity, newValue);
afterVariableChanged(variableDescriptor, entity);
}
// ************************************************************************
// List variable
// ************************************************************************
/**
* Call this for each element that will be assigned (added to a list variable of one entity without being removed
* from a list variable of another entity).
*
* @param variableDescriptor the list variable descriptor
* @param element the assigned element
*/
void beforeListVariableElementAssigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element);
/**
* Call this for each element that was assigned (added to a list variable of one entity without being removed
* from a list variable of another entity).
*
* @param variableDescriptor the list variable descriptor
* @param element the assigned element
*/
void afterListVariableElementAssigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element);
/**
* Call this for each element that will be unassigned (removed from a list variable of one entity without being added
* to a list variable of another entity).
*
* @param variableDescriptor the list variable descriptor
* @param element the unassigned element
*/
void beforeListVariableElementUnassigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element);
/**
* Call this for each element that was unassigned (removed from a list variable of one entity without being added
* to a list variable of another entity).
*
* @param variableDescriptor the list variable descriptor
* @param element the unassigned element
*/
void afterListVariableElementUnassigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element);
/**
* Notify the score director before a list variable changes.
* <p>
* The list variable change includes:
* <ul>
* <li>Changing position (index) of one or more elements.</li>
* <li>Removing one or more elements from the list variable.</li>
* <li>Adding one or more elements to the list variable.</li>
* <li>Any mix of the above.</li>
* </ul>
* For the sake of variable listeners' efficiency, the change notification requires an index range that contains elements
* affected by the change. The range starts at {@code fromIndex} (inclusive) and ends at {@code toIndex} (exclusive).
* <p>
* The range has to comply with the following contract:
* <ol>
* <li>{@code fromIndex} must be greater than or equal to 0; {@code toIndex} must be less than or equal to the list variable
* size.</li>
* <li>{@code toIndex} must be greater than or equal to {@code fromIndex}.</li>
* <li>The range must contain all elements that are going to be changed.</li>
* <li>The range is allowed to contain elements that are not going to be changed.</li>
* <li>The range may be empty ({@code fromIndex} equals {@code toIndex}) if none of the existing list variable elements
* are going to be changed.</li>
* </ol>
* <p>
* {@link #beforeListVariableElementUnassigned(ListVariableDescriptor, Object)} must be called for each element
* that will be unassigned (removed from a list variable of one entity without being added
* to a list variable of another entity).
*
* @param variableDescriptor descriptor of the list variable being changed
* @param entity the entity owning the list variable being changed
* @param fromIndex low endpoint (inclusive) of the changed range
* @param toIndex high endpoint (exclusive) of the changed range
*/
void beforeListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex,
int toIndex);
/**
* Notify the score director after a list variable changes.
* <p>
* The list variable change includes:
* <ul>
* <li>Changing position (index) of one or more elements.</li>
* <li>Removing one or more elements from the list variable.</li>
* <li>Adding one or more elements to the list variable.</li>
* <li>Any mix of the above.</li>
* </ul>
* For the sake of variable listeners' efficiency, the change notification requires an index range that contains elements
* affected by the change. The range starts at {@code fromIndex} (inclusive) and ends at {@code toIndex} (exclusive).
* <p>
* The range has to comply with the following contract:
* <ol>
* <li>{@code fromIndex} must be greater than or equal to 0; {@code toIndex} must be less than or equal to the list variable
* size.</li>
* <li>{@code toIndex} must be greater than or equal to {@code fromIndex}.</li>
* <li>The range must contain all elements that have changed.</li>
* <li>The range is allowed to contain elements that have not changed.</li>
* <li>The range may be empty ({@code fromIndex} equals {@code toIndex}) if none of the existing list variable elements
* have changed.</li>
* </ol>
* <p>
* {@link #afterListVariableElementUnassigned(ListVariableDescriptor, Object)} must be called for each element
* that was unassigned (removed from a list variable of one entity without being added
* to a list variable of another entity).
*
* @param variableDescriptor descriptor of the list variable being changed
* @param entity the entity owning the list variable being changed
* @param fromIndex low endpoint (inclusive) of the changed range
* @param toIndex high endpoint (exclusive) of the changed range
*/
void afterListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex,
int toIndex);
// ************************************************************************
// Overloads without known variable descriptors
// ************************************************************************
VariableDescriptorCache<Solution_> getVariableDescriptorCache();
ValueRangeManager<Solution_> getValueRangeManager();
@Override
default void beforeVariableChanged(Object entity, String variableName) {
beforeVariableChanged(getVariableDescriptorCache().getVariableDescriptor(entity, variableName), entity);
}
@Override
default void afterVariableChanged(Object entity, String variableName) {
afterVariableChanged(getVariableDescriptorCache().getVariableDescriptor(entity, variableName), entity);
}
@Override
default void beforeListVariableElementAssigned(Object entity, String variableName, Object element) {
beforeListVariableElementAssigned(getVariableDescriptorCache().getListVariableDescriptor(entity, variableName),
element);
}
@Override
default void afterListVariableElementAssigned(Object entity, String variableName, Object element) {
afterListVariableElementAssigned(getVariableDescriptorCache().getListVariableDescriptor(entity, variableName), element);
}
@Override
default void beforeListVariableElementUnassigned(Object entity, String variableName, Object element) {
beforeListVariableElementUnassigned(getVariableDescriptorCache().getListVariableDescriptor(entity, variableName),
element);
}
@Override
default void afterListVariableElementUnassigned(Object entity, String variableName, Object element) {
afterListVariableElementUnassigned(getVariableDescriptorCache().getListVariableDescriptor(entity, variableName),
element);
}
@Override
default void beforeListVariableChanged(Object entity, String variableName, int fromIndex, int toIndex) {
beforeListVariableChanged(getVariableDescriptorCache().getListVariableDescriptor(entity, variableName), entity,
fromIndex,
toIndex);
}
@Override
default void afterListVariableChanged(Object entity, String variableName, int fromIndex, int toIndex) {
afterListVariableChanged(getVariableDescriptorCache().getListVariableDescriptor(entity, variableName), entity,
fromIndex,
toIndex);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score | java-sources/ai/timefold/solver/timefold-solver-core/1.26.1/ai/timefold/solver/core/impl/score/director/VariableDescriptorCache.java | package ai.timefold.solver.core.impl.score.director;
import java.util.Objects;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
/**
* Each before/after event needs to look up a variable descriptor.
* These operations are not cheap, they are very frequent and they often end up looking up the same descriptor.
* These caches are used to avoid looking up the same descriptor multiple times.
*
* @param <Solution_>
*/
public final class VariableDescriptorCache<Solution_> {
private final SolutionDescriptor<Solution_> solutionDescriptor;
private Class<?> basicVarDescritorCacheClass = null;
private String basicVarDescriptorCacheName = null;
private VariableDescriptor<Solution_> basicVarDescriptorCache = null;
private Class<?> listVarDescritorCacheClass = null;
private String listVarDescriptorCacheName = null;
private ListVariableDescriptor<Solution_> listVarDescriptorCache = null;
public VariableDescriptorCache(SolutionDescriptor<Solution_> solutionDescriptor) {
this.solutionDescriptor = solutionDescriptor;
}
public VariableDescriptor<Solution_> getVariableDescriptor(Object entity, String variableName) {
if (!Objects.equals(basicVarDescritorCacheClass, entity.getClass())
|| !Objects.equals(basicVarDescriptorCacheName, variableName)) {
basicVarDescritorCacheClass = entity.getClass();
basicVarDescriptorCacheName = variableName;
basicVarDescriptorCache = solutionDescriptor.findVariableDescriptorOrFail(entity, variableName);
}
return basicVarDescriptorCache;
}
public ListVariableDescriptor<Solution_> getListVariableDescriptor(Object entity, String variableName) {
if (!Objects.equals(listVarDescritorCacheClass, entity.getClass())
|| !Objects.equals(listVarDescriptorCacheName, variableName)) {
listVarDescritorCacheClass = entity.getClass();
listVarDescriptorCacheName = variableName;
listVarDescriptorCache =
(ListVariableDescriptor<Solution_>) solutionDescriptor.findVariableDescriptorOrFail(entity, variableName);
}
return listVarDescriptorCache;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.