index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/heuristic/selector/value | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/heuristic/selector/value/chained/SubChainSelectorConfig.java | package ai.timefold.solver.core.config.heuristic.selector.value.chained;
import java.util.function.Consumer;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
import ai.timefold.solver.core.config.heuristic.selector.SelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig;
import ai.timefold.solver.core.config.util.ConfigUtils;
@XmlType(propOrder = {
"valueSelectorConfig",
"minimumSubChainSize",
"maximumSubChainSize"
})
public class SubChainSelectorConfig extends SelectorConfig<SubChainSelectorConfig> {
@XmlElement(name = "valueSelector")
protected ValueSelectorConfig valueSelectorConfig = null;
protected Integer minimumSubChainSize = null;
protected Integer maximumSubChainSize = null;
public ValueSelectorConfig getValueSelectorConfig() {
return valueSelectorConfig;
}
public void setValueSelectorConfig(ValueSelectorConfig valueSelectorConfig) {
this.valueSelectorConfig = valueSelectorConfig;
}
/**
* @return sometimes null
*/
public Integer getMinimumSubChainSize() {
return minimumSubChainSize;
}
public void setMinimumSubChainSize(Integer minimumSubChainSize) {
this.minimumSubChainSize = minimumSubChainSize;
}
public Integer getMaximumSubChainSize() {
return maximumSubChainSize;
}
public void setMaximumSubChainSize(Integer maximumSubChainSize) {
this.maximumSubChainSize = maximumSubChainSize;
}
// ************************************************************************
// With methods
// ************************************************************************
public SubChainSelectorConfig withValueSelectorConfig(ValueSelectorConfig valueSelectorConfig) {
this.setValueSelectorConfig(valueSelectorConfig);
return this;
}
public SubChainSelectorConfig withMinimumSubChainSize(Integer minimumSubChainSize) {
this.setMinimumSubChainSize(minimumSubChainSize);
return this;
}
public SubChainSelectorConfig withMaximumSubChainSize(Integer maximumSubChainSize) {
this.setMaximumSubChainSize(maximumSubChainSize);
return this;
}
@Override
public SubChainSelectorConfig inherit(SubChainSelectorConfig inheritedConfig) {
valueSelectorConfig = ConfigUtils.inheritConfig(valueSelectorConfig, inheritedConfig.getValueSelectorConfig());
minimumSubChainSize = ConfigUtils.inheritOverwritableProperty(minimumSubChainSize,
inheritedConfig.getMinimumSubChainSize());
maximumSubChainSize = ConfigUtils.inheritOverwritableProperty(maximumSubChainSize,
inheritedConfig.getMaximumSubChainSize());
return this;
}
@Override
public SubChainSelectorConfig copyConfig() {
return new SubChainSelectorConfig().inherit(this);
}
@Override
public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {
if (valueSelectorConfig != null) {
valueSelectorConfig.visitReferencedClasses(classVisitor);
}
}
@Override
public boolean hasNearbySelectionConfig() {
return valueSelectorConfig != null && valueSelectorConfig.hasNearbySelectionConfig();
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + valueSelectorConfig + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/localsearch/LocalSearchPhaseConfig.java | package ai.timefold.solver.core.config.localsearch;
import java.util.function.Consumer;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlElements;
import jakarta.xml.bind.annotation.XmlType;
import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.composite.CartesianProductMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.factory.MoveIteratorFactoryConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.factory.MoveListFactoryConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.PillarChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.PillarSwapMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.SwapMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.SubChainSwapMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.TailChainSwapMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListSwapMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.SubListChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.SubListSwapMoveSelectorConfig;
import ai.timefold.solver.core.config.localsearch.decider.acceptor.LocalSearchAcceptorConfig;
import ai.timefold.solver.core.config.localsearch.decider.forager.LocalSearchForagerConfig;
import ai.timefold.solver.core.config.phase.PhaseConfig;
import ai.timefold.solver.core.config.util.ConfigUtils;
@XmlType(propOrder = {
"localSearchType",
"moveSelectorConfig",
"acceptorConfig",
"foragerConfig"
})
public class LocalSearchPhaseConfig extends PhaseConfig<LocalSearchPhaseConfig> {
public static final String XML_ELEMENT_NAME = "localSearch";
// Warning: all fields are null (and not defaulted) because they can be inherited
// and also because the input config file should match the output config file
protected LocalSearchType localSearchType = null;
@XmlElements({
@XmlElement(name = CartesianProductMoveSelectorConfig.XML_ELEMENT_NAME,
type = CartesianProductMoveSelectorConfig.class),
@XmlElement(name = ChangeMoveSelectorConfig.XML_ELEMENT_NAME, type = ChangeMoveSelectorConfig.class),
@XmlElement(name = ListChangeMoveSelectorConfig.XML_ELEMENT_NAME, type = ListChangeMoveSelectorConfig.class),
@XmlElement(name = ListSwapMoveSelectorConfig.XML_ELEMENT_NAME, type = ListSwapMoveSelectorConfig.class),
@XmlElement(name = MoveIteratorFactoryConfig.XML_ELEMENT_NAME, type = MoveIteratorFactoryConfig.class),
@XmlElement(name = MoveListFactoryConfig.XML_ELEMENT_NAME, type = MoveListFactoryConfig.class),
@XmlElement(name = PillarChangeMoveSelectorConfig.XML_ELEMENT_NAME,
type = PillarChangeMoveSelectorConfig.class),
@XmlElement(name = PillarSwapMoveSelectorConfig.XML_ELEMENT_NAME, type = PillarSwapMoveSelectorConfig.class),
@XmlElement(name = SubChainChangeMoveSelectorConfig.XML_ELEMENT_NAME,
type = SubChainChangeMoveSelectorConfig.class),
@XmlElement(name = SubChainSwapMoveSelectorConfig.XML_ELEMENT_NAME,
type = SubChainSwapMoveSelectorConfig.class),
@XmlElement(name = SubListChangeMoveSelectorConfig.XML_ELEMENT_NAME, type = SubListChangeMoveSelectorConfig.class),
@XmlElement(name = SubListSwapMoveSelectorConfig.XML_ELEMENT_NAME, type = SubListSwapMoveSelectorConfig.class),
@XmlElement(name = SwapMoveSelectorConfig.XML_ELEMENT_NAME, type = SwapMoveSelectorConfig.class),
@XmlElement(name = TailChainSwapMoveSelectorConfig.XML_ELEMENT_NAME,
type = TailChainSwapMoveSelectorConfig.class),
@XmlElement(name = UnionMoveSelectorConfig.XML_ELEMENT_NAME, type = UnionMoveSelectorConfig.class)
})
private MoveSelectorConfig moveSelectorConfig = null;
@XmlElement(name = "acceptor")
private LocalSearchAcceptorConfig acceptorConfig = null;
@XmlElement(name = "forager")
private LocalSearchForagerConfig foragerConfig = null;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public LocalSearchType getLocalSearchType() {
return localSearchType;
}
public void setLocalSearchType(LocalSearchType localSearchType) {
this.localSearchType = localSearchType;
}
public MoveSelectorConfig getMoveSelectorConfig() {
return moveSelectorConfig;
}
public void setMoveSelectorConfig(MoveSelectorConfig moveSelectorConfig) {
this.moveSelectorConfig = moveSelectorConfig;
}
public LocalSearchAcceptorConfig getAcceptorConfig() {
return acceptorConfig;
}
public void setAcceptorConfig(LocalSearchAcceptorConfig acceptorConfig) {
this.acceptorConfig = acceptorConfig;
}
public LocalSearchForagerConfig getForagerConfig() {
return foragerConfig;
}
public void setForagerConfig(LocalSearchForagerConfig foragerConfig) {
this.foragerConfig = foragerConfig;
}
// ************************************************************************
// With methods
// ************************************************************************
public LocalSearchPhaseConfig withLocalSearchType(LocalSearchType localSearchType) {
this.localSearchType = localSearchType;
return this;
}
public LocalSearchPhaseConfig withMoveSelectorConfig(MoveSelectorConfig moveSelectorConfig) {
this.moveSelectorConfig = moveSelectorConfig;
return this;
}
public LocalSearchPhaseConfig withAcceptorConfig(LocalSearchAcceptorConfig acceptorConfig) {
this.acceptorConfig = acceptorConfig;
return this;
}
public LocalSearchPhaseConfig withForagerConfig(LocalSearchForagerConfig foragerConfig) {
this.foragerConfig = foragerConfig;
return this;
}
@Override
public LocalSearchPhaseConfig inherit(LocalSearchPhaseConfig inheritedConfig) {
super.inherit(inheritedConfig);
localSearchType = ConfigUtils.inheritOverwritableProperty(localSearchType,
inheritedConfig.getLocalSearchType());
setMoveSelectorConfig(ConfigUtils.inheritOverwritableProperty(
getMoveSelectorConfig(), inheritedConfig.getMoveSelectorConfig()));
acceptorConfig = ConfigUtils.inheritConfig(acceptorConfig, inheritedConfig.getAcceptorConfig());
foragerConfig = ConfigUtils.inheritConfig(foragerConfig, inheritedConfig.getForagerConfig());
return this;
}
@Override
public LocalSearchPhaseConfig copyConfig() {
return new LocalSearchPhaseConfig().inherit(this);
}
@Override
public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {
if (getTerminationConfig() != null) {
getTerminationConfig().visitReferencedClasses(classVisitor);
}
if (moveSelectorConfig != null) {
moveSelectorConfig.visitReferencedClasses(classVisitor);
}
if (acceptorConfig != null) {
acceptorConfig.visitReferencedClasses(classVisitor);
}
if (foragerConfig != null) {
foragerConfig.visitReferencedClasses(classVisitor);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/localsearch/LocalSearchType.java | package ai.timefold.solver.core.config.localsearch;
import java.util.Arrays;
import jakarta.xml.bind.annotation.XmlEnum;
@XmlEnum
public enum LocalSearchType {
HILL_CLIMBING,
TABU_SEARCH,
SIMULATED_ANNEALING,
LATE_ACCEPTANCE,
GREAT_DELUGE,
VARIABLE_NEIGHBORHOOD_DESCENT;
/**
* @return {@link #values()} without duplicates (abstract types that end up behaving as one of the other types).
*/
public static LocalSearchType[] getBluePrintTypes() {
return Arrays.stream(values())
// Workaround for https://issues.redhat.com/browse/PLANNER-1294
.filter(localSearchType -> localSearchType != SIMULATED_ANNEALING)
.toArray(LocalSearchType[]::new);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/localsearch/decider | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/localsearch/decider/acceptor/AcceptorType.java | package ai.timefold.solver.core.config.localsearch.decider.acceptor;
import jakarta.xml.bind.annotation.XmlEnum;
@XmlEnum
public enum AcceptorType {
HILL_CLIMBING,
ENTITY_TABU,
VALUE_TABU,
MOVE_TABU,
UNDO_MOVE_TABU,
SIMULATED_ANNEALING,
LATE_ACCEPTANCE,
GREAT_DELUGE,
STEP_COUNTING_HILL_CLIMBING
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/localsearch/decider | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/localsearch/decider/acceptor/LocalSearchAcceptorConfig.java | package ai.timefold.solver.core.config.localsearch.decider.acceptor;
import java.util.List;
import java.util.function.Consumer;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
import ai.timefold.solver.core.config.AbstractConfig;
import ai.timefold.solver.core.config.localsearch.decider.acceptor.stepcountinghillclimbing.StepCountingHillClimbingType;
import ai.timefold.solver.core.config.util.ConfigUtils;
@XmlType(propOrder = {
"acceptorTypeList",
"entityTabuSize",
"entityTabuRatio",
"fadingEntityTabuSize",
"fadingEntityTabuRatio",
"valueTabuSize",
"valueTabuRatio",
"fadingValueTabuSize",
"fadingValueTabuRatio",
"moveTabuSize",
"fadingMoveTabuSize",
"undoMoveTabuSize",
"fadingUndoMoveTabuSize",
"simulatedAnnealingStartingTemperature",
"lateAcceptanceSize",
"greatDelugeWaterLevelIncrementScore",
"greatDelugeWaterLevelIncrementRatio",
"stepCountingHillClimbingSize",
"stepCountingHillClimbingType"
})
public class LocalSearchAcceptorConfig extends AbstractConfig<LocalSearchAcceptorConfig> {
@XmlElement(name = "acceptorType")
private List<AcceptorType> acceptorTypeList = null;
protected Integer entityTabuSize = null;
protected Double entityTabuRatio = null;
protected Integer fadingEntityTabuSize = null;
protected Double fadingEntityTabuRatio = null;
protected Integer valueTabuSize = null;
protected Double valueTabuRatio = null;
protected Integer fadingValueTabuSize = null;
protected Double fadingValueTabuRatio = null;
protected Integer moveTabuSize = null;
protected Integer fadingMoveTabuSize = null;
protected Integer undoMoveTabuSize = null;
protected Integer fadingUndoMoveTabuSize = null;
protected String simulatedAnnealingStartingTemperature = null;
protected Integer lateAcceptanceSize = null;
protected String greatDelugeWaterLevelIncrementScore = null;
protected Double greatDelugeWaterLevelIncrementRatio = null;
protected Integer stepCountingHillClimbingSize = null;
protected StepCountingHillClimbingType stepCountingHillClimbingType = null;
public List<AcceptorType> getAcceptorTypeList() {
return acceptorTypeList;
}
public void setAcceptorTypeList(List<AcceptorType> acceptorTypeList) {
this.acceptorTypeList = acceptorTypeList;
}
public Integer getEntityTabuSize() {
return entityTabuSize;
}
public void setEntityTabuSize(Integer entityTabuSize) {
this.entityTabuSize = entityTabuSize;
}
public Double getEntityTabuRatio() {
return entityTabuRatio;
}
public void setEntityTabuRatio(Double entityTabuRatio) {
this.entityTabuRatio = entityTabuRatio;
}
public Integer getFadingEntityTabuSize() {
return fadingEntityTabuSize;
}
public void setFadingEntityTabuSize(Integer fadingEntityTabuSize) {
this.fadingEntityTabuSize = fadingEntityTabuSize;
}
public Double getFadingEntityTabuRatio() {
return fadingEntityTabuRatio;
}
public void setFadingEntityTabuRatio(Double fadingEntityTabuRatio) {
this.fadingEntityTabuRatio = fadingEntityTabuRatio;
}
public Integer getValueTabuSize() {
return valueTabuSize;
}
public void setValueTabuSize(Integer valueTabuSize) {
this.valueTabuSize = valueTabuSize;
}
/**
* @deprecated Deprecated on account of never having worked in the first place.
*/
@Deprecated(forRemoval = true, since = "1.5.0")
public Double getValueTabuRatio() {
return valueTabuRatio;
}
/**
* @deprecated Deprecated on account of never having worked in the first place.
*/
@Deprecated(forRemoval = true, since = "1.5.0")
public void setValueTabuRatio(Double valueTabuRatio) {
this.valueTabuRatio = valueTabuRatio;
}
public Integer getFadingValueTabuSize() {
return fadingValueTabuSize;
}
public void setFadingValueTabuSize(Integer fadingValueTabuSize) {
this.fadingValueTabuSize = fadingValueTabuSize;
}
/**
* @deprecated Deprecated on account of never having worked in the first place.
*/
@Deprecated(forRemoval = true, since = "1.5.0")
public Double getFadingValueTabuRatio() {
return fadingValueTabuRatio;
}
/**
* @deprecated Deprecated on account of never having worked in the first place.
*/
@Deprecated(forRemoval = true, since = "1.5.0")
public void setFadingValueTabuRatio(Double fadingValueTabuRatio) {
this.fadingValueTabuRatio = fadingValueTabuRatio;
}
public Integer getMoveTabuSize() {
return moveTabuSize;
}
public void setMoveTabuSize(Integer moveTabuSize) {
this.moveTabuSize = moveTabuSize;
}
public Integer getFadingMoveTabuSize() {
return fadingMoveTabuSize;
}
public void setFadingMoveTabuSize(Integer fadingMoveTabuSize) {
this.fadingMoveTabuSize = fadingMoveTabuSize;
}
public Integer getUndoMoveTabuSize() {
return undoMoveTabuSize;
}
public void setUndoMoveTabuSize(Integer undoMoveTabuSize) {
this.undoMoveTabuSize = undoMoveTabuSize;
}
public Integer getFadingUndoMoveTabuSize() {
return fadingUndoMoveTabuSize;
}
public void setFadingUndoMoveTabuSize(Integer fadingUndoMoveTabuSize) {
this.fadingUndoMoveTabuSize = fadingUndoMoveTabuSize;
}
public String getSimulatedAnnealingStartingTemperature() {
return simulatedAnnealingStartingTemperature;
}
public void setSimulatedAnnealingStartingTemperature(String simulatedAnnealingStartingTemperature) {
this.simulatedAnnealingStartingTemperature = simulatedAnnealingStartingTemperature;
}
public Integer getLateAcceptanceSize() {
return lateAcceptanceSize;
}
public void setLateAcceptanceSize(Integer lateAcceptanceSize) {
this.lateAcceptanceSize = lateAcceptanceSize;
}
public String getGreatDelugeWaterLevelIncrementScore() {
return greatDelugeWaterLevelIncrementScore;
}
public void setGreatDelugeWaterLevelIncrementScore(String greatDelugeWaterLevelIncrementScore) {
this.greatDelugeWaterLevelIncrementScore = greatDelugeWaterLevelIncrementScore;
}
public Double getGreatDelugeWaterLevelIncrementRatio() {
return greatDelugeWaterLevelIncrementRatio;
}
public void setGreatDelugeWaterLevelIncrementRatio(Double greatDelugeWaterLevelIncrementRatio) {
this.greatDelugeWaterLevelIncrementRatio = greatDelugeWaterLevelIncrementRatio;
}
public Integer getStepCountingHillClimbingSize() {
return stepCountingHillClimbingSize;
}
public void setStepCountingHillClimbingSize(Integer stepCountingHillClimbingSize) {
this.stepCountingHillClimbingSize = stepCountingHillClimbingSize;
}
public StepCountingHillClimbingType getStepCountingHillClimbingType() {
return stepCountingHillClimbingType;
}
public void setStepCountingHillClimbingType(StepCountingHillClimbingType stepCountingHillClimbingType) {
this.stepCountingHillClimbingType = stepCountingHillClimbingType;
}
// ************************************************************************
// With methods
// ************************************************************************
public LocalSearchAcceptorConfig withAcceptorTypeList(List<AcceptorType> acceptorTypeList) {
this.acceptorTypeList = acceptorTypeList;
return this;
}
public LocalSearchAcceptorConfig withEntityTabuSize(Integer entityTabuSize) {
this.entityTabuSize = entityTabuSize;
return this;
}
public LocalSearchAcceptorConfig withEntityTabuRatio(Double entityTabuRatio) {
this.entityTabuRatio = entityTabuRatio;
return this;
}
public LocalSearchAcceptorConfig withFadingEntityTabuSize(Integer fadingEntityTabuSize) {
this.fadingEntityTabuSize = fadingEntityTabuSize;
return this;
}
public LocalSearchAcceptorConfig withFadingEntityTabuRatio(Double fadingEntityTabuRatio) {
this.fadingEntityTabuRatio = fadingEntityTabuRatio;
return this;
}
public LocalSearchAcceptorConfig withValueTabuSize(Integer valueTabuSize) {
this.valueTabuSize = valueTabuSize;
return this;
}
public LocalSearchAcceptorConfig withValueTabuRatio(Double valueTabuRatio) {
this.valueTabuRatio = valueTabuRatio;
return this;
}
public LocalSearchAcceptorConfig withFadingValueTabuSize(Integer fadingValueTabuSize) {
this.fadingValueTabuSize = fadingValueTabuSize;
return this;
}
public LocalSearchAcceptorConfig withFadingValueTabuRatio(Double fadingValueTabuRatio) {
this.fadingValueTabuRatio = fadingValueTabuRatio;
return this;
}
public LocalSearchAcceptorConfig withMoveTabuSize(Integer moveTabuSize) {
this.moveTabuSize = moveTabuSize;
return this;
}
public LocalSearchAcceptorConfig withFadingMoveTabuSize(Integer fadingMoveTabuSize) {
this.fadingMoveTabuSize = fadingMoveTabuSize;
return this;
}
public LocalSearchAcceptorConfig withUndoMoveTabuSize(Integer undoMoveTabuSize) {
this.undoMoveTabuSize = undoMoveTabuSize;
return this;
}
public LocalSearchAcceptorConfig withFadingUndoMoveTabuSize(Integer fadingUndoMoveTabuSize) {
this.fadingUndoMoveTabuSize = fadingUndoMoveTabuSize;
return this;
}
public LocalSearchAcceptorConfig withSimulatedAnnealingStartingTemperature(String simulatedAnnealingStartingTemperature) {
this.simulatedAnnealingStartingTemperature = simulatedAnnealingStartingTemperature;
return this;
}
public LocalSearchAcceptorConfig withLateAcceptanceSize(Integer lateAcceptanceSize) {
this.lateAcceptanceSize = lateAcceptanceSize;
return this;
}
public LocalSearchAcceptorConfig withStepCountingHillClimbingSize(Integer stepCountingHillClimbingSize) {
this.stepCountingHillClimbingSize = stepCountingHillClimbingSize;
return this;
}
public LocalSearchAcceptorConfig
withStepCountingHillClimbingType(StepCountingHillClimbingType stepCountingHillClimbingType) {
this.stepCountingHillClimbingType = stepCountingHillClimbingType;
return this;
}
@Override
public LocalSearchAcceptorConfig inherit(LocalSearchAcceptorConfig inheritedConfig) {
if (acceptorTypeList == null) {
acceptorTypeList = inheritedConfig.getAcceptorTypeList();
} else {
List<AcceptorType> inheritedAcceptorTypeList = inheritedConfig.getAcceptorTypeList();
if (inheritedAcceptorTypeList != null) {
for (AcceptorType acceptorType : inheritedAcceptorTypeList) {
if (!acceptorTypeList.contains(acceptorType)) {
acceptorTypeList.add(acceptorType);
}
}
}
}
entityTabuSize = ConfigUtils.inheritOverwritableProperty(entityTabuSize, inheritedConfig.getEntityTabuSize());
entityTabuRatio = ConfigUtils.inheritOverwritableProperty(entityTabuRatio, inheritedConfig.getEntityTabuRatio());
fadingEntityTabuSize = ConfigUtils.inheritOverwritableProperty(fadingEntityTabuSize,
inheritedConfig.getFadingEntityTabuSize());
fadingEntityTabuRatio = ConfigUtils.inheritOverwritableProperty(fadingEntityTabuRatio,
inheritedConfig.getFadingEntityTabuRatio());
valueTabuSize = ConfigUtils.inheritOverwritableProperty(valueTabuSize, inheritedConfig.getValueTabuSize());
valueTabuRatio = ConfigUtils.inheritOverwritableProperty(valueTabuRatio, inheritedConfig.getValueTabuRatio());
fadingValueTabuSize = ConfigUtils.inheritOverwritableProperty(fadingValueTabuSize,
inheritedConfig.getFadingValueTabuSize());
fadingValueTabuRatio = ConfigUtils.inheritOverwritableProperty(fadingValueTabuRatio,
inheritedConfig.getFadingValueTabuRatio());
moveTabuSize = ConfigUtils.inheritOverwritableProperty(moveTabuSize, inheritedConfig.getMoveTabuSize());
fadingMoveTabuSize = ConfigUtils.inheritOverwritableProperty(fadingMoveTabuSize,
inheritedConfig.getFadingMoveTabuSize());
undoMoveTabuSize = ConfigUtils.inheritOverwritableProperty(undoMoveTabuSize,
inheritedConfig.getUndoMoveTabuSize());
fadingUndoMoveTabuSize = ConfigUtils.inheritOverwritableProperty(fadingUndoMoveTabuSize,
inheritedConfig.getFadingUndoMoveTabuSize());
simulatedAnnealingStartingTemperature = ConfigUtils.inheritOverwritableProperty(
simulatedAnnealingStartingTemperature, inheritedConfig.getSimulatedAnnealingStartingTemperature());
lateAcceptanceSize = ConfigUtils.inheritOverwritableProperty(lateAcceptanceSize,
inheritedConfig.getLateAcceptanceSize());
greatDelugeWaterLevelIncrementScore = ConfigUtils.inheritOverwritableProperty(greatDelugeWaterLevelIncrementScore,
inheritedConfig.getGreatDelugeWaterLevelIncrementScore());
greatDelugeWaterLevelIncrementRatio = ConfigUtils.inheritOverwritableProperty(greatDelugeWaterLevelIncrementRatio,
inheritedConfig.getGreatDelugeWaterLevelIncrementRatio());
stepCountingHillClimbingSize = ConfigUtils.inheritOverwritableProperty(stepCountingHillClimbingSize,
inheritedConfig.getStepCountingHillClimbingSize());
stepCountingHillClimbingType = ConfigUtils.inheritOverwritableProperty(stepCountingHillClimbingType,
inheritedConfig.getStepCountingHillClimbingType());
return this;
}
@Override
public LocalSearchAcceptorConfig copyConfig() {
return new LocalSearchAcceptorConfig().inherit(this);
}
@Override
public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {
// No referenced classes
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/localsearch/decider | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/localsearch/decider/forager/FinalistPodiumType.java | package ai.timefold.solver.core.config.localsearch.decider.forager;
import jakarta.xml.bind.annotation.XmlEnum;
import ai.timefold.solver.core.impl.localsearch.decider.forager.finalist.FinalistPodium;
import ai.timefold.solver.core.impl.localsearch.decider.forager.finalist.HighestScoreFinalistPodium;
import ai.timefold.solver.core.impl.localsearch.decider.forager.finalist.StrategicOscillationByLevelFinalistPodium;
@XmlEnum
public enum FinalistPodiumType {
HIGHEST_SCORE,
STRATEGIC_OSCILLATION,
STRATEGIC_OSCILLATION_BY_LEVEL,
STRATEGIC_OSCILLATION_BY_LEVEL_ON_BEST_SCORE;
public <Solution_> FinalistPodium<Solution_> buildFinalistPodium() {
switch (this) {
case HIGHEST_SCORE:
return new HighestScoreFinalistPodium<>();
case STRATEGIC_OSCILLATION:
case STRATEGIC_OSCILLATION_BY_LEVEL:
return new StrategicOscillationByLevelFinalistPodium<>(false);
case STRATEGIC_OSCILLATION_BY_LEVEL_ON_BEST_SCORE:
return new StrategicOscillationByLevelFinalistPodium<>(true);
default:
throw new IllegalStateException("The finalistPodiumType (" + this + ") is not implemented.");
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/localsearch/decider | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/localsearch/decider/forager/LocalSearchForagerConfig.java | package ai.timefold.solver.core.config.localsearch.decider.forager;
import java.util.function.Consumer;
import jakarta.xml.bind.annotation.XmlType;
import ai.timefold.solver.core.config.AbstractConfig;
import ai.timefold.solver.core.config.util.ConfigUtils;
@XmlType(propOrder = {
"pickEarlyType",
"acceptedCountLimit",
"finalistPodiumType",
"breakTieRandomly"
})
public class LocalSearchForagerConfig extends AbstractConfig<LocalSearchForagerConfig> {
protected LocalSearchPickEarlyType pickEarlyType = null;
protected Integer acceptedCountLimit = null;
protected FinalistPodiumType finalistPodiumType = null;
protected Boolean breakTieRandomly = null;
public LocalSearchPickEarlyType getPickEarlyType() {
return pickEarlyType;
}
public void setPickEarlyType(LocalSearchPickEarlyType pickEarlyType) {
this.pickEarlyType = pickEarlyType;
}
public Integer getAcceptedCountLimit() {
return acceptedCountLimit;
}
public void setAcceptedCountLimit(Integer acceptedCountLimit) {
this.acceptedCountLimit = acceptedCountLimit;
}
public FinalistPodiumType getFinalistPodiumType() {
return finalistPodiumType;
}
public void setFinalistPodiumType(FinalistPodiumType finalistPodiumType) {
this.finalistPodiumType = finalistPodiumType;
}
public Boolean getBreakTieRandomly() {
return breakTieRandomly;
}
public void setBreakTieRandomly(Boolean breakTieRandomly) {
this.breakTieRandomly = breakTieRandomly;
}
// ************************************************************************
// With methods
// ************************************************************************
public LocalSearchForagerConfig withPickEarlyType(LocalSearchPickEarlyType pickEarlyType) {
this.pickEarlyType = pickEarlyType;
return this;
}
public LocalSearchForagerConfig withAcceptedCountLimit(int acceptedCountLimit) {
this.acceptedCountLimit = acceptedCountLimit;
return this;
}
public LocalSearchForagerConfig withFinalistPodiumType(FinalistPodiumType finalistPodiumType) {
this.finalistPodiumType = finalistPodiumType;
return this;
}
public LocalSearchForagerConfig withBreakTieRandomly(boolean breakTieRandomly) {
this.breakTieRandomly = breakTieRandomly;
return this;
}
@Override
public LocalSearchForagerConfig inherit(LocalSearchForagerConfig inheritedConfig) {
pickEarlyType = ConfigUtils.inheritOverwritableProperty(pickEarlyType,
inheritedConfig.getPickEarlyType());
acceptedCountLimit = ConfigUtils.inheritOverwritableProperty(acceptedCountLimit,
inheritedConfig.getAcceptedCountLimit());
finalistPodiumType = ConfigUtils.inheritOverwritableProperty(finalistPodiumType,
inheritedConfig.getFinalistPodiumType());
breakTieRandomly = ConfigUtils.inheritOverwritableProperty(breakTieRandomly,
inheritedConfig.getBreakTieRandomly());
return this;
}
@Override
public LocalSearchForagerConfig copyConfig() {
return new LocalSearchForagerConfig().inherit(this);
}
@Override
public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {
// No referenced classes
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/partitionedsearch/PartitionedSearchPhaseConfig.java | package ai.timefold.solver.core.config.partitionedsearch;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlElements;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.api.solver.Solver;
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.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.util.ConfigUtils;
import ai.timefold.solver.core.impl.io.jaxb.adapter.JaxbCustomPropertiesAdapter;
import ai.timefold.solver.core.impl.partitionedsearch.partitioner.SolutionPartitioner;
@XmlType(propOrder = {
"solutionPartitionerClass",
"solutionPartitionerCustomProperties",
"runnablePartThreadLimit",
"phaseConfigList"
})
public class PartitionedSearchPhaseConfig extends PhaseConfig<PartitionedSearchPhaseConfig> {
public static final String XML_ELEMENT_NAME = "partitionedSearch";
public static final String ACTIVE_THREAD_COUNT_AUTO = "AUTO";
public static final String ACTIVE_THREAD_COUNT_UNLIMITED = "UNLIMITED";
// Warning: all fields are null (and not defaulted) because they can be inherited
// and also because the input config file should match the output config file
protected Class<? extends SolutionPartitioner<?>> solutionPartitionerClass = null;
@XmlJavaTypeAdapter(JaxbCustomPropertiesAdapter.class)
protected Map<String, String> solutionPartitionerCustomProperties = null;
protected String runnablePartThreadLimit = null;
@XmlElements({
@XmlElement(name = ConstructionHeuristicPhaseConfig.XML_ELEMENT_NAME,
type = ConstructionHeuristicPhaseConfig.class),
@XmlElement(name = CustomPhaseConfig.XML_ELEMENT_NAME, type = CustomPhaseConfig.class),
@XmlElement(name = ExhaustiveSearchPhaseConfig.XML_ELEMENT_NAME, type = ExhaustiveSearchPhaseConfig.class),
@XmlElement(name = LocalSearchPhaseConfig.XML_ELEMENT_NAME, type = LocalSearchPhaseConfig.class),
@XmlElement(name = NoChangePhaseConfig.XML_ELEMENT_NAME, type = NoChangePhaseConfig.class),
@XmlElement(name = PartitionedSearchPhaseConfig.XML_ELEMENT_NAME, type = PartitionedSearchPhaseConfig.class)
})
protected List<PhaseConfig> phaseConfigList = null;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public Class<? extends SolutionPartitioner<?>> getSolutionPartitionerClass() {
return solutionPartitionerClass;
}
public void setSolutionPartitionerClass(Class<? extends SolutionPartitioner<?>> solutionPartitionerClass) {
this.solutionPartitionerClass = solutionPartitionerClass;
}
public Map<String, String> getSolutionPartitionerCustomProperties() {
return solutionPartitionerCustomProperties;
}
public void setSolutionPartitionerCustomProperties(Map<String, String> solutionPartitionerCustomProperties) {
this.solutionPartitionerCustomProperties = solutionPartitionerCustomProperties;
}
/**
* Similar to a thread pool size, but instead of limiting the number of {@link Thread}s,
* it limits the number of {@link java.lang.Thread.State#RUNNABLE runnable} {@link Thread}s to avoid consuming all
* CPU resources (which would starve UI, Servlets and REST threads).
*
* <p>
* The number of {@link Thread}s is always equal to the number of partitions returned by
* {@link SolutionPartitioner#splitWorkingSolution(ScoreDirector, Integer)},
* because otherwise some partitions would never run (especially with {@link Solver#terminateEarly() asynchronous
* termination}).
* If this limit (or {@link Runtime#availableProcessors()}) is lower than the number of partitions,
* this results in a slower score calculation speed per partition {@link Solver}.
*
* <p>
* Defaults to {@value #ACTIVE_THREAD_COUNT_AUTO} which consumes the majority
* but not all of the CPU cores on multi-core machines, to prevent a livelock that hangs other processes
* (such as your IDE, REST servlets threads or SSH connections) on the machine.
*
* <p>
* Use {@value #ACTIVE_THREAD_COUNT_UNLIMITED} to give it all CPU cores.
* This is useful if you're handling the CPU consumption on an OS level.
*
* @return null, a number, {@value #ACTIVE_THREAD_COUNT_AUTO} or {@value #ACTIVE_THREAD_COUNT_UNLIMITED}.
*/
public String getRunnablePartThreadLimit() {
return runnablePartThreadLimit;
}
public void setRunnablePartThreadLimit(String runnablePartThreadLimit) {
this.runnablePartThreadLimit = runnablePartThreadLimit;
}
public List<PhaseConfig> getPhaseConfigList() {
return phaseConfigList;
}
public void setPhaseConfigList(List<PhaseConfig> phaseConfigList) {
this.phaseConfigList = phaseConfigList;
}
// ************************************************************************
// With methods
// ************************************************************************
public PartitionedSearchPhaseConfig withSolutionPartitionerClass(
Class<? extends SolutionPartitioner<?>> solutionPartitionerClass) {
this.setSolutionPartitionerClass(solutionPartitionerClass);
return this;
}
public PartitionedSearchPhaseConfig withSolutionPartitionerCustomProperties(
Map<String, String> solutionPartitionerCustomProperties) {
this.setSolutionPartitionerCustomProperties(solutionPartitionerCustomProperties);
return this;
}
public PartitionedSearchPhaseConfig withRunnablePartThreadLimit(String runnablePartThreadLimit) {
this.setRunnablePartThreadLimit(runnablePartThreadLimit);
return this;
}
public PartitionedSearchPhaseConfig withPhaseConfigList(List<PhaseConfig> phaseConfigList) {
this.setPhaseConfigList(phaseConfigList);
return this;
}
public PartitionedSearchPhaseConfig withPhaseConfigs(PhaseConfig... phaseConfigs) {
this.setPhaseConfigList(List.of(phaseConfigs));
return this;
}
@Override
public PartitionedSearchPhaseConfig inherit(PartitionedSearchPhaseConfig inheritedConfig) {
super.inherit(inheritedConfig);
solutionPartitionerClass = ConfigUtils.inheritOverwritableProperty(solutionPartitionerClass,
inheritedConfig.getSolutionPartitionerClass());
solutionPartitionerCustomProperties = ConfigUtils.inheritMergeableMapProperty(
solutionPartitionerCustomProperties, inheritedConfig.getSolutionPartitionerCustomProperties());
runnablePartThreadLimit = ConfigUtils.inheritOverwritableProperty(runnablePartThreadLimit,
inheritedConfig.getRunnablePartThreadLimit());
phaseConfigList = ConfigUtils.inheritMergeableListConfig(
phaseConfigList, inheritedConfig.getPhaseConfigList());
return this;
}
@Override
public PartitionedSearchPhaseConfig copyConfig() {
return new PartitionedSearchPhaseConfig().inherit(this);
}
@Override
public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {
if (getTerminationConfig() != null) {
getTerminationConfig().visitReferencedClasses(classVisitor);
}
classVisitor.accept(solutionPartitionerClass);
if (phaseConfigList != null) {
phaseConfigList.forEach(pc -> pc.visitReferencedClasses(classVisitor));
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/phase/NoChangePhaseConfig.java | package ai.timefold.solver.core.config.phase;
import java.util.function.Consumer;
public class NoChangePhaseConfig extends PhaseConfig<NoChangePhaseConfig> {
public static final String XML_ELEMENT_NAME = "noChangePhase";
@Override
public NoChangePhaseConfig inherit(NoChangePhaseConfig inheritedConfig) {
super.inherit(inheritedConfig);
return this;
}
@Override
public NoChangePhaseConfig copyConfig() {
return new NoChangePhaseConfig().inherit(this);
}
@Override
public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {
if (getTerminationConfig() != null) {
getTerminationConfig().visitReferencedClasses(classVisitor);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/phase/PhaseConfig.java | package ai.timefold.solver.core.config.phase;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlSeeAlso;
import jakarta.xml.bind.annotation.XmlType;
import ai.timefold.solver.core.config.AbstractConfig;
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.custom.CustomPhaseConfig;
import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
import ai.timefold.solver.core.config.util.ConfigUtils;
@XmlSeeAlso({
ConstructionHeuristicPhaseConfig.class,
CustomPhaseConfig.class,
ExhaustiveSearchPhaseConfig.class,
LocalSearchPhaseConfig.class,
NoChangePhaseConfig.class,
PartitionedSearchPhaseConfig.class
})
@XmlType(propOrder = {
"terminationConfig"
})
public abstract class PhaseConfig<Config_ extends PhaseConfig<Config_>> extends AbstractConfig<Config_> {
// Warning: all fields are null (and not defaulted) because they can be inherited
// and also because the input config file should match the output config file
@XmlElement(name = "termination")
private TerminationConfig terminationConfig = null;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public TerminationConfig getTerminationConfig() {
return terminationConfig;
}
public void setTerminationConfig(TerminationConfig terminationConfig) {
this.terminationConfig = terminationConfig;
}
// ************************************************************************
// With methods
// ************************************************************************
public Config_ withTerminationConfig(TerminationConfig terminationConfig) {
this.setTerminationConfig(terminationConfig);
return (Config_) this;
}
@Override
public Config_ inherit(Config_ inheritedConfig) {
terminationConfig = ConfigUtils.inheritConfig(terminationConfig, inheritedConfig.getTerminationConfig());
return (Config_) this;
}
@Override
public String toString() {
return getClass().getSimpleName();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/phase | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/phase/custom/CustomPhaseConfig.java | package ai.timefold.solver.core.config.phase.custom;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlTransient;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import ai.timefold.solver.core.config.phase.PhaseConfig;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.io.jaxb.adapter.JaxbCustomPropertiesAdapter;
import ai.timefold.solver.core.impl.phase.custom.CustomPhaseCommand;
@XmlType(propOrder = {
"customPhaseCommandClassList",
"customProperties",
})
public class CustomPhaseConfig extends PhaseConfig<CustomPhaseConfig> {
public static final String XML_ELEMENT_NAME = "customPhase";
// Warning: all fields are null (and not defaulted) because they can be inherited
// and also because the input config file should match the output config file
@XmlElement(name = "customPhaseCommandClass")
protected List<Class<? extends CustomPhaseCommand>> customPhaseCommandClassList = null;
@XmlJavaTypeAdapter(JaxbCustomPropertiesAdapter.class)
protected Map<String, String> customProperties = null;
@XmlTransient
protected List<CustomPhaseCommand> customPhaseCommandList = null;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public List<Class<? extends CustomPhaseCommand>> getCustomPhaseCommandClassList() {
return customPhaseCommandClassList;
}
public void setCustomPhaseCommandClassList(List<Class<? extends CustomPhaseCommand>> customPhaseCommandClassList) {
this.customPhaseCommandClassList = customPhaseCommandClassList;
}
public Map<String, String> getCustomProperties() {
return customProperties;
}
public void setCustomProperties(Map<String, String> customProperties) {
this.customProperties = customProperties;
}
public List<CustomPhaseCommand> getCustomPhaseCommandList() {
return customPhaseCommandList;
}
public void setCustomPhaseCommandList(List<CustomPhaseCommand> customPhaseCommandList) {
this.customPhaseCommandList = customPhaseCommandList;
}
// ************************************************************************
// With methods
// ************************************************************************
public CustomPhaseConfig withCustomPhaseCommandClassList(
List<Class<? extends CustomPhaseCommand>> customPhaseCommandClassList) {
this.customPhaseCommandClassList = customPhaseCommandClassList;
return this;
}
public CustomPhaseConfig withCustomProperties(Map<String, String> customProperties) {
this.customProperties = customProperties;
return this;
}
public CustomPhaseConfig withCustomPhaseCommandList(List<CustomPhaseCommand> customPhaseCommandList) {
boolean hasNullCommand = Objects.requireNonNullElse(customPhaseCommandList, Collections.emptyList())
.stream().anyMatch(Objects::isNull);
if (hasNullCommand) {
throw new IllegalArgumentException(
"Custom phase commands (" + customPhaseCommandList + ") must not contain a null element.");
}
this.customPhaseCommandList = customPhaseCommandList;
return this;
}
public <Solution_> CustomPhaseConfig withCustomPhaseCommands(CustomPhaseCommand<Solution_>... customPhaseCommands) {
boolean hasNullCommand = Arrays.stream(customPhaseCommands).anyMatch(Objects::isNull);
if (hasNullCommand) {
throw new IllegalArgumentException(
"Custom phase commands (" + Arrays.toString(customPhaseCommands) + ") must not contain a null element.");
}
this.customPhaseCommandList = Arrays.asList(customPhaseCommands);
return this;
}
@Override
public CustomPhaseConfig inherit(CustomPhaseConfig inheritedConfig) {
super.inherit(inheritedConfig);
customPhaseCommandClassList = ConfigUtils.inheritMergeableListProperty(
customPhaseCommandClassList, inheritedConfig.getCustomPhaseCommandClassList());
customPhaseCommandList = ConfigUtils.inheritMergeableListProperty(
customPhaseCommandList, inheritedConfig.getCustomPhaseCommandList());
customProperties = ConfigUtils.inheritMergeableMapProperty(
customProperties, inheritedConfig.getCustomProperties());
return this;
}
@Override
public CustomPhaseConfig copyConfig() {
return new CustomPhaseConfig().inherit(this);
}
@Override
public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {
if (getTerminationConfig() != null) {
getTerminationConfig().visitReferencedClasses(classVisitor);
}
if (customPhaseCommandClassList != null) {
customPhaseCommandClassList.forEach(classVisitor);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/score | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/score/director/ScoreDirectorFactoryConfig.java | package ai.timefold.solver.core.config.score.director;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import ai.timefold.solver.core.api.score.calculator.EasyScoreCalculator;
import ai.timefold.solver.core.api.score.calculator.IncrementalScoreCalculator;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.api.score.stream.ConstraintStreamImplType;
import ai.timefold.solver.core.config.AbstractConfig;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.io.jaxb.adapter.JaxbCustomPropertiesAdapter;
@XmlType(propOrder = {
"easyScoreCalculatorClass",
"easyScoreCalculatorCustomProperties",
"constraintProviderClass",
"constraintProviderCustomProperties",
"constraintStreamImplType",
"constraintStreamAutomaticNodeSharing",
"incrementalScoreCalculatorClass",
"incrementalScoreCalculatorCustomProperties",
"scoreDrlList",
"initializingScoreTrend",
"assertionScoreDirectorFactory"
})
public class ScoreDirectorFactoryConfig extends AbstractConfig<ScoreDirectorFactoryConfig> {
protected Class<? extends EasyScoreCalculator> easyScoreCalculatorClass = null;
@XmlJavaTypeAdapter(JaxbCustomPropertiesAdapter.class)
protected Map<String, String> easyScoreCalculatorCustomProperties = null;
protected Class<? extends ConstraintProvider> constraintProviderClass = null;
@XmlJavaTypeAdapter(JaxbCustomPropertiesAdapter.class)
protected Map<String, String> constraintProviderCustomProperties = null;
protected ConstraintStreamImplType constraintStreamImplType;
protected Boolean constraintStreamAutomaticNodeSharing;
protected Class<? extends IncrementalScoreCalculator> incrementalScoreCalculatorClass = null;
@XmlJavaTypeAdapter(JaxbCustomPropertiesAdapter.class)
protected Map<String, String> incrementalScoreCalculatorCustomProperties = null;
@Deprecated(forRemoval = true)
@XmlElement(name = "scoreDrl")
protected List<String> scoreDrlList = null;
// TODO: this should be rather an enum?
protected String initializingScoreTrend = null;
@XmlElement(name = "assertionScoreDirectorFactory")
protected ScoreDirectorFactoryConfig assertionScoreDirectorFactory = null;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public Class<? extends EasyScoreCalculator> getEasyScoreCalculatorClass() {
return easyScoreCalculatorClass;
}
public void setEasyScoreCalculatorClass(Class<? extends EasyScoreCalculator> easyScoreCalculatorClass) {
this.easyScoreCalculatorClass = easyScoreCalculatorClass;
}
public Map<String, String> getEasyScoreCalculatorCustomProperties() {
return easyScoreCalculatorCustomProperties;
}
public void setEasyScoreCalculatorCustomProperties(Map<String, String> easyScoreCalculatorCustomProperties) {
this.easyScoreCalculatorCustomProperties = easyScoreCalculatorCustomProperties;
}
public Class<? extends ConstraintProvider> getConstraintProviderClass() {
return constraintProviderClass;
}
public void setConstraintProviderClass(Class<? extends ConstraintProvider> constraintProviderClass) {
this.constraintProviderClass = constraintProviderClass;
}
public Map<String, String> getConstraintProviderCustomProperties() {
return constraintProviderCustomProperties;
}
public void setConstraintProviderCustomProperties(Map<String, String> constraintProviderCustomProperties) {
this.constraintProviderCustomProperties = constraintProviderCustomProperties;
}
public ConstraintStreamImplType getConstraintStreamImplType() {
return constraintStreamImplType;
}
public void setConstraintStreamImplType(ConstraintStreamImplType constraintStreamImplType) {
this.constraintStreamImplType = constraintStreamImplType;
}
public Boolean getConstraintStreamAutomaticNodeSharing() {
return constraintStreamAutomaticNodeSharing;
}
public void setConstraintStreamAutomaticNodeSharing(Boolean constraintStreamAutomaticNodeSharing) {
this.constraintStreamAutomaticNodeSharing = constraintStreamAutomaticNodeSharing;
}
public Class<? extends IncrementalScoreCalculator> getIncrementalScoreCalculatorClass() {
return incrementalScoreCalculatorClass;
}
public void
setIncrementalScoreCalculatorClass(Class<? extends IncrementalScoreCalculator> incrementalScoreCalculatorClass) {
this.incrementalScoreCalculatorClass = incrementalScoreCalculatorClass;
}
public Map<String, String> getIncrementalScoreCalculatorCustomProperties() {
return incrementalScoreCalculatorCustomProperties;
}
public void setIncrementalScoreCalculatorCustomProperties(Map<String, String> incrementalScoreCalculatorCustomProperties) {
this.incrementalScoreCalculatorCustomProperties = incrementalScoreCalculatorCustomProperties;
}
/**
* @deprecated Score DRL is deprecated and will be removed in a future major version of Timefold.
* See <a href="https://timefold.ai/docs/">DRL
* to Constraint Streams migration recipe</a>.
*/
@Deprecated(forRemoval = true)
public List<String> getScoreDrlList() {
return scoreDrlList;
}
/**
* @deprecated Score DRL is deprecated and will be removed in a future major version of Timefold.
* See <a href="https://timefold.ai/docs/">DRL
* to Constraint
* Streams migration recipe</a>.
*/
@Deprecated(forRemoval = true)
public void setScoreDrlList(List<String> scoreDrlList) {
this.scoreDrlList = scoreDrlList;
}
public String getInitializingScoreTrend() {
return initializingScoreTrend;
}
public void setInitializingScoreTrend(String initializingScoreTrend) {
this.initializingScoreTrend = initializingScoreTrend;
}
public ScoreDirectorFactoryConfig getAssertionScoreDirectorFactory() {
return assertionScoreDirectorFactory;
}
public void setAssertionScoreDirectorFactory(ScoreDirectorFactoryConfig assertionScoreDirectorFactory) {
this.assertionScoreDirectorFactory = assertionScoreDirectorFactory;
}
// ************************************************************************
// With methods
// ************************************************************************
public ScoreDirectorFactoryConfig
withEasyScoreCalculatorClass(Class<? extends EasyScoreCalculator> easyScoreCalculatorClass) {
this.easyScoreCalculatorClass = easyScoreCalculatorClass;
return this;
}
public ScoreDirectorFactoryConfig
withEasyScoreCalculatorCustomProperties(Map<String, String> easyScoreCalculatorCustomProperties) {
this.easyScoreCalculatorCustomProperties = easyScoreCalculatorCustomProperties;
return this;
}
public ScoreDirectorFactoryConfig withConstraintProviderClass(Class<? extends ConstraintProvider> constraintProviderClass) {
this.constraintProviderClass = constraintProviderClass;
return this;
}
public ScoreDirectorFactoryConfig
withConstraintProviderCustomProperties(Map<String, String> constraintProviderCustomProperties) {
this.constraintProviderCustomProperties = constraintProviderCustomProperties;
return this;
}
public ScoreDirectorFactoryConfig withConstraintStreamImplType(ConstraintStreamImplType constraintStreamImplType) {
this.constraintStreamImplType = constraintStreamImplType;
return this;
}
public ScoreDirectorFactoryConfig withConstraintStreamAutomaticNodeSharing(Boolean constraintStreamAutomaticNodeSharing) {
this.constraintStreamAutomaticNodeSharing = constraintStreamAutomaticNodeSharing;
return this;
}
public ScoreDirectorFactoryConfig
withIncrementalScoreCalculatorClass(Class<? extends IncrementalScoreCalculator> incrementalScoreCalculatorClass) {
this.incrementalScoreCalculatorClass = incrementalScoreCalculatorClass;
return this;
}
public ScoreDirectorFactoryConfig
withIncrementalScoreCalculatorCustomProperties(Map<String, String> incrementalScoreCalculatorCustomProperties) {
this.incrementalScoreCalculatorCustomProperties = incrementalScoreCalculatorCustomProperties;
return this;
}
/**
* @deprecated Score DRL is deprecated and will be removed in a future major version of Timefold.
* See <a href="https://timefold.ai/docs/">DRL
* to Constraint
* Streams migration recipe</a>.
*/
@Deprecated(forRemoval = true)
public ScoreDirectorFactoryConfig withScoreDrlList(List<String> scoreDrlList) {
this.scoreDrlList = scoreDrlList;
return this;
}
/**
* @deprecated Score DRL is deprecated and will be removed in a future major version of Timefold.
* See <a href="https://timefold.ai/docs/">DRL
* to Constraint
* Streams migration recipe</a>.
*/
@Deprecated(forRemoval = true)
public ScoreDirectorFactoryConfig withScoreDrls(String... scoreDrls) {
this.scoreDrlList = Arrays.asList(scoreDrls);
return this;
}
public ScoreDirectorFactoryConfig withInitializingScoreTrend(String initializingScoreTrend) {
this.initializingScoreTrend = initializingScoreTrend;
return this;
}
public ScoreDirectorFactoryConfig withAssertionScoreDirectorFactory(
ScoreDirectorFactoryConfig assertionScoreDirectorFactory) {
this.assertionScoreDirectorFactory = assertionScoreDirectorFactory;
return this;
}
@Override
public ScoreDirectorFactoryConfig inherit(ScoreDirectorFactoryConfig inheritedConfig) {
easyScoreCalculatorClass = ConfigUtils.inheritOverwritableProperty(
easyScoreCalculatorClass, inheritedConfig.getEasyScoreCalculatorClass());
easyScoreCalculatorCustomProperties = ConfigUtils.inheritMergeableMapProperty(
easyScoreCalculatorCustomProperties, inheritedConfig.getEasyScoreCalculatorCustomProperties());
constraintProviderClass = ConfigUtils.inheritOverwritableProperty(
constraintProviderClass, inheritedConfig.getConstraintProviderClass());
constraintProviderCustomProperties = ConfigUtils.inheritMergeableMapProperty(
constraintProviderCustomProperties, inheritedConfig.getConstraintProviderCustomProperties());
constraintStreamImplType = ConfigUtils.inheritOverwritableProperty(
constraintStreamImplType, inheritedConfig.getConstraintStreamImplType());
constraintStreamAutomaticNodeSharing = ConfigUtils.inheritOverwritableProperty(constraintStreamAutomaticNodeSharing,
inheritedConfig.getConstraintStreamAutomaticNodeSharing());
incrementalScoreCalculatorClass = ConfigUtils.inheritOverwritableProperty(
incrementalScoreCalculatorClass, inheritedConfig.getIncrementalScoreCalculatorClass());
incrementalScoreCalculatorCustomProperties = ConfigUtils.inheritMergeableMapProperty(
incrementalScoreCalculatorCustomProperties, inheritedConfig.getIncrementalScoreCalculatorCustomProperties());
scoreDrlList = ConfigUtils.inheritMergeableListProperty(
scoreDrlList, inheritedConfig.getScoreDrlList());
initializingScoreTrend = ConfigUtils.inheritOverwritableProperty(
initializingScoreTrend, inheritedConfig.getInitializingScoreTrend());
assertionScoreDirectorFactory = ConfigUtils.inheritOverwritableProperty(
assertionScoreDirectorFactory, inheritedConfig.getAssertionScoreDirectorFactory());
return this;
}
@Override
public ScoreDirectorFactoryConfig copyConfig() {
return new ScoreDirectorFactoryConfig().inherit(this);
}
@Override
public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {
classVisitor.accept(easyScoreCalculatorClass);
classVisitor.accept(constraintProviderClass);
classVisitor.accept(incrementalScoreCalculatorClass);
if (assertionScoreDirectorFactory != null) {
assertionScoreDirectorFactory.visitReferencedClasses(classVisitor);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/solver/EnvironmentMode.java | package ai.timefold.solver.core.config.solver;
import java.util.Random;
import jakarta.xml.bind.annotation.XmlEnum;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
/**
* The environment mode also allows you to detect common bugs in your implementation.
* <p>
* Also, a {@link Solver} has a single {@link Random} instance.
* Some optimization algorithms use the {@link Random} instance a lot more than others.
* For example simulated annealing depends highly on random numbers,
* while tabu search only depends on it to deal with score ties.
* This environment mode influences the seed of that {@link Random} instance.
*/
@XmlEnum
public enum EnvironmentMode {
/**
* This mode turns on {@link #FULL_ASSERT} and enables variable tracking to fail-fast on a bug in a {@link Move}
* implementation,
* a constraint, the engine itself or something else at the highest performance cost.
* <p>
* Because it tracks genuine and shadow variables, it is able to report precisely what variables caused the corruption and
* report any missed {@link ai.timefold.solver.core.api.domain.variable.VariableListener} events.
* <p>
* This mode is reproducible (see {@link #REPRODUCIBLE} mode).
* <p>
* This mode is intrusive because it calls the {@link InnerScoreDirector#calculateScore()} more frequently than a non assert
* mode.
* <p>
* This mode is by far the slowest of all the modes.
*/
TRACKED_FULL_ASSERT(true),
/**
* This mode turns on all assertions
* to fail-fast on a bug in a {@link Move} implementation, a constraint, the engine itself or something else
* at a horrible performance cost.
* <p>
* This mode is reproducible (see {@link #REPRODUCIBLE} mode).
* <p>
* This mode is intrusive because it calls the {@link InnerScoreDirector#calculateScore()} more frequently
* than a non assert mode.
* <p>
* This mode is horribly slow.
*/
FULL_ASSERT(true),
/**
* This mode turns on several assertions (but not all of them)
* to fail-fast on a bug in a {@link Move} implementation, a constraint, the engine itself or something else
* at an overwhelming performance cost.
* <p>
* This mode is reproducible (see {@link #REPRODUCIBLE} mode).
* <p>
* This mode is non-intrusive, unlike {@link #FULL_ASSERT} and {@link #FAST_ASSERT}.
* <p>
* This mode is horribly slow.
*/
NON_INTRUSIVE_FULL_ASSERT(true),
/**
* This mode turns on several assertions (but not all of them)
* to fail-fast on a bug in a {@link Move} implementation, a constraint rule, the engine itself or something else
* at a reasonable performance cost (in development at least).
* <p>
* This mode is reproducible (see {@link #REPRODUCIBLE} mode).
* <p>
* This mode is intrusive because it calls the {@link InnerScoreDirector#calculateScore()} more frequently
* than a non assert mode.
* <p>
* This mode is slow.
*/
FAST_ASSERT(true),
/**
* The reproducible mode is the default mode because it is recommended during development.
* In this mode, 2 runs on the same computer will execute the same code in the same order.
* They will also yield the same result, except if they use a time based termination
* and they have a sufficiently large difference in allocated CPU time.
* This allows you to benchmark new optimizations (such as a new {@link Move} implementation) fairly
* and reproduce bugs in your code reliably.
* <p>
* Warning: some code can disrupt reproducibility regardless of this mode. See the reference manual for more info.
* <p>
* In practice, this mode uses the default random seed,
* and it also disables certain concurrency optimizations (such as work stealing).
*/
REPRODUCIBLE(false),
/**
* The non reproducible mode is equally fast or slightly faster than {@link #REPRODUCIBLE}.
* <p>
* The random seed is different on every run, which makes it more robust against an unlucky random seed.
* An unlucky random seed gives a bad result on a certain data set with a certain solver configuration.
* Note that in most use cases the impact of the random seed is relatively low on the result.
* An occasional bad result is far more likely to be caused by another issue (such as a score trap).
* <p>
* In multithreaded scenarios, this mode allows the use of work stealing and other non deterministic speed tricks.
*/
NON_REPRODUCIBLE(false);
private final boolean asserted;
EnvironmentMode(boolean asserted) {
this.asserted = asserted;
}
public boolean isAsserted() {
return asserted;
}
public boolean isNonIntrusiveFullAsserted() {
if (!isAsserted()) {
return false;
}
return this != FAST_ASSERT;
}
public boolean isIntrusiveFastAsserted() {
if (!isAsserted()) {
return false;
}
return this != NON_INTRUSIVE_FULL_ASSERT;
}
public boolean isReproducible() {
return this != NON_REPRODUCIBLE;
}
public boolean isTracking() {
return this == TRACKED_FULL_ASSERT;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/solver/SolverConfig.java | package ai.timefold.solver.core.config.solver;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ThreadFactory;
import java.util.function.Consumer;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlElements;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlTransient;
import jakarta.xml.bind.annotation.XmlType;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner;
import ai.timefold.solver.core.api.score.calculator.EasyScoreCalculator;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.api.score.stream.ConstraintStreamImplType;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.api.solver.SolverFactory;
import ai.timefold.solver.core.config.AbstractConfig;
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.NoChangePhaseConfig;
import ai.timefold.solver.core.config.phase.PhaseConfig;
import ai.timefold.solver.core.config.phase.custom.CustomPhaseConfig;
import ai.timefold.solver.core.config.score.director.ScoreDirectorFactoryConfig;
import ai.timefold.solver.core.config.solver.monitoring.MonitoringConfig;
import ai.timefold.solver.core.config.solver.monitoring.SolverMetric;
import ai.timefold.solver.core.config.solver.random.RandomType;
import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.heuristic.selector.common.nearby.NearbyDistanceMeter;
import ai.timefold.solver.core.impl.io.jaxb.SolverConfigIO;
import ai.timefold.solver.core.impl.io.jaxb.TimefoldXmlSerializationException;
import ai.timefold.solver.core.impl.phase.PhaseFactory;
import ai.timefold.solver.core.impl.solver.random.RandomFactory;
/**
* To read it from XML, use {@link #createFromXmlResource(String)}.
* To build a {@link SolverFactory} with it, use {@link SolverFactory#create(SolverConfig)}.
*/
@XmlRootElement(name = SolverConfig.XML_ELEMENT_NAME)
@XmlType(name = SolverConfig.XML_TYPE_NAME, propOrder = {
"environmentMode",
"daemon",
"randomType",
"randomSeed",
"randomFactoryClass",
"moveThreadCount",
"moveThreadBufferSize",
"threadFactoryClass",
"monitoringConfig",
"solutionClass",
"entityClassList",
"domainAccessType",
"scoreDirectorFactoryConfig",
"terminationConfig",
"nearbyDistanceMeterClass",
"phaseConfigList",
})
public class SolverConfig extends AbstractConfig<SolverConfig> {
public static final String XML_ELEMENT_NAME = "solver";
public static final String XML_NAMESPACE = "https://timefold.ai/xsd/solver";
public static final String XML_TYPE_NAME = "solverConfig";
/**
* Reads an XML solver configuration from the classpath.
*
* @param solverConfigResource never null, a classpath resource
* as defined by {@link ClassLoader#getResource(String)}
* @return never null
*/
public static SolverConfig createFromXmlResource(String solverConfigResource) {
return createFromXmlResource(solverConfigResource, null);
}
/**
* As defined by {@link #createFromXmlResource(String)}.
*
* @param solverConfigResource never null, a classpath resource
* as defined by {@link ClassLoader#getResource(String)}
* @param classLoader sometimes null, the {@link ClassLoader} to use for loading all resources and {@link Class}es,
* null to use the default {@link ClassLoader}
* @return never null
*/
public static SolverConfig createFromXmlResource(String solverConfigResource, ClassLoader classLoader) {
ClassLoader actualClassLoader = classLoader != null ? classLoader : Thread.currentThread().getContextClassLoader();
try (InputStream in = actualClassLoader.getResourceAsStream(solverConfigResource)) {
if (in == null) {
String errorMessage = "The solverConfigResource (" + solverConfigResource
+ ") does not exist as a classpath resource in the classLoader (" + actualClassLoader + ").";
if (solverConfigResource.startsWith("/")) {
errorMessage += "\nA classpath resource should not start with a slash (/)."
+ " A solverConfigResource adheres to ClassLoader.getResource(String)."
+ " Maybe remove the leading slash from the solverConfigResource.";
}
throw new IllegalArgumentException(errorMessage);
}
return createFromXmlInputStream(in, classLoader);
} catch (TimefoldXmlSerializationException e) {
throw new IllegalArgumentException("Unmarshalling of solverConfigResource (" + solverConfigResource + ") fails.",
e);
} catch (IOException e) {
throw new IllegalArgumentException("Reading the solverConfigResource (" + solverConfigResource + ") fails.", e);
}
}
/**
* Reads an XML solver configuration from the file system.
* <p>
* Warning: this leads to platform dependent code,
* it's recommend to use {@link #createFromXmlResource(String)} instead.
*
* @param solverConfigFile never null
* @return never null
*/
public static SolverConfig createFromXmlFile(File solverConfigFile) {
return createFromXmlFile(solverConfigFile, null);
}
/**
* As defined by {@link #createFromXmlFile(File)}.
*
* @param solverConfigFile never null
* @param classLoader sometimes null, the {@link ClassLoader} to use for loading all resources and {@link Class}es,
* null to use the default {@link ClassLoader}
* @return never null
*/
public static SolverConfig createFromXmlFile(File solverConfigFile, ClassLoader classLoader) {
try (InputStream in = new FileInputStream(solverConfigFile)) {
return createFromXmlInputStream(in, classLoader);
} catch (TimefoldXmlSerializationException e) {
throw new IllegalArgumentException("Unmarshalling the solverConfigFile (" + solverConfigFile + ") fails.", e);
} catch (FileNotFoundException e) {
throw new IllegalArgumentException("The solverConfigFile (" + solverConfigFile + ") was not found.", e);
} catch (IOException e) {
throw new IllegalArgumentException("Reading the solverConfigFile (" + solverConfigFile + ") fails.", e);
}
}
/**
* @param in never null, gets closed
* @return never null
*/
public static SolverConfig createFromXmlInputStream(InputStream in) {
return createFromXmlInputStream(in, null);
}
/**
* As defined by {@link #createFromXmlInputStream(InputStream)}.
*
* @param in never null, gets closed
* @param classLoader sometimes null, the {@link ClassLoader} to use for loading all resources and {@link Class}es,
* null to use the default {@link ClassLoader}
* @return never null
*/
public static SolverConfig createFromXmlInputStream(InputStream in, ClassLoader classLoader) {
try (Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) {
return createFromXmlReader(reader, classLoader);
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("This vm does not support the charset (" + StandardCharsets.UTF_8 + ").", e);
} catch (IOException e) {
throw new IllegalArgumentException("Reading solverConfigInputStream fails.", e);
}
}
/**
* @param reader never null, gets closed
* @return never null
*/
public static SolverConfig createFromXmlReader(Reader reader) {
return createFromXmlReader(reader, null);
}
/**
* As defined by {@link #createFromXmlReader(Reader)}.
*
* @param reader never null, gets closed
* @param classLoader sometimes null, the {@link ClassLoader} to use for loading all resources and {@link Class}es,
* null to use the default {@link ClassLoader}
* @return never null
*/
public static SolverConfig createFromXmlReader(Reader reader, ClassLoader classLoader) {
SolverConfigIO solverConfigIO = new SolverConfigIO();
SolverConfig solverConfig = solverConfigIO.read(reader);
solverConfig.setClassLoader(classLoader);
return solverConfig;
}
// ************************************************************************
// Fields
// ************************************************************************
public static final String MOVE_THREAD_COUNT_NONE = "NONE";
public static final String MOVE_THREAD_COUNT_AUTO = "AUTO";
@XmlTransient
private ClassLoader classLoader = null;
// Warning: all fields are null (and not defaulted) because they can be inherited
// and also because the input config file should match the output config file
protected EnvironmentMode environmentMode = null;
protected Boolean daemon = null;
protected RandomType randomType = null;
protected Long randomSeed = null;
protected Class<? extends RandomFactory> randomFactoryClass = null;
protected String moveThreadCount = null;
protected Integer moveThreadBufferSize = null;
protected Class<? extends ThreadFactory> threadFactoryClass = null;
protected Class<?> solutionClass = null;
@XmlElement(name = "entityClass")
protected List<Class<?>> entityClassList = null;
protected DomainAccessType domainAccessType = null;
@XmlTransient
protected Map<String, MemberAccessor> gizmoMemberAccessorMap = null;
@XmlTransient
protected Map<String, SolutionCloner> gizmoSolutionClonerMap = null;
@XmlElement(name = "scoreDirectorFactory")
protected ScoreDirectorFactoryConfig scoreDirectorFactoryConfig = null;
@XmlElement(name = "termination")
private TerminationConfig terminationConfig;
protected Class<? extends NearbyDistanceMeter<?, ?>> nearbyDistanceMeterClass = null;
@XmlElements({
@XmlElement(name = ConstructionHeuristicPhaseConfig.XML_ELEMENT_NAME,
type = ConstructionHeuristicPhaseConfig.class),
@XmlElement(name = CustomPhaseConfig.XML_ELEMENT_NAME, type = CustomPhaseConfig.class),
@XmlElement(name = ExhaustiveSearchPhaseConfig.XML_ELEMENT_NAME, type = ExhaustiveSearchPhaseConfig.class),
@XmlElement(name = LocalSearchPhaseConfig.XML_ELEMENT_NAME, type = LocalSearchPhaseConfig.class),
@XmlElement(name = NoChangePhaseConfig.XML_ELEMENT_NAME, type = NoChangePhaseConfig.class),
@XmlElement(name = PartitionedSearchPhaseConfig.XML_ELEMENT_NAME, type = PartitionedSearchPhaseConfig.class)
})
protected List<PhaseConfig> phaseConfigList = null;
@XmlElement(name = "monitoring")
protected MonitoringConfig monitoringConfig = null;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
/**
* Create an empty solver config.
*/
public SolverConfig() {
}
/**
* @param classLoader sometimes null
*/
public SolverConfig(ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Allows you to programmatically change the {@link SolverConfig} per concurrent request,
* based on a template solver config,
* by building a separate {@link SolverFactory} with {@link SolverFactory#create(SolverConfig)}
* and a separate {@link Solver} per request to avoid race conditions.
*
* @param inheritedConfig never null
*/
public SolverConfig(SolverConfig inheritedConfig) {
inherit(inheritedConfig);
}
public ClassLoader getClassLoader() {
return classLoader;
}
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public EnvironmentMode getEnvironmentMode() {
return environmentMode;
}
public void setEnvironmentMode(EnvironmentMode environmentMode) {
this.environmentMode = environmentMode;
}
public Boolean getDaemon() {
return daemon;
}
public void setDaemon(Boolean daemon) {
this.daemon = daemon;
}
public RandomType getRandomType() {
return randomType;
}
public void setRandomType(RandomType randomType) {
this.randomType = randomType;
}
public Long getRandomSeed() {
return randomSeed;
}
public void setRandomSeed(Long randomSeed) {
this.randomSeed = randomSeed;
}
public Class<? extends RandomFactory> getRandomFactoryClass() {
return randomFactoryClass;
}
public void setRandomFactoryClass(Class<? extends RandomFactory> randomFactoryClass) {
this.randomFactoryClass = randomFactoryClass;
}
public String getMoveThreadCount() {
return moveThreadCount;
}
public void setMoveThreadCount(String moveThreadCount) {
this.moveThreadCount = moveThreadCount;
}
public Integer getMoveThreadBufferSize() {
return moveThreadBufferSize;
}
public void setMoveThreadBufferSize(Integer moveThreadBufferSize) {
this.moveThreadBufferSize = moveThreadBufferSize;
}
public Class<? extends ThreadFactory> getThreadFactoryClass() {
return threadFactoryClass;
}
public void setThreadFactoryClass(Class<? extends ThreadFactory> threadFactoryClass) {
this.threadFactoryClass = threadFactoryClass;
}
public Class<?> getSolutionClass() {
return solutionClass;
}
public void setSolutionClass(Class<?> solutionClass) {
this.solutionClass = solutionClass;
}
public List<Class<?>> getEntityClassList() {
return entityClassList;
}
public void setEntityClassList(List<Class<?>> entityClassList) {
this.entityClassList = entityClassList;
}
public DomainAccessType getDomainAccessType() {
return domainAccessType;
}
public void setDomainAccessType(DomainAccessType domainAccessType) {
this.domainAccessType = domainAccessType;
}
public Map<String, MemberAccessor> getGizmoMemberAccessorMap() {
return gizmoMemberAccessorMap;
}
public void setGizmoMemberAccessorMap(Map<String, MemberAccessor> gizmoMemberAccessorMap) {
this.gizmoMemberAccessorMap = gizmoMemberAccessorMap;
}
public Map<String, SolutionCloner> getGizmoSolutionClonerMap() {
return gizmoSolutionClonerMap;
}
public void setGizmoSolutionClonerMap(Map<String, SolutionCloner> gizmoSolutionClonerMap) {
this.gizmoSolutionClonerMap = gizmoSolutionClonerMap;
}
public ScoreDirectorFactoryConfig getScoreDirectorFactoryConfig() {
return scoreDirectorFactoryConfig;
}
public void setScoreDirectorFactoryConfig(ScoreDirectorFactoryConfig scoreDirectorFactoryConfig) {
this.scoreDirectorFactoryConfig = scoreDirectorFactoryConfig;
}
public TerminationConfig getTerminationConfig() {
return terminationConfig;
}
public void setTerminationConfig(TerminationConfig terminationConfig) {
this.terminationConfig = terminationConfig;
}
public Class<? extends NearbyDistanceMeter<?, ?>> getNearbyDistanceMeterClass() {
return nearbyDistanceMeterClass;
}
public void setNearbyDistanceMeterClass(Class<? extends NearbyDistanceMeter<?, ?>> nearbyDistanceMeterClass) {
this.nearbyDistanceMeterClass = nearbyDistanceMeterClass;
}
public List<PhaseConfig> getPhaseConfigList() {
return phaseConfigList;
}
public void setPhaseConfigList(List<PhaseConfig> phaseConfigList) {
this.phaseConfigList = phaseConfigList;
}
public MonitoringConfig getMonitoringConfig() {
return monitoringConfig;
}
public void setMonitoringConfig(MonitoringConfig monitoringConfig) {
this.monitoringConfig = monitoringConfig;
}
// ************************************************************************
// With methods
// ************************************************************************
public SolverConfig withEnvironmentMode(EnvironmentMode environmentMode) {
this.environmentMode = environmentMode;
return this;
}
public SolverConfig withDaemon(Boolean daemon) {
this.daemon = daemon;
return this;
}
public SolverConfig withRandomType(RandomType randomType) {
this.randomType = randomType;
return this;
}
public SolverConfig withRandomSeed(Long randomSeed) {
this.randomSeed = randomSeed;
return this;
}
public SolverConfig withRandomFactoryClass(Class<? extends RandomFactory> randomFactoryClass) {
this.randomFactoryClass = randomFactoryClass;
return this;
}
public SolverConfig withMoveThreadCount(String moveThreadCount) {
this.moveThreadCount = moveThreadCount;
return this;
}
public SolverConfig withMoveThreadBufferSize(Integer moveThreadBufferSize) {
this.moveThreadBufferSize = moveThreadBufferSize;
return this;
}
public SolverConfig withThreadFactoryClass(Class<? extends ThreadFactory> threadFactoryClass) {
this.threadFactoryClass = threadFactoryClass;
return this;
}
public SolverConfig withSolutionClass(Class<?> solutionClass) {
this.solutionClass = solutionClass;
return this;
}
public SolverConfig withEntityClassList(List<Class<?>> entityClassList) {
this.entityClassList = entityClassList;
return this;
}
public SolverConfig withEntityClasses(Class<?>... entityClasses) {
this.entityClassList = Arrays.asList(entityClasses);
return this;
}
public SolverConfig withDomainAccessType(DomainAccessType domainAccessType) {
this.domainAccessType = domainAccessType;
return this;
}
public SolverConfig withGizmoMemberAccessorMap(Map<String, MemberAccessor> memberAccessorMap) {
this.gizmoMemberAccessorMap = memberAccessorMap;
return this;
}
public SolverConfig withGizmoSolutionClonerMap(Map<String, SolutionCloner> solutionClonerMap) {
this.gizmoSolutionClonerMap = solutionClonerMap;
return this;
}
public SolverConfig withScoreDirectorFactory(ScoreDirectorFactoryConfig scoreDirectorFactoryConfig) {
this.scoreDirectorFactoryConfig = scoreDirectorFactoryConfig;
return this;
}
public SolverConfig withClassLoader(ClassLoader classLoader) {
this.setClassLoader(classLoader);
return this;
}
/**
* As defined by {@link ScoreDirectorFactoryConfig#withEasyScoreCalculatorClass(Class)}, but returns this.
*
* @param easyScoreCalculatorClass sometimes null
* @return this, never null
*/
public SolverConfig withEasyScoreCalculatorClass(Class<? extends EasyScoreCalculator> easyScoreCalculatorClass) {
if (scoreDirectorFactoryConfig == null) {
scoreDirectorFactoryConfig = new ScoreDirectorFactoryConfig();
}
scoreDirectorFactoryConfig.setEasyScoreCalculatorClass(easyScoreCalculatorClass);
return this;
}
/**
* As defined by {@link ScoreDirectorFactoryConfig#withConstraintProviderClass(Class)}, but returns this.
*
* @param constraintProviderClass sometimes null
* @return this, never null
*/
public SolverConfig withConstraintProviderClass(Class<? extends ConstraintProvider> constraintProviderClass) {
if (scoreDirectorFactoryConfig == null) {
scoreDirectorFactoryConfig = new ScoreDirectorFactoryConfig();
}
scoreDirectorFactoryConfig.setConstraintProviderClass(constraintProviderClass);
return this;
}
public SolverConfig withConstraintStreamImplType(ConstraintStreamImplType constraintStreamImplType) {
if (scoreDirectorFactoryConfig == null) {
scoreDirectorFactoryConfig = new ScoreDirectorFactoryConfig();
}
scoreDirectorFactoryConfig.setConstraintStreamImplType(constraintStreamImplType);
return this;
}
public SolverConfig withTerminationConfig(TerminationConfig terminationConfig) {
this.terminationConfig = terminationConfig;
return this;
}
/**
* As defined by {@link TerminationConfig#withSpentLimit(Duration)}, but returns this.
*
* @param spentLimit sometimes null
* @return this, never null
*/
public SolverConfig withTerminationSpentLimit(Duration spentLimit) {
if (terminationConfig == null) {
terminationConfig = new TerminationConfig();
}
terminationConfig.setSpentLimit(spentLimit);
return this;
}
public SolverConfig withNearbyDistanceMeterClass(Class<? extends NearbyDistanceMeter<?, ?>> distanceMeterClass) {
this.nearbyDistanceMeterClass = distanceMeterClass;
return this;
}
public SolverConfig withPhaseList(List<PhaseConfig> phaseConfigList) {
this.phaseConfigList = phaseConfigList;
return this;
}
public SolverConfig withPhases(PhaseConfig... phaseConfigs) {
this.phaseConfigList = Arrays.asList(phaseConfigs);
return this;
}
public SolverConfig withMonitoringConfig(MonitoringConfig monitoringConfig) {
this.monitoringConfig = monitoringConfig;
return this;
}
// ************************************************************************
// Smart getters
// ************************************************************************
/**
*
* @return true if the solver has either a global termination configured,
* or all of its phases have a termination configured
*/
public boolean canTerminate() {
if (terminationConfig == null || !terminationConfig.isConfigured()) {
if (getPhaseConfigList() == null) {
return true;
} else {
return getPhaseConfigList().stream()
.allMatch(PhaseFactory::canTerminate);
}
} else {
return terminationConfig.isConfigured();
}
}
public EnvironmentMode determineEnvironmentMode() {
return Objects.requireNonNullElse(environmentMode, EnvironmentMode.REPRODUCIBLE);
}
public DomainAccessType determineDomainAccessType() {
return Objects.requireNonNullElse(domainAccessType, DomainAccessType.REFLECTION);
}
public MonitoringConfig determineMetricConfig() {
return Objects.requireNonNullElse(monitoringConfig,
new MonitoringConfig().withSolverMetricList(Arrays.asList(SolverMetric.SOLVE_DURATION, SolverMetric.ERROR_COUNT,
SolverMetric.SCORE_CALCULATION_COUNT, SolverMetric.PROBLEM_ENTITY_COUNT,
SolverMetric.PROBLEM_VARIABLE_COUNT, SolverMetric.PROBLEM_VALUE_COUNT,
SolverMetric.PROBLEM_SIZE_LOG)));
}
// ************************************************************************
// Builder methods
// ************************************************************************
public void offerRandomSeedFromSubSingleIndex(long subSingleIndex) {
if (environmentMode == null || environmentMode.isReproducible()) {
if (randomFactoryClass == null && randomSeed == null) {
randomSeed = subSingleIndex;
}
}
}
/**
* Do not use this method, it is an internal method.
* Use {@link #SolverConfig(SolverConfig)} instead.
*
* @param inheritedConfig never null
*/
@Override
public SolverConfig inherit(SolverConfig inheritedConfig) {
classLoader = ConfigUtils.inheritOverwritableProperty(classLoader, inheritedConfig.getClassLoader());
environmentMode = ConfigUtils.inheritOverwritableProperty(environmentMode, inheritedConfig.getEnvironmentMode());
daemon = ConfigUtils.inheritOverwritableProperty(daemon, inheritedConfig.getDaemon());
randomType = ConfigUtils.inheritOverwritableProperty(randomType, inheritedConfig.getRandomType());
randomSeed = ConfigUtils.inheritOverwritableProperty(randomSeed, inheritedConfig.getRandomSeed());
randomFactoryClass = ConfigUtils.inheritOverwritableProperty(randomFactoryClass,
inheritedConfig.getRandomFactoryClass());
moveThreadCount = ConfigUtils.inheritOverwritableProperty(moveThreadCount,
inheritedConfig.getMoveThreadCount());
moveThreadBufferSize = ConfigUtils.inheritOverwritableProperty(moveThreadBufferSize,
inheritedConfig.getMoveThreadBufferSize());
threadFactoryClass = ConfigUtils.inheritOverwritableProperty(threadFactoryClass,
inheritedConfig.getThreadFactoryClass());
solutionClass = ConfigUtils.inheritOverwritableProperty(solutionClass, inheritedConfig.getSolutionClass());
entityClassList = ConfigUtils.inheritMergeableListProperty(entityClassList,
inheritedConfig.getEntityClassList());
domainAccessType = ConfigUtils.inheritOverwritableProperty(domainAccessType, inheritedConfig.getDomainAccessType());
gizmoMemberAccessorMap = ConfigUtils.inheritMergeableMapProperty(
gizmoMemberAccessorMap, inheritedConfig.getGizmoMemberAccessorMap());
gizmoSolutionClonerMap = ConfigUtils.inheritMergeableMapProperty(
gizmoSolutionClonerMap, inheritedConfig.getGizmoSolutionClonerMap());
scoreDirectorFactoryConfig = ConfigUtils.inheritConfig(scoreDirectorFactoryConfig,
inheritedConfig.getScoreDirectorFactoryConfig());
terminationConfig = ConfigUtils.inheritConfig(terminationConfig, inheritedConfig.getTerminationConfig());
nearbyDistanceMeterClass = ConfigUtils.inheritOverwritableProperty(nearbyDistanceMeterClass,
inheritedConfig.getNearbyDistanceMeterClass());
phaseConfigList = ConfigUtils.inheritMergeableListConfig(phaseConfigList, inheritedConfig.getPhaseConfigList());
monitoringConfig = ConfigUtils.inheritConfig(monitoringConfig, inheritedConfig.getMonitoringConfig());
return this;
}
@Override
public SolverConfig copyConfig() {
return new SolverConfig().inherit(this);
}
@Override
public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {
classVisitor.accept(randomFactoryClass);
classVisitor.accept(threadFactoryClass);
classVisitor.accept(solutionClass);
if (entityClassList != null) {
entityClassList.forEach(classVisitor);
}
if (scoreDirectorFactoryConfig != null) {
scoreDirectorFactoryConfig.visitReferencedClasses(classVisitor);
}
if (terminationConfig != null) {
terminationConfig.visitReferencedClasses(classVisitor);
}
if (phaseConfigList != null) {
phaseConfigList.forEach(pc -> pc.visitReferencedClasses(classVisitor));
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/solver/SolverManagerConfig.java | package ai.timefold.solver.core.config.solver;
import java.util.concurrent.ThreadFactory;
import java.util.function.Consumer;
import jakarta.xml.bind.annotation.XmlType;
import ai.timefold.solver.core.config.AbstractConfig;
import ai.timefold.solver.core.config.util.ConfigUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@XmlType(propOrder = {
"parallelSolverCount",
"threadFactoryClass"
})
public class SolverManagerConfig extends AbstractConfig<SolverManagerConfig> {
public static final String PARALLEL_SOLVER_COUNT_AUTO = "AUTO";
private static final Logger LOGGER = LoggerFactory.getLogger(SolverManagerConfig.class);
protected String parallelSolverCount = null;
protected Class<? extends ThreadFactory> threadFactoryClass = null;
// Future features:
// throttlingDelay
// congestionStrategy
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public SolverManagerConfig() {
}
public String getParallelSolverCount() {
return parallelSolverCount;
}
public void setParallelSolverCount(String parallelSolverCount) {
this.parallelSolverCount = parallelSolverCount;
}
public Class<? extends ThreadFactory> getThreadFactoryClass() {
return threadFactoryClass;
}
public void setThreadFactoryClass(Class<? extends ThreadFactory> threadFactoryClass) {
this.threadFactoryClass = threadFactoryClass;
}
// ************************************************************************
// With methods
// ************************************************************************
public SolverManagerConfig withParallelSolverCount(String parallelSolverCount) {
this.parallelSolverCount = parallelSolverCount;
return this;
}
public SolverManagerConfig withThreadFactoryClass(Class<? extends ThreadFactory> threadFactoryClass) {
this.threadFactoryClass = threadFactoryClass;
return this;
}
// ************************************************************************
// Builder methods
// ************************************************************************
public Integer resolveParallelSolverCount() {
int availableProcessorCount = getAvailableProcessors();
Integer resolvedParallelSolverCount;
if (parallelSolverCount == null || parallelSolverCount.equals(PARALLEL_SOLVER_COUNT_AUTO)) {
resolvedParallelSolverCount = resolveParallelSolverCountAutomatically(availableProcessorCount);
} else {
resolvedParallelSolverCount = ConfigUtils.resolvePoolSize("parallelSolverCount",
parallelSolverCount, PARALLEL_SOLVER_COUNT_AUTO);
}
if (resolvedParallelSolverCount < 1) {
throw new IllegalArgumentException("The parallelSolverCount (" + parallelSolverCount
+ ") resulted in a resolvedParallelSolverCount (" + resolvedParallelSolverCount
+ ") that is lower than 1.");
}
if (resolvedParallelSolverCount > availableProcessorCount) {
LOGGER.warn("The resolvedParallelSolverCount ({}) is higher "
+ "than the availableProcessorCount ({}), which is counter-efficient.",
resolvedParallelSolverCount, availableProcessorCount);
// Still allow it, to reproduce issues of a high-end server machine on a low-end developer machine
}
return resolvedParallelSolverCount;
}
protected int getAvailableProcessors() {
return Runtime.getRuntime().availableProcessors();
}
protected int resolveParallelSolverCountAutomatically(int availableProcessorCount) {
// Tweaked based on experience
if (availableProcessorCount < 2) {
return 1;
} else {
return availableProcessorCount / 2;
}
}
@Override
public SolverManagerConfig inherit(SolverManagerConfig inheritedConfig) {
parallelSolverCount = ConfigUtils.inheritOverwritableProperty(parallelSolverCount,
inheritedConfig.getParallelSolverCount());
threadFactoryClass = ConfigUtils.inheritOverwritableProperty(threadFactoryClass,
inheritedConfig.getThreadFactoryClass());
return this;
}
@Override
public SolverManagerConfig copyConfig() {
return new SolverManagerConfig().inherit(this);
}
@Override
public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {
classVisitor.accept(threadFactoryClass);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/solver/monitoring/MonitoringConfig.java | package ai.timefold.solver.core.config.solver.monitoring;
import java.util.List;
import java.util.function.Consumer;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
import ai.timefold.solver.core.config.AbstractConfig;
import ai.timefold.solver.core.config.util.ConfigUtils;
@XmlType(propOrder = {
"solverMetricList",
})
public class MonitoringConfig extends AbstractConfig<MonitoringConfig> {
@XmlElement(name = "metric")
protected List<SolverMetric> solverMetricList = null;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public List<SolverMetric> getSolverMetricList() {
return solverMetricList;
}
public void setSolverMetricList(List<SolverMetric> solverMetricList) {
this.solverMetricList = solverMetricList;
}
// ************************************************************************
// With methods
// ************************************************************************
public MonitoringConfig withSolverMetricList(List<SolverMetric> solverMetricList) {
this.solverMetricList = solverMetricList;
return this;
}
@Override
public MonitoringConfig inherit(MonitoringConfig inheritedConfig) {
solverMetricList = ConfigUtils.inheritMergeableListProperty(solverMetricList, inheritedConfig.solverMetricList);
return this;
}
@Override
public MonitoringConfig copyConfig() {
return new MonitoringConfig().inherit(this);
}
@Override
public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {
// No referenced classes currently
// If we add custom metrics here, then this should
// register the custom metrics
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/solver/monitoring/SolverMetric.java | package ai.timefold.solver.core.config.solver.monitoring;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.ToDoubleFunction;
import jakarta.xml.bind.annotation.XmlEnum;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.statistic.BestScoreStatistic;
import ai.timefold.solver.core.impl.statistic.BestSolutionMutationCountStatistic;
import ai.timefold.solver.core.impl.statistic.MemoryUseStatistic;
import ai.timefold.solver.core.impl.statistic.PickedMoveBestScoreDiffStatistic;
import ai.timefold.solver.core.impl.statistic.PickedMoveStepScoreDiffStatistic;
import ai.timefold.solver.core.impl.statistic.SolverScopeStatistic;
import ai.timefold.solver.core.impl.statistic.SolverStatistic;
import ai.timefold.solver.core.impl.statistic.StatelessSolverStatistic;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
@XmlEnum
public enum SolverMetric {
SOLVE_DURATION("timefold.solver.solve.duration", false),
ERROR_COUNT("timefold.solver.errors", false),
SCORE_CALCULATION_COUNT("timefold.solver.score.calculation.count",
SolverScope::getScoreCalculationCount,
false),
PROBLEM_ENTITY_COUNT("timefold.solver.problem.entities",
solverScope -> solverScope.getProblemSizeStatistics().entityCount(),
false),
PROBLEM_VARIABLE_COUNT("timefold.solver.problem.variables",
solverScope -> solverScope.getProblemSizeStatistics().variableCount(),
false),
PROBLEM_VALUE_COUNT("timefold.solver.problem.values",
solverScope -> solverScope.getProblemSizeStatistics().approximateValueCount(),
false),
PROBLEM_SIZE_LOG("timefold.solver.problem.size.log",
solverScope -> solverScope.getProblemSizeStatistics().approximateProblemSizeLog(),
false),
BEST_SCORE("timefold.solver.best.score", new BestScoreStatistic<>(), true),
STEP_SCORE("timefold.solver.step.score", false),
BEST_SOLUTION_MUTATION("timefold.solver.best.solution.mutation", new BestSolutionMutationCountStatistic<>(), true),
MOVE_COUNT_PER_STEP("timefold.solver.step.move.count", false),
MEMORY_USE("jvm.memory.used", new MemoryUseStatistic<>(), false),
CONSTRAINT_MATCH_TOTAL_BEST_SCORE("timefold.solver.constraint.match.best.score", true, true),
CONSTRAINT_MATCH_TOTAL_STEP_SCORE("timefold.solver.constraint.match.step.score", false, true),
PICKED_MOVE_TYPE_BEST_SCORE_DIFF("timefold.solver.move.type.best.score.diff", new PickedMoveBestScoreDiffStatistic<>(),
true),
PICKED_MOVE_TYPE_STEP_SCORE_DIFF("timefold.solver.move.type.step.score.diff", new PickedMoveStepScoreDiffStatistic<>(),
false);
private final String meterId;
@SuppressWarnings("rawtypes")
private final SolverStatistic registerFunction;
private final boolean isBestSolutionBased;
private final boolean isConstraintMatchBased;
SolverMetric(String meterId, boolean isBestSolutionBased) {
this(meterId, isBestSolutionBased, false);
}
SolverMetric(String meterId, boolean isBestSolutionBased, boolean isConstraintMatchBased) {
this(meterId, new StatelessSolverStatistic<>(), isBestSolutionBased, isConstraintMatchBased);
}
SolverMetric(String meterId, ToDoubleFunction<SolverScope<Object>> gaugeFunction, boolean isBestSolutionBased) {
this(meterId, new SolverScopeStatistic<>(meterId, gaugeFunction), isBestSolutionBased, false);
}
SolverMetric(String meterId, SolverStatistic<?> registerFunction, boolean isBestSolutionBased) {
this(meterId, registerFunction, isBestSolutionBased, false);
}
SolverMetric(String meterId, SolverStatistic<?> registerFunction, boolean isBestSolutionBased,
boolean isConstraintMatchBased) {
this.meterId = meterId;
this.registerFunction = registerFunction;
this.isBestSolutionBased = isBestSolutionBased;
this.isConstraintMatchBased = isConstraintMatchBased;
}
public String getMeterId() {
return meterId;
}
public static void registerScoreMetrics(SolverMetric metric, Tags tags, ScoreDefinition<?> scoreDefinition,
Map<Tags, List<AtomicReference<Number>>> tagToScoreLevels, Score<?> score) {
Number[] levelValues = score.toLevelNumbers();
if (tagToScoreLevels.containsKey(tags)) {
List<AtomicReference<Number>> scoreLevels = tagToScoreLevels.get(tags);
for (int i = 0; i < levelValues.length; i++) {
scoreLevels.get(i).set(levelValues[i]);
}
} else {
String[] levelLabels = scoreDefinition.getLevelLabels();
for (int i = 0; i < levelLabels.length; i++) {
levelLabels[i] = levelLabels[i].replace(' ', '.');
}
List<AtomicReference<Number>> scoreLevels = new ArrayList<>(levelValues.length);
for (int i = 0; i < levelValues.length; i++) {
scoreLevels.add(Metrics.gauge(metric.getMeterId() + "." + levelLabels[i],
tags, new AtomicReference<>(levelValues[i]),
ar -> ar.get().doubleValue()));
}
tagToScoreLevels.put(tags, scoreLevels);
}
}
public boolean isMetricBestSolutionBased() {
return isBestSolutionBased;
}
public boolean isMetricConstraintMatchBased() {
return isConstraintMatchBased;
}
@SuppressWarnings("unchecked")
public void register(Solver<?> solver) {
registerFunction.register(solver);
}
@SuppressWarnings("unchecked")
public void unregister(Solver<?> solver) {
registerFunction.unregister(solver);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/solver | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/solver/termination/TerminationConfig.java | package ai.timefold.solver.core.config.solver.termination;
import java.time.Duration;
import java.util.List;
import java.util.function.Consumer;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlTransient;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import ai.timefold.solver.core.config.AbstractConfig;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.io.jaxb.adapter.JaxbDurationAdapter;
import ai.timefold.solver.core.impl.solver.termination.Termination;
@XmlType(propOrder = {
"terminationClass",
"terminationCompositionStyle",
"spentLimit",
"millisecondsSpentLimit",
"secondsSpentLimit",
"minutesSpentLimit",
"hoursSpentLimit",
"daysSpentLimit",
"unimprovedSpentLimit",
"unimprovedMillisecondsSpentLimit",
"unimprovedSecondsSpentLimit",
"unimprovedMinutesSpentLimit",
"unimprovedHoursSpentLimit",
"unimprovedDaysSpentLimit",
"unimprovedScoreDifferenceThreshold",
"bestScoreLimit",
"bestScoreFeasible",
"stepCountLimit",
"unimprovedStepCountLimit",
"scoreCalculationCountLimit",
"terminationConfigList"
})
public class TerminationConfig extends AbstractConfig<TerminationConfig> {
/**
* @deprecated A custom terminationClass is deprecated and will be removed in a future major version of Timefold.
*/
@Deprecated(forRemoval = true)
private Class<? extends Termination> terminationClass = null;
private TerminationCompositionStyle terminationCompositionStyle = null;
@XmlJavaTypeAdapter(JaxbDurationAdapter.class)
private Duration spentLimit = null;
private Long millisecondsSpentLimit = null;
private Long secondsSpentLimit = null;
private Long minutesSpentLimit = null;
private Long hoursSpentLimit = null;
private Long daysSpentLimit = null;
@XmlJavaTypeAdapter(JaxbDurationAdapter.class)
private Duration unimprovedSpentLimit = null;
private Long unimprovedMillisecondsSpentLimit = null;
private Long unimprovedSecondsSpentLimit = null;
private Long unimprovedMinutesSpentLimit = null;
private Long unimprovedHoursSpentLimit = null;
private Long unimprovedDaysSpentLimit = null;
private String unimprovedScoreDifferenceThreshold = null;
private String bestScoreLimit = null;
private Boolean bestScoreFeasible = null;
private Integer stepCountLimit = null;
private Integer unimprovedStepCountLimit = null;
private Long scoreCalculationCountLimit = null;
@XmlElement(name = "termination")
private List<TerminationConfig> terminationConfigList = null;
/**
* @deprecated A custom terminationClass is deprecated and will be removed in a future major version of Timefold.
*/
@Deprecated(forRemoval = true)
public Class<? extends Termination> getTerminationClass() {
return terminationClass;
}
/**
* @deprecated A custom terminationClass is deprecated and will be removed in a future major version of Timefold.
*/
@Deprecated(forRemoval = true)
public void setTerminationClass(Class<? extends Termination> terminationClass) {
this.terminationClass = terminationClass;
}
public TerminationCompositionStyle getTerminationCompositionStyle() {
return terminationCompositionStyle;
}
public void setTerminationCompositionStyle(TerminationCompositionStyle terminationCompositionStyle) {
this.terminationCompositionStyle = terminationCompositionStyle;
}
public Duration getSpentLimit() {
return spentLimit;
}
public void setSpentLimit(Duration spentLimit) {
this.spentLimit = spentLimit;
}
public Long getMillisecondsSpentLimit() {
return millisecondsSpentLimit;
}
public void setMillisecondsSpentLimit(Long millisecondsSpentLimit) {
this.millisecondsSpentLimit = millisecondsSpentLimit;
}
public Long getSecondsSpentLimit() {
return secondsSpentLimit;
}
public void setSecondsSpentLimit(Long secondsSpentLimit) {
this.secondsSpentLimit = secondsSpentLimit;
}
public Long getMinutesSpentLimit() {
return minutesSpentLimit;
}
public void setMinutesSpentLimit(Long minutesSpentLimit) {
this.minutesSpentLimit = minutesSpentLimit;
}
public Long getHoursSpentLimit() {
return hoursSpentLimit;
}
public void setHoursSpentLimit(Long hoursSpentLimit) {
this.hoursSpentLimit = hoursSpentLimit;
}
public Long getDaysSpentLimit() {
return daysSpentLimit;
}
public void setDaysSpentLimit(Long daysSpentLimit) {
this.daysSpentLimit = daysSpentLimit;
}
public Duration getUnimprovedSpentLimit() {
return unimprovedSpentLimit;
}
public void setUnimprovedSpentLimit(Duration unimprovedSpentLimit) {
this.unimprovedSpentLimit = unimprovedSpentLimit;
}
public Long getUnimprovedMillisecondsSpentLimit() {
return unimprovedMillisecondsSpentLimit;
}
public void setUnimprovedMillisecondsSpentLimit(Long unimprovedMillisecondsSpentLimit) {
this.unimprovedMillisecondsSpentLimit = unimprovedMillisecondsSpentLimit;
}
public Long getUnimprovedSecondsSpentLimit() {
return unimprovedSecondsSpentLimit;
}
public void setUnimprovedSecondsSpentLimit(Long unimprovedSecondsSpentLimit) {
this.unimprovedSecondsSpentLimit = unimprovedSecondsSpentLimit;
}
public Long getUnimprovedMinutesSpentLimit() {
return unimprovedMinutesSpentLimit;
}
public void setUnimprovedMinutesSpentLimit(Long unimprovedMinutesSpentLimit) {
this.unimprovedMinutesSpentLimit = unimprovedMinutesSpentLimit;
}
public Long getUnimprovedHoursSpentLimit() {
return unimprovedHoursSpentLimit;
}
public void setUnimprovedHoursSpentLimit(Long unimprovedHoursSpentLimit) {
this.unimprovedHoursSpentLimit = unimprovedHoursSpentLimit;
}
public Long getUnimprovedDaysSpentLimit() {
return unimprovedDaysSpentLimit;
}
public void setUnimprovedDaysSpentLimit(Long unimprovedDaysSpentLimit) {
this.unimprovedDaysSpentLimit = unimprovedDaysSpentLimit;
}
public String getUnimprovedScoreDifferenceThreshold() {
return unimprovedScoreDifferenceThreshold;
}
public void setUnimprovedScoreDifferenceThreshold(String unimprovedScoreDifferenceThreshold) {
this.unimprovedScoreDifferenceThreshold = unimprovedScoreDifferenceThreshold;
}
public String getBestScoreLimit() {
return bestScoreLimit;
}
public void setBestScoreLimit(String bestScoreLimit) {
this.bestScoreLimit = bestScoreLimit;
}
public Boolean getBestScoreFeasible() {
return bestScoreFeasible;
}
public void setBestScoreFeasible(Boolean bestScoreFeasible) {
this.bestScoreFeasible = bestScoreFeasible;
}
public Integer getStepCountLimit() {
return stepCountLimit;
}
public void setStepCountLimit(Integer stepCountLimit) {
this.stepCountLimit = stepCountLimit;
}
public Integer getUnimprovedStepCountLimit() {
return unimprovedStepCountLimit;
}
public void setUnimprovedStepCountLimit(Integer unimprovedStepCountLimit) {
this.unimprovedStepCountLimit = unimprovedStepCountLimit;
}
public Long getScoreCalculationCountLimit() {
return scoreCalculationCountLimit;
}
public void setScoreCalculationCountLimit(Long scoreCalculationCountLimit) {
this.scoreCalculationCountLimit = scoreCalculationCountLimit;
}
public List<TerminationConfig> getTerminationConfigList() {
return terminationConfigList;
}
public void setTerminationConfigList(List<TerminationConfig> terminationConfigList) {
this.terminationConfigList = terminationConfigList;
}
// ************************************************************************
// With methods
// ************************************************************************
/**
* @deprecated A custom terminationClass is deprecated and will be removed in a future major version of Timefold.
*/
@Deprecated(forRemoval = true)
public TerminationConfig withTerminationClass(Class<? extends Termination> terminationClass) {
this.terminationClass = terminationClass;
return this;
}
public TerminationConfig withTerminationCompositionStyle(TerminationCompositionStyle terminationCompositionStyle) {
this.terminationCompositionStyle = terminationCompositionStyle;
return this;
}
public TerminationConfig withSpentLimit(Duration spentLimit) {
this.spentLimit = spentLimit;
return this;
}
public TerminationConfig withMillisecondsSpentLimit(Long millisecondsSpentLimit) {
this.millisecondsSpentLimit = millisecondsSpentLimit;
return this;
}
public TerminationConfig withSecondsSpentLimit(Long secondsSpentLimit) {
this.secondsSpentLimit = secondsSpentLimit;
return this;
}
public TerminationConfig withMinutesSpentLimit(Long minutesSpentLimit) {
this.minutesSpentLimit = minutesSpentLimit;
return this;
}
public TerminationConfig withHoursSpentLimit(Long hoursSpentLimit) {
this.hoursSpentLimit = hoursSpentLimit;
return this;
}
public TerminationConfig withDaysSpentLimit(Long daysSpentLimit) {
this.daysSpentLimit = daysSpentLimit;
return this;
}
public TerminationConfig withUnimprovedSpentLimit(Duration unimprovedSpentLimit) {
this.unimprovedSpentLimit = unimprovedSpentLimit;
return this;
}
public TerminationConfig withUnimprovedMillisecondsSpentLimit(Long unimprovedMillisecondsSpentLimit) {
this.unimprovedMillisecondsSpentLimit = unimprovedMillisecondsSpentLimit;
return this;
}
public TerminationConfig withUnimprovedSecondsSpentLimit(Long unimprovedSecondsSpentLimit) {
this.unimprovedSecondsSpentLimit = unimprovedSecondsSpentLimit;
return this;
}
public TerminationConfig withUnimprovedMinutesSpentLimit(Long unimprovedMinutesSpentLimit) {
this.unimprovedMinutesSpentLimit = unimprovedMinutesSpentLimit;
return this;
}
public TerminationConfig withUnimprovedHoursSpentLimit(Long unimprovedHoursSpentLimit) {
this.unimprovedHoursSpentLimit = unimprovedHoursSpentLimit;
return this;
}
public TerminationConfig withUnimprovedDaysSpentLimit(Long unimprovedDaysSpentLimit) {
this.unimprovedDaysSpentLimit = unimprovedDaysSpentLimit;
return this;
}
public TerminationConfig withUnimprovedScoreDifferenceThreshold(String unimprovedScoreDifferenceThreshold) {
this.unimprovedScoreDifferenceThreshold = unimprovedScoreDifferenceThreshold;
return this;
}
public TerminationConfig withBestScoreLimit(String bestScoreLimit) {
this.bestScoreLimit = bestScoreLimit;
return this;
}
public TerminationConfig withBestScoreFeasible(Boolean bestScoreFeasible) {
this.bestScoreFeasible = bestScoreFeasible;
return this;
}
public TerminationConfig withStepCountLimit(Integer stepCountLimit) {
this.stepCountLimit = stepCountLimit;
return this;
}
public TerminationConfig withUnimprovedStepCountLimit(Integer unimprovedStepCountLimit) {
this.unimprovedStepCountLimit = unimprovedStepCountLimit;
return this;
}
public TerminationConfig withScoreCalculationCountLimit(Long scoreCalculationCountLimit) {
this.scoreCalculationCountLimit = scoreCalculationCountLimit;
return this;
}
public TerminationConfig withTerminationConfigList(List<TerminationConfig> terminationConfigList) {
this.terminationConfigList = terminationConfigList;
return this;
}
public void overwriteSpentLimit(Duration spentLimit) {
setSpentLimit(spentLimit);
setMillisecondsSpentLimit(null);
setSecondsSpentLimit(null);
setMinutesSpentLimit(null);
setHoursSpentLimit(null);
setDaysSpentLimit(null);
}
public Long calculateTimeMillisSpentLimit() {
if (millisecondsSpentLimit == null && secondsSpentLimit == null
&& minutesSpentLimit == null && hoursSpentLimit == null && daysSpentLimit == null) {
if (spentLimit != null) {
if (spentLimit.getNano() % 1000 != 0) {
throw new IllegalArgumentException("The termination spentLimit (" + spentLimit
+ ") cannot use nanoseconds.");
}
return spentLimit.toMillis();
}
return null;
}
if (spentLimit != null) {
throw new IllegalArgumentException("The termination spentLimit (" + spentLimit
+ ") cannot be combined with millisecondsSpentLimit (" + millisecondsSpentLimit
+ "), secondsSpentLimit (" + secondsSpentLimit
+ "), minutesSpentLimit (" + minutesSpentLimit
+ "), hoursSpentLimit (" + hoursSpentLimit
+ ") or daysSpentLimit (" + daysSpentLimit + ").");
}
long timeMillisSpentLimit = 0L
+ requireNonNegative(millisecondsSpentLimit, "millisecondsSpentLimit")
+ requireNonNegative(secondsSpentLimit, "secondsSpentLimit") * 1_000L
+ requireNonNegative(minutesSpentLimit, "minutesSpentLimit") * 60_000L
+ requireNonNegative(hoursSpentLimit, "hoursSpentLimit") * 3_600_000L
+ requireNonNegative(daysSpentLimit, "daysSpentLimit") * 86_400_000L;
return timeMillisSpentLimit;
}
public void shortenTimeMillisSpentLimit(long timeMillisSpentLimit) {
Long oldLimit = calculateTimeMillisSpentLimit();
if (oldLimit == null || timeMillisSpentLimit < oldLimit) {
spentLimit = null;
millisecondsSpentLimit = timeMillisSpentLimit;
secondsSpentLimit = null;
minutesSpentLimit = null;
hoursSpentLimit = null;
daysSpentLimit = null;
}
}
public void overwriteUnimprovedSpentLimit(Duration unimprovedSpentLimit) {
setUnimprovedSpentLimit(unimprovedSpentLimit);
setUnimprovedMillisecondsSpentLimit(null);
setUnimprovedSecondsSpentLimit(null);
setUnimprovedMinutesSpentLimit(null);
setUnimprovedHoursSpentLimit(null);
setUnimprovedDaysSpentLimit(null);
}
public Long calculateUnimprovedTimeMillisSpentLimit() {
if (unimprovedMillisecondsSpentLimit == null && unimprovedSecondsSpentLimit == null
&& unimprovedMinutesSpentLimit == null && unimprovedHoursSpentLimit == null) {
if (unimprovedSpentLimit != null) {
if (unimprovedSpentLimit.getNano() % 1000 != 0) {
throw new IllegalArgumentException("The termination unimprovedSpentLimit (" + unimprovedSpentLimit
+ ") cannot use nanoseconds.");
}
return unimprovedSpentLimit.toMillis();
}
return null;
}
if (unimprovedSpentLimit != null) {
throw new IllegalArgumentException("The termination unimprovedSpentLimit (" + unimprovedSpentLimit
+ ") cannot be combined with unimprovedMillisecondsSpentLimit (" + unimprovedMillisecondsSpentLimit
+ "), unimprovedSecondsSpentLimit (" + unimprovedSecondsSpentLimit
+ "), unimprovedMinutesSpentLimit (" + unimprovedMinutesSpentLimit
+ "), unimprovedHoursSpentLimit (" + unimprovedHoursSpentLimit + ").");
}
long unimprovedTimeMillisSpentLimit = 0L
+ requireNonNegative(unimprovedMillisecondsSpentLimit, "unimprovedMillisecondsSpentLimit")
+ requireNonNegative(unimprovedSecondsSpentLimit, "unimprovedSecondsSpentLimit") * 1000L
+ requireNonNegative(unimprovedMinutesSpentLimit, "unimprovedMinutesSpentLimit") * 60_000L
+ requireNonNegative(unimprovedHoursSpentLimit, "unimprovedHoursSpentLimit") * 3_600_000L
+ requireNonNegative(unimprovedDaysSpentLimit, "unimprovedDaysSpentLimit") * 86_400_000L;
return unimprovedTimeMillisSpentLimit;
}
/**
* Return true if this TerminationConfig configures a termination condition.
* Note: this does not mean it will always terminate: ex: bestScoreLimit configured,
* but it is impossible to reach the bestScoreLimit.
*/
@XmlTransient
public boolean isConfigured() {
return terminationClass != null ||
timeSpentLimitIsSet() ||
unimprovedTimeSpentLimitIsSet() ||
bestScoreLimit != null ||
bestScoreFeasible != null ||
stepCountLimit != null ||
unimprovedStepCountLimit != null ||
scoreCalculationCountLimit != null ||
isTerminationListConfigured();
}
private boolean isTerminationListConfigured() {
if (terminationConfigList == null || terminationCompositionStyle == null) {
return false;
}
switch (terminationCompositionStyle) {
case AND:
return terminationConfigList.stream().allMatch(TerminationConfig::isConfigured);
case OR:
return terminationConfigList.stream().anyMatch(TerminationConfig::isConfigured);
default:
throw new IllegalStateException("Unhandled case (" + terminationCompositionStyle + ").");
}
}
@Override
public TerminationConfig inherit(TerminationConfig inheritedConfig) {
if (!timeSpentLimitIsSet()) {
inheritTimeSpentLimit(inheritedConfig);
}
if (!unimprovedTimeSpentLimitIsSet()) {
inheritUnimprovedTimeSpentLimit(inheritedConfig);
}
terminationClass = ConfigUtils.inheritOverwritableProperty(terminationClass,
inheritedConfig.getTerminationClass());
terminationCompositionStyle = ConfigUtils.inheritOverwritableProperty(terminationCompositionStyle,
inheritedConfig.getTerminationCompositionStyle());
unimprovedScoreDifferenceThreshold = ConfigUtils.inheritOverwritableProperty(unimprovedScoreDifferenceThreshold,
inheritedConfig.getUnimprovedScoreDifferenceThreshold());
bestScoreLimit = ConfigUtils.inheritOverwritableProperty(bestScoreLimit,
inheritedConfig.getBestScoreLimit());
bestScoreFeasible = ConfigUtils.inheritOverwritableProperty(bestScoreFeasible,
inheritedConfig.getBestScoreFeasible());
stepCountLimit = ConfigUtils.inheritOverwritableProperty(stepCountLimit,
inheritedConfig.getStepCountLimit());
unimprovedStepCountLimit = ConfigUtils.inheritOverwritableProperty(unimprovedStepCountLimit,
inheritedConfig.getUnimprovedStepCountLimit());
scoreCalculationCountLimit = ConfigUtils.inheritOverwritableProperty(scoreCalculationCountLimit,
inheritedConfig.getScoreCalculationCountLimit());
terminationConfigList = ConfigUtils.inheritMergeableListConfig(
terminationConfigList, inheritedConfig.getTerminationConfigList());
return this;
}
@Override
public TerminationConfig copyConfig() {
return new TerminationConfig().inherit(this);
}
@Override
public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {
classVisitor.accept(terminationClass);
if (terminationConfigList != null) {
terminationConfigList.forEach(tc -> tc.visitReferencedClasses(classVisitor));
}
}
private TerminationConfig inheritTimeSpentLimit(TerminationConfig parent) {
spentLimit = ConfigUtils.inheritOverwritableProperty(spentLimit,
parent.getSpentLimit());
millisecondsSpentLimit = ConfigUtils.inheritOverwritableProperty(millisecondsSpentLimit,
parent.getMillisecondsSpentLimit());
secondsSpentLimit = ConfigUtils.inheritOverwritableProperty(secondsSpentLimit,
parent.getSecondsSpentLimit());
minutesSpentLimit = ConfigUtils.inheritOverwritableProperty(minutesSpentLimit,
parent.getMinutesSpentLimit());
hoursSpentLimit = ConfigUtils.inheritOverwritableProperty(hoursSpentLimit,
parent.getHoursSpentLimit());
daysSpentLimit = ConfigUtils.inheritOverwritableProperty(daysSpentLimit,
parent.getDaysSpentLimit());
return this;
}
private TerminationConfig inheritUnimprovedTimeSpentLimit(TerminationConfig parent) {
unimprovedSpentLimit = ConfigUtils.inheritOverwritableProperty(unimprovedSpentLimit,
parent.getUnimprovedSpentLimit());
unimprovedMillisecondsSpentLimit = ConfigUtils.inheritOverwritableProperty(unimprovedMillisecondsSpentLimit,
parent.getUnimprovedMillisecondsSpentLimit());
unimprovedSecondsSpentLimit = ConfigUtils.inheritOverwritableProperty(unimprovedSecondsSpentLimit,
parent.getUnimprovedSecondsSpentLimit());
unimprovedMinutesSpentLimit = ConfigUtils.inheritOverwritableProperty(unimprovedMinutesSpentLimit,
parent.getUnimprovedMinutesSpentLimit());
unimprovedHoursSpentLimit = ConfigUtils.inheritOverwritableProperty(unimprovedHoursSpentLimit,
parent.getUnimprovedHoursSpentLimit());
unimprovedDaysSpentLimit = ConfigUtils.inheritOverwritableProperty(unimprovedDaysSpentLimit,
parent.getUnimprovedDaysSpentLimit());
return this;
}
/**
* Assert that the parameter is non-negative and return its value,
* converting {@code null} to 0.
*
* @param param the parameter to test/convert
* @param name the name of the parameter, for use in the exception message
* @throws IllegalArgumentException iff param is negative
*/
private Long requireNonNegative(Long param, String name) {
if (param == null) {
return 0L; // Makes adding a null param a NOP.
} else if (param < 0L) {
String msg = String.format("The termination %s (%d) cannot be negative.", name, param);
throw new IllegalArgumentException(msg);
} else {
return param;
}
}
/** Check whether any ...SpentLimit is non-null. */
private boolean timeSpentLimitIsSet() {
return getDaysSpentLimit() != null
|| getHoursSpentLimit() != null
|| getMinutesSpentLimit() != null
|| getSecondsSpentLimit() != null
|| getMillisecondsSpentLimit() != null
|| getSpentLimit() != null;
}
/** Check whether any unimproved...SpentLimit is non-null. */
private boolean unimprovedTimeSpentLimitIsSet() {
return getUnimprovedDaysSpentLimit() != null
|| getUnimprovedHoursSpentLimit() != null
|| getUnimprovedMinutesSpentLimit() != null
|| getUnimprovedSecondsSpentLimit() != null
|| getUnimprovedMillisecondsSpentLimit() != null
|| getUnimprovedSpentLimit() != null;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/config/util/ConfigUtils.java | package ai.timefold.solver.core.config.util;
import static ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory.MemberAccessorType.FIELD_OR_READ_METHOD;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.domain.lookup.PlanningId;
import ai.timefold.solver.core.config.AbstractConfig;
import ai.timefold.solver.core.impl.domain.common.AlphabeticMemberComparator;
import ai.timefold.solver.core.impl.domain.common.ReflectionHelper;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory;
public class ConfigUtils {
private static final AlphabeticMemberComparator alphabeticMemberComparator = new AlphabeticMemberComparator();
/**
* Create a new instance of clazz from a config's property.
* <p>
* If the instantiation fails, the simple class name of {@code configBean} will be used as the owner of
* {@code propertyName}.
* <p>
* Intended usage:
*
* <pre>
* selectionFilter = ConfigUtils.newInstance(
* config, "filterClass", config.getFilterClass());
* </pre>
*
* @param configBean the bean holding the {@code clazz} to be instantiated
* @param propertyName {@code configBean}'s property holding {@code clazz}
* @param clazz {@code Class} representation of the type {@code T}
* @param <T> the new instance type
* @return new instance of clazz
*/
public static <T> T newInstance(Object configBean, String propertyName, Class<T> clazz) {
return ConfigUtils.newInstance(() -> (configBean == null ? "?" : configBean.getClass().getSimpleName()),
propertyName, clazz);
}
/**
* Create a new instance of clazz from a general source.
* <p>
* If the instantiation fails, the result of {@code ownerDescriptor} will be used to describe the owner of
* {@code propertyName}.
*
* @param ownerDescriptor describes the owner of {@code propertyName}
* @param propertyName property holding the {@code clazz}
* @param clazz {@code Class} representation of the type {@code T}
* @param <T> the new instance type
* @return new instance of clazz
*/
public static <T> T newInstance(Supplier<String> ownerDescriptor, String propertyName, Class<T> clazz) {
try {
return clazz.getDeclaredConstructor().newInstance();
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalArgumentException("The " + ownerDescriptor.get() + "'s " + propertyName + " ("
+ clazz.getName() + ") does not have a public no-arg constructor"
// Inner classes include local, anonymous and non-static member classes
+ ((clazz.isLocalClass() || clazz.isAnonymousClass() || clazz.isMemberClass())
&& !Modifier.isStatic(clazz.getModifiers()) ? " because it is an inner class." : "."),
e);
}
}
public static void applyCustomProperties(Object bean, String beanClassPropertyName,
Map<String, String> customProperties, String customPropertiesPropertyName) {
if (customProperties == null) {
return;
}
Class<?> beanClass = bean.getClass();
customProperties.forEach((propertyName, valueString) -> {
Method setterMethod = ReflectionHelper.getSetterMethod(beanClass, propertyName);
if (setterMethod == null) {
throw new IllegalStateException("The custom property " + propertyName + " (" + valueString
+ ") in the " + customPropertiesPropertyName
+ " cannot be set on the " + beanClassPropertyName + " (" + beanClass
+ ") because that class has no public setter for that property.\n"
+ "Maybe add a public setter for that custom property (" + propertyName
+ ") on that class (" + beanClass.getSimpleName() + ").\n"
+ "Maybe don't configure that custom property " + propertyName + " (" + valueString
+ ") in the " + customPropertiesPropertyName + ".");
}
Class<?> propertyType = setterMethod.getParameterTypes()[0];
Object typedValue;
try {
if (propertyType.equals(String.class)) {
typedValue = valueString;
} else if (propertyType.equals(Boolean.TYPE) || propertyType.equals(Boolean.class)) {
typedValue = Boolean.parseBoolean(valueString);
} else if (propertyType.equals(Integer.TYPE) || propertyType.equals(Integer.class)) {
typedValue = Integer.parseInt(valueString);
} else if (propertyType.equals(Long.TYPE) || propertyType.equals(Long.class)) {
typedValue = Long.parseLong(valueString);
} else if (propertyType.equals(Float.TYPE) || propertyType.equals(Float.class)) {
typedValue = Float.parseFloat(valueString);
} else if (propertyType.equals(Double.TYPE) || propertyType.equals(Double.class)) {
typedValue = Double.parseDouble(valueString);
} else if (propertyType.equals(BigDecimal.class)) {
typedValue = new BigDecimal(valueString);
} else if (propertyType.isEnum()) {
typedValue = Enum.valueOf((Class<? extends Enum>) propertyType, valueString);
} else {
throw new IllegalStateException("The custom property " + propertyName + " (" + valueString
+ ") in the " + customPropertiesPropertyName
+ " has an unsupported propertyType (" + propertyType + ") for value (" + valueString + ").");
}
} catch (NumberFormatException e) {
throw new IllegalStateException("The custom property " + propertyName + " (" + valueString
+ ") in the " + customPropertiesPropertyName
+ " cannot be parsed to the propertyType (" + propertyType
+ ") of the setterMethod (" + setterMethod + ").");
}
try {
setterMethod.invoke(bean, typedValue);
} catch (IllegalAccessException e) {
throw new IllegalStateException("The custom property " + propertyName + " (" + valueString
+ ") in the " + customPropertiesPropertyName
+ " has a setterMethod (" + setterMethod + ") on the beanClass (" + beanClass
+ ") that cannot be called for the typedValue (" + typedValue + ").", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("The custom property " + propertyName + " (" + valueString
+ ") in the " + customPropertiesPropertyName
+ " has a setterMethod (" + setterMethod + ") on the beanClass (" + beanClass
+ ") that throws an exception for the typedValue (" + typedValue + ").",
e.getCause());
}
});
}
public static <Config_ extends AbstractConfig<Config_>> Config_ inheritConfig(Config_ original, Config_ inherited) {
if (inherited != null) {
if (original == null) {
original = inherited.copyConfig();
} else {
original.inherit(inherited);
}
}
return original;
}
public static <Config_ extends AbstractConfig<Config_>> List<Config_> inheritMergeableListConfig(
List<Config_> originalList, List<Config_> inheritedList) {
if (inheritedList != null) {
List<Config_> mergedList = new ArrayList<>(inheritedList.size()
+ (originalList == null ? 0 : originalList.size()));
// The inheritedList should be before the originalList
for (Config_ inherited : inheritedList) {
Config_ copy = inherited.copyConfig();
mergedList.add(copy);
}
if (originalList != null) {
mergedList.addAll(originalList);
}
originalList = mergedList;
}
return originalList;
}
public static <T> T inheritOverwritableProperty(T original, T inherited) {
if (original != null) {
// Original overwrites inherited
return original;
} else {
return inherited;
}
}
public static <T> List<T> inheritMergeableListProperty(List<T> originalList, List<T> inheritedList) {
if (inheritedList == null) {
return originalList;
} else if (originalList == null) {
// Shallow clone due to modifications after calling inherit
return new ArrayList<>(inheritedList);
} else {
// The inheritedList should be before the originalList
List<T> mergedList = new ArrayList<>(inheritedList);
mergedList.addAll(originalList);
return mergedList;
}
}
public static <K, T> Map<K, T> inheritMergeableMapProperty(Map<K, T> originalMap, Map<K, T> inheritedMap) {
if (inheritedMap == null) {
return originalMap;
} else if (originalMap == null) {
return inheritedMap;
} else {
// The inheritedMap should be before the originalMap
Map<K, T> mergedMap = new LinkedHashMap<>(inheritedMap);
mergedMap.putAll(originalMap);
return mergedMap;
}
}
public static <T> T mergeProperty(T a, T b) {
return Objects.equals(a, b) ? a : null;
}
/**
* A relaxed version of {@link #mergeProperty(Object, Object)}. Used primarily for merging failed benchmarks,
* where a property remains the same over benchmark runs (for example: dataset problem size), but the property in
* the failed benchmark isn't initialized, therefore null. When merging, we can still use the correctly initialized
* property of the benchmark that didn't fail.
* <p>
* Null-handling:
* <ul>
* <li>if <strong>both</strong> properties <strong>are null</strong>, returns null</li>
* <li>if <strong>only one</strong> of the properties <strong>is not null</strong>, returns that property</li>
* <li>if <strong>both</strong> properties <strong>are not null</strong>, returns
* {@link #mergeProperty(Object, Object)}</li>
* </ul>
*
* @see #mergeProperty(Object, Object)
* @param a property {@code a}
* @param b property {@code b}
* @param <T> the type of property {@code a} and {@code b}
* @return sometimes null
*/
public static <T> T meldProperty(T a, T b) {
if (a == null && b == null) {
return null;
}
if (a == null) {
return b;
}
if (b == null) {
return a;
}
return ConfigUtils.mergeProperty(a, b);
}
public static boolean isEmptyCollection(Collection<?> collection) {
return collection == null || collection.isEmpty();
}
/**
* Divides and ceils the result without using floating point arithmetic. For floor division,
* see {@link Math#floorDiv(long, long)}.
*
* @throws ArithmeticException if {@code divisor == 0}
* @param dividend the dividend
* @param divisor the divisor
* @return dividend / divisor, ceiled
*/
public static int ceilDivide(int dividend, int divisor) {
if (divisor == 0) {
throw new ArithmeticException("Cannot divide by zero: " + dividend + "/" + divisor);
}
int correction;
if (dividend % divisor == 0) {
correction = 0;
} else if (Integer.signum(dividend) * Integer.signum(divisor) < 0) {
correction = 0;
} else {
correction = 1;
}
return (dividend / divisor) + correction;
}
public static int resolvePoolSize(String propertyName, String value, String... magicValues) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException ex) {
throw new IllegalStateException("The " + propertyName + " (" + value + ") resolved to neither of ("
+ Arrays.toString(magicValues) + ") nor a number.");
}
}
// ************************************************************************
// Member and annotation methods
// ************************************************************************
public static List<Class<?>> getAllAnnotatedLineageClasses(Class<?> bottomClass,
Class<? extends Annotation> annotation) {
if (!bottomClass.isAnnotationPresent(annotation)) {
return Collections.emptyList();
}
List<Class<?>> lineageClassList = new ArrayList<>();
lineageClassList.add(bottomClass);
Class<?> superclass = bottomClass.getSuperclass();
lineageClassList.addAll(getAllAnnotatedLineageClasses(superclass, annotation));
for (Class<?> superInterface : bottomClass.getInterfaces()) {
lineageClassList.addAll(getAllAnnotatedLineageClasses(superInterface, annotation));
}
return lineageClassList;
}
/**
* @param baseClass never null
* @return never null, sorted by type (fields before methods), then by {@link AlphabeticMemberComparator}.
*/
public static List<Member> getDeclaredMembers(Class<?> baseClass) {
Stream<Field> fieldStream = Stream.of(baseClass.getDeclaredFields())
// A synthetic field is a field generated by the compiler that
// does not exist in the source code. It is used mainly in
// nested classes so the inner class can access the fields
// of the outer class.
.filter(field -> !field.isSynthetic())
.sorted(alphabeticMemberComparator);
Stream<Method> methodStream = Stream.of(baseClass.getDeclaredMethods())
// A synthetic method is a method generated by the compiler that does
// not exist in the source code. These include bridge methods.
// A bridge method is a generic variant that duplicates a concrete method
// Example: "Score getScore()" that duplicates "HardSoftScore getScore()"
.filter(method -> !method.isSynthetic())
.sorted(alphabeticMemberComparator);
return Stream.concat(fieldStream, methodStream)
.collect(Collectors.toList());
}
/**
* @param baseClass never null
* @param annotationClass never null
* @return never null, sorted by type (fields before methods), then by {@link AlphabeticMemberComparator}.
*/
public static List<Member> getAllMembers(Class<?> baseClass, Class<? extends Annotation> annotationClass) {
Class<?> clazz = baseClass;
Stream<Member> memberStream = Stream.empty();
while (clazz != null) {
Stream<Field> fieldStream = Stream.of(clazz.getDeclaredFields())
.filter(field -> field.isAnnotationPresent(annotationClass) && !field.isSynthetic())
.sorted(alphabeticMemberComparator);
Stream<Method> methodStream = Stream.of(clazz.getDeclaredMethods())
.filter(method -> method.isAnnotationPresent(annotationClass) && !method.isSynthetic())
.sorted(alphabeticMemberComparator);
memberStream = Stream.concat(memberStream, Stream.concat(fieldStream, methodStream));
clazz = clazz.getSuperclass();
}
return memberStream.collect(Collectors.toList());
}
@SafeVarargs
public static Class<? extends Annotation> extractAnnotationClass(Member member,
Class<? extends Annotation>... annotationClasses) {
Class<? extends Annotation> annotationClass = null;
for (Class<? extends Annotation> detectedAnnotationClass : annotationClasses) {
if (((AnnotatedElement) member).isAnnotationPresent(detectedAnnotationClass)) {
if (annotationClass != null) {
throw new IllegalStateException("The class (" + member.getDeclaringClass()
+ ") has a member (" + member + ") that has both a @"
+ annotationClass.getSimpleName() + " annotation and a @"
+ detectedAnnotationClass.getSimpleName() + " annotation.");
}
annotationClass = detectedAnnotationClass;
// Do not break early: check other annotationClasses too
}
}
return annotationClass;
}
public static Class<?> extractCollectionGenericTypeParameterStrictly(
String parentClassConcept, Class<?> parentClass,
Class<?> type, Type genericType,
Class<? extends Annotation> annotationClass, String memberName) {
return extractCollectionGenericTypeParameter(
parentClassConcept, parentClass,
type, genericType,
annotationClass, memberName).orElseThrow(
() -> new IllegalArgumentException("The " + parentClassConcept + " (" + parentClass + ") has a "
+ (annotationClass == null ? "auto discovered"
: "@" + annotationClass.getSimpleName() + " annotated")
+ " member (" + memberName
+ ") with a member type (" + type
+ ") which has no generic parameters.\n"
+ "Maybe the member (" + memberName + ") should return a parameterized "
+ type.getSimpleName()
+ "."));
}
public static Optional<Class<?>> extractCollectionGenericTypeParameterLeniently(
String parentClassConcept, Class<?> parentClass,
Class<?> type, Type genericType,
Class<? extends Annotation> annotationClass, String memberName) {
return extractCollectionGenericTypeParameter(
parentClassConcept, parentClass,
type, genericType,
annotationClass, memberName);
}
private static Optional<Class<?>> extractCollectionGenericTypeParameter(
String parentClassConcept, Class<?> parentClass,
Class<?> type, Type genericType,
Class<? extends Annotation> annotationClass, String memberName) {
if (!(genericType instanceof ParameterizedType)) {
return Optional.empty();
}
ParameterizedType parameterizedType = (ParameterizedType) genericType;
Type[] typeArguments = parameterizedType.getActualTypeArguments();
if (typeArguments.length != 1) {
throw new IllegalArgumentException("The " + parentClassConcept + " (" + parentClass + ") has a "
+ (annotationClass == null ? "auto discovered" : "@" + annotationClass.getSimpleName() + " annotated")
+ " member (" + memberName
+ ") with a member type (" + type
+ ") which is a parameterized collection with an unsupported number of generic parameters ("
+ typeArguments.length + ").");
}
Type typeArgument = typeArguments[0];
if (typeArgument instanceof ParameterizedType parameterizedType1) {
// Remove the type parameters so it can be cast to a Class
typeArgument = parameterizedType1.getRawType();
}
if (typeArgument instanceof WildcardType wildcardType) {
Type[] upperBounds = wildcardType.getUpperBounds();
if (upperBounds.length > 1) {
// Multiple upper bounds is impossible in traditional Java
// Other JVM languages or future java versions might enabling triggering this
throw new IllegalArgumentException("The " + parentClassConcept + " (" + parentClass + ") has a "
+ (annotationClass == null ? "auto discovered" : "@" + annotationClass.getSimpleName() + " annotated")
+ " member (" + memberName
+ ") with a member type (" + type
+ ") which is a parameterized collection with a wildcard type argument ("
+ typeArgument + ") that has multiple upper bounds (" + Arrays.toString(upperBounds) + ").\n"
+ "Maybe don't use wildcards with multiple upper bounds for the member (" + memberName + ").");
}
if (upperBounds.length == 0) {
typeArgument = Object.class;
} else {
typeArgument = upperBounds[0];
}
}
if (typeArgument instanceof Class class1) {
return Optional.of(class1);
} else if (typeArgument instanceof ParameterizedType parameterizedType1) {
// Turns SomeGenericType<T> into SomeGenericType.
return Optional.of((Class<?>) parameterizedType1.getRawType());
} else {
throw new IllegalArgumentException("The " + parentClassConcept + " (" + parentClass + ") has a "
+ (annotationClass == null ? "auto discovered" : "@" + annotationClass.getSimpleName() + " annotated")
+ " member (" + memberName
+ ") with a member type (" + type
+ ") which is a parameterized collection with a type argument (" + typeArgument
+ ") that is not a class or interface.");
}
}
/**
* This method is heavy, and it is effectively a computed constant.
* It is recommended that its results are cached at call sites.
*
* @param clazz never null
* @param memberAccessorFactory never null
* @param domainAccessType never null
* @return null if no accessor found
* @param <C> the class type
*/
public static <C> MemberAccessor findPlanningIdMemberAccessor(Class<C> clazz,
MemberAccessorFactory memberAccessorFactory, DomainAccessType domainAccessType) {
Member member = getSingleMember(clazz, PlanningId.class);
if (member == null) {
return null;
}
MemberAccessor memberAccessor =
memberAccessorFactory.buildAndCacheMemberAccessor(member, FIELD_OR_READ_METHOD, PlanningId.class,
domainAccessType);
assertPlanningIdMemberIsComparable(clazz, member, memberAccessor);
return memberAccessor;
}
private static void assertPlanningIdMemberIsComparable(Class<?> clazz, Member member, MemberAccessor memberAccessor) {
if (!memberAccessor.getType().isPrimitive() && !Comparable.class.isAssignableFrom(memberAccessor.getType())) {
throw new IllegalArgumentException("The class (" + clazz
+ ") has a member (" + member + ") with a @" + PlanningId.class.getSimpleName()
+ " annotation that returns a type (" + memberAccessor.getType()
+ ") that does not implement " + Comparable.class.getSimpleName() + ".\n"
+ "Maybe use a " + Long.class.getSimpleName()
+ " or " + String.class.getSimpleName() + " type instead.");
}
}
private static <C> Member getSingleMember(Class<C> clazz, Class<? extends Annotation> annotationClass) {
List<Member> memberList = getAllMembers(clazz, annotationClass);
if (memberList.isEmpty()) {
return null;
}
int size = memberList.size();
if (clazz.isRecord()) {
/*
* A record has a field and a getter for each record component.
* When the component is annotated with @PlanningId,
* the annotation ends up both on the field and on the getter.
*/
if (size == 2) { // The getter is used to retrieve the value of the record component.
var methodMembers = getMembers(memberList, true);
if (methodMembers.isEmpty()) {
throw new IllegalStateException("Impossible state: record (%s) doesn't have any method members (%s)."
.formatted(clazz.getCanonicalName(), memberList));
}
return methodMembers.get(0);
} else { // There is more than one component annotated with @PlanningId; take the fields and fail.
var componentList = getMembers(memberList, false)
.stream()
.map(Member::getName)
.toList();
throw new IllegalArgumentException("The record (%s) has %s components (%s) with %s annotation."
.formatted(clazz, componentList.size(), componentList, annotationClass.getSimpleName()));
}
} else if (size > 1) {
throw new IllegalArgumentException("The class (%s) has %s members (%s) with %s annotation."
.formatted(clazz, memberList.size(), memberList, annotationClass.getSimpleName()));
}
return memberList.get(0);
}
private static List<Member> getMembers(List<Member> memberList, boolean needMethod) {
var filteredMemberList = new ArrayList<Member>(memberList.size());
for (var member : memberList) {
if (member instanceof Method && needMethod) {
filteredMemberList.add(member);
} else if (member instanceof Field && !needMethod) {
filteredMemberList.add(member);
}
}
return filteredMemberList;
}
public static String abbreviate(List<String> list, int limit) {
String abbreviation = "";
if (list != null) {
abbreviation = list.stream().limit(limit).collect(Collectors.joining(", "));
if (list.size() > limit) {
abbreviation += ", ...";
}
}
return abbreviation;
}
public static String abbreviate(List<String> list) {
return abbreviate(list, 3);
}
public static boolean isNativeImage() {
return System.getProperty("org.graalvm.nativeimage.imagecode") != null;
}
// ************************************************************************
// Private constructor
// ************************************************************************
private ConfigUtils() {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/enterprise/TimefoldSolverEnterpriseService.java | package ai.timefold.solver.core.enterprise;
import java.util.ServiceLoader;
import java.util.function.BiFunction;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.api.solver.SolverFactory;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
import ai.timefold.solver.core.config.heuristic.selector.common.nearby.NearbySelectionConfig;
import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.list.DestinationSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.list.SubListSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig;
import ai.timefold.solver.core.config.partitionedsearch.PartitionedSearchPhaseConfig;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
import ai.timefold.solver.core.impl.constructionheuristic.decider.ConstructionHeuristicDecider;
import ai.timefold.solver.core.impl.constructionheuristic.decider.forager.ConstructionHeuristicForager;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.list.DestinationSelector;
import ai.timefold.solver.core.impl.heuristic.selector.list.ElementDestinationSelector;
import ai.timefold.solver.core.impl.heuristic.selector.list.RandomSubListSelector;
import ai.timefold.solver.core.impl.heuristic.selector.list.SubListSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
import ai.timefold.solver.core.impl.localsearch.decider.LocalSearchDecider;
import ai.timefold.solver.core.impl.localsearch.decider.acceptor.Acceptor;
import ai.timefold.solver.core.impl.localsearch.decider.forager.LocalSearchForager;
import ai.timefold.solver.core.impl.partitionedsearch.PartitionedSearchPhase;
import ai.timefold.solver.core.impl.solver.termination.Termination;
public interface TimefoldSolverEnterpriseService {
static String identifySolverVersion() {
var packaging = TimefoldSolverEnterpriseService.load() == null ? "Community Edition" : "Enterprise Edition";
var version = SolverFactory.class.getPackage().getImplementationVersion();
return packaging + " " + (version == null ? "(Development snapshot)" : "v" + version);
}
static TimefoldSolverEnterpriseService load() {
var serviceLoader = ServiceLoader.load(TimefoldSolverEnterpriseService.class);
var iterator = serviceLoader.iterator();
return iterator.hasNext() ? iterator.next() : null;
}
static TimefoldSolverEnterpriseService loadOrFail(Feature feature) {
var service = load();
if (service == null) {
throw new IllegalStateException("""
%s requested but Timefold Solver Enterprise Edition not found on classpath
Either add the ai.timefold.solver.enterprise:timefold-solver-enterprise-core dependency,
or %s.
"Note: Timefold Solver Enterprise Edition is a commercial product."""
.formatted(feature.getName(), feature.getWorkaround()));
}
return service;
}
Class<? extends ConstraintProvider>
buildLambdaSharedConstraintProvider(Class<? extends ConstraintProvider> originalConstraintProvider);
<Solution_> ConstructionHeuristicDecider<Solution_> buildConstructionHeuristic(int moveThreadCount,
Termination<Solution_> termination, ConstructionHeuristicForager<Solution_> forager,
EnvironmentMode environmentMode, HeuristicConfigPolicy<Solution_> configPolicy);
<Solution_> LocalSearchDecider<Solution_> buildLocalSearch(int moveThreadCount, Termination<Solution_> termination,
MoveSelector<Solution_> moveSelector, Acceptor<Solution_> acceptor, LocalSearchForager<Solution_> forager,
EnvironmentMode environmentMode, HeuristicConfigPolicy<Solution_> configPolicy);
<Solution_> PartitionedSearchPhase<Solution_> buildPartitionedSearch(int phaseIndex,
PartitionedSearchPhaseConfig phaseConfig, HeuristicConfigPolicy<Solution_> solverConfigPolicy,
Termination<Solution_> solverTermination,
BiFunction<HeuristicConfigPolicy<Solution_>, Termination<Solution_>, Termination<Solution_>> phaseTerminationFunction);
<Solution_> EntitySelector<Solution_> applyNearbySelection(EntitySelectorConfig entitySelectorConfig,
HeuristicConfigPolicy<Solution_> configPolicy, NearbySelectionConfig nearbySelectionConfig,
SelectionCacheType minimumCacheType, SelectionOrder resolvedSelectionOrder,
EntitySelector<Solution_> entitySelector);
<Solution_> ValueSelector<Solution_> applyNearbySelection(ValueSelectorConfig valueSelectorConfig,
HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor,
SelectionCacheType minimumCacheType, SelectionOrder resolvedSelectionOrder, ValueSelector<Solution_> valueSelector);
<Solution_> SubListSelector<Solution_> applyNearbySelection(SubListSelectorConfig subListSelectorConfig,
HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType,
SelectionOrder resolvedSelectionOrder, RandomSubListSelector<Solution_> subListSelector);
<Solution_> DestinationSelector<Solution_> applyNearbySelection(DestinationSelectorConfig destinationSelectorConfig,
HeuristicConfigPolicy<Solution_> configPolicy, SelectionCacheType minimumCacheType,
SelectionOrder resolvedSelectionOrder, ElementDestinationSelector<Solution_> destinationSelector);
enum Feature {
MULTITHREADED_SOLVING("Multi-threaded solving", "remove moveThreadCount from solver configuration"),
PARTITIONED_SEARCH("Partitioned search", "remove partitioned search phase from solver configuration"),
NEARBY_SELECTION("Nearby selection", "remove nearby selection from solver configuration"),
AUTOMATIC_NODE_SHARING("Automatic node sharing",
"remove automatic node sharing from solver configuration");
private final String name;
private final String workaround;
Feature(String name, String workaround) {
this.name = name;
this.workaround = workaround;
}
public String getName() {
return name;
}
public String getWorkaround() {
return workaround;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/AbstractFromConfigFactory.java | package ai.timefold.solver.core.impl;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.config.AbstractConfig;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig;
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.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
public abstract class AbstractFromConfigFactory<Solution_, Config_ extends AbstractConfig<Config_>> {
protected final Config_ config;
public AbstractFromConfigFactory(Config_ config) {
this.config = config;
}
public static <Solution_> EntitySelectorConfig getDefaultEntitySelectorConfigForEntity(
HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor) {
Class<?> entityClass = entityDescriptor.getEntityClass();
EntitySelectorConfig entitySelectorConfig = new EntitySelectorConfig()
.withId(entityClass.getName())
.withEntityClass(entityClass);
if (EntitySelectorConfig.hasSorter(configPolicy.getEntitySorterManner(), entityDescriptor)) {
entitySelectorConfig = entitySelectorConfig.withCacheType(SelectionCacheType.PHASE)
.withSelectionOrder(SelectionOrder.SORTED)
.withSorterManner(configPolicy.getEntitySorterManner());
}
return entitySelectorConfig;
}
protected EntityDescriptor<Solution_> deduceEntityDescriptor(HeuristicConfigPolicy<Solution_> configPolicy,
Class<?> entityClass) {
SolutionDescriptor<Solution_> solutionDescriptor = configPolicy.getSolutionDescriptor();
return entityClass == null
? getTheOnlyEntityDescriptor(solutionDescriptor)
: getEntityDescriptorForClass(solutionDescriptor, entityClass);
}
private EntityDescriptor<Solution_> getEntityDescriptorForClass(SolutionDescriptor<Solution_> solutionDescriptor,
Class<?> entityClass) {
EntityDescriptor<Solution_> entityDescriptor = solutionDescriptor.getEntityDescriptorStrict(entityClass);
if (entityDescriptor == null) {
throw new IllegalArgumentException("The config (" + config
+ ") has an entityClass (" + entityClass + ") that is not a known planning entity.\n"
+ "Check your solver configuration. If that class (" + entityClass.getSimpleName()
+ ") is not in the entityClassSet (" + solutionDescriptor.getEntityClassSet()
+ "), check your @" + PlanningSolution.class.getSimpleName()
+ " implementation's annotated methods too.");
}
return entityDescriptor;
}
protected EntityDescriptor<Solution_> getTheOnlyEntityDescriptor(SolutionDescriptor<Solution_> solutionDescriptor) {
Collection<EntityDescriptor<Solution_>> entityDescriptors = solutionDescriptor.getGenuineEntityDescriptors();
if (entityDescriptors.size() != 1) {
throw new IllegalArgumentException("The config (" + config
+ ") has no entityClass configured and because there are multiple in the entityClassSet ("
+ solutionDescriptor.getEntityClassSet()
+ "), it cannot be deduced automatically.");
}
return entityDescriptors.iterator().next();
}
protected GenuineVariableDescriptor<Solution_> deduceGenuineVariableDescriptor(EntityDescriptor<Solution_> entityDescriptor,
String variableName) {
return variableName == null
? getTheOnlyVariableDescriptor(entityDescriptor)
: getVariableDescriptorForName(entityDescriptor, variableName);
}
protected GenuineVariableDescriptor<Solution_> getVariableDescriptorForName(EntityDescriptor<Solution_> entityDescriptor,
String variableName) {
GenuineVariableDescriptor<Solution_> variableDescriptor = entityDescriptor.getGenuineVariableDescriptor(variableName);
if (variableDescriptor == null) {
throw new IllegalArgumentException("The config (" + config
+ ") has a variableName (" + variableName
+ ") which is not a valid planning variable on entityClass ("
+ entityDescriptor.getEntityClass() + ").\n"
+ entityDescriptor.buildInvalidVariableNameExceptionMessage(variableName));
}
return variableDescriptor;
}
protected GenuineVariableDescriptor<Solution_> getTheOnlyVariableDescriptor(EntityDescriptor<Solution_> entityDescriptor) {
List<GenuineVariableDescriptor<Solution_>> variableDescriptorList =
entityDescriptor.getGenuineVariableDescriptorList();
if (variableDescriptorList.size() != 1) {
throw new IllegalArgumentException("The config (" + config
+ ") has no configured variableName for entityClass (" + entityDescriptor.getEntityClass()
+ ") and because there are multiple variableNames ("
+ entityDescriptor.getGenuineVariableNameSet()
+ "), it cannot be deduced automatically.");
}
return variableDescriptorList.iterator().next();
}
protected List<GenuineVariableDescriptor<Solution_>> deduceVariableDescriptorList(
EntityDescriptor<Solution_> entityDescriptor, List<String> variableNameIncludeList) {
Objects.requireNonNull(entityDescriptor);
List<GenuineVariableDescriptor<Solution_>> variableDescriptorList =
entityDescriptor.getGenuineVariableDescriptorList();
if (variableNameIncludeList == null) {
return variableDescriptorList;
}
return variableNameIncludeList.stream()
.map(variableNameInclude -> variableDescriptorList.stream()
.filter(variableDescriptor -> variableDescriptor.getVariableName().equals(variableNameInclude))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("The config (" + config
+ ") has a variableNameInclude (" + variableNameInclude
+ ") which does not exist in the entity (" + entityDescriptor.getEntityClass()
+ ")'s variableDescriptorList (" + variableDescriptorList + ").")))
.collect(Collectors.toList());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/package-info.java | /**
* Implementation classes of Timefold.
* <p>
* All classes in this namespace are NOT backwards compatible: they might change in future releases
* (including hotfix releases). All relevant changes are documented in
* <a href="https://timefold.ai/docs/">the upgrade recipe</a>.
*/
package ai.timefold.solver.core.impl;
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/ConstructionHeuristicPhase.java | package ai.timefold.solver.core.impl.constructionheuristic;
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 ConstructionHeuristicPhase} is a {@link Phase} which uses a construction heuristic algorithm,
* such as First Fit, First Fit Decreasing, Cheapest Insertion, ...
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @see Phase
* @see AbstractPhase
* @see DefaultConstructionHeuristicPhase
*/
public interface ConstructionHeuristicPhase<Solution_> extends Phase<Solution_> {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/DefaultConstructionHeuristicPhase.java | package ai.timefold.solver.core.impl.constructionheuristic;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.constructionheuristic.decider.ConstructionHeuristicDecider;
import ai.timefold.solver.core.impl.constructionheuristic.placer.EntityPlacer;
import ai.timefold.solver.core.impl.constructionheuristic.placer.Placement;
import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicPhaseScope;
import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicStepScope;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.phase.AbstractPhase;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.termination.Termination;
/**
* Default implementation of {@link ConstructionHeuristicPhase}.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class DefaultConstructionHeuristicPhase<Solution_> extends AbstractPhase<Solution_>
implements ConstructionHeuristicPhase<Solution_> {
protected final EntityPlacer<Solution_> entityPlacer;
protected final ConstructionHeuristicDecider<Solution_> decider;
private DefaultConstructionHeuristicPhase(Builder<Solution_> builder) {
super(builder);
entityPlacer = builder.entityPlacer;
decider = builder.decider;
}
public EntityPlacer<Solution_> getEntityPlacer() {
return entityPlacer;
}
@Override
public String getPhaseTypeString() {
return "Construction Heuristics";
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void solve(SolverScope<Solution_> solverScope) {
ConstructionHeuristicPhaseScope<Solution_> phaseScope = new ConstructionHeuristicPhaseScope<>(solverScope);
phaseStarted(phaseScope);
// In case of list variable with support for unassigned values, the placer will iterate indefinitely.
// (When it exhausts all values, it will start over from the beginning.)
// To prevent that, we need to limit the number of steps to the number of unassigned values.
var solutionDescriptor = solverScope.getSolutionDescriptor();
var listVariableDescriptor = solutionDescriptor.getListVariableDescriptor();
var supportsUnassignedValues = listVariableDescriptor != null && listVariableDescriptor.allowsUnassignedValues();
var maxStepCount = -1;
if (supportsUnassignedValues) {
var workingSolution = phaseScope.getWorkingSolution();
maxStepCount = listVariableDescriptor.countUnassigned(workingSolution);
}
for (Placement<Solution_> placement : entityPlacer) {
ConstructionHeuristicStepScope<Solution_> stepScope = new ConstructionHeuristicStepScope<>(phaseScope);
stepStarted(stepScope);
decider.decideNextStep(stepScope, placement);
if (stepScope.getStep() == null) {
if (phaseTermination.isPhaseTerminated(phaseScope)) {
logger.trace("{} Step index ({}), time spent ({}) terminated without picking a nextStep.",
logIndentation,
stepScope.getStepIndex(),
stepScope.getPhaseScope().calculateSolverTimeMillisSpentUpToNow());
} else if (stepScope.getSelectedMoveCount() == 0L) {
logger.warn("{} No doable selected move at step index ({}), time spent ({})."
+ " Terminating phase early.",
logIndentation,
stepScope.getStepIndex(),
stepScope.getPhaseScope().calculateSolverTimeMillisSpentUpToNow());
} else {
throw new IllegalStateException("The step index (" + stepScope.getStepIndex()
+ ") has selected move count (" + stepScope.getSelectedMoveCount()
+ ") but failed to pick a nextStep (" + stepScope.getStep() + ").");
}
// Although stepStarted has been called, stepEnded is not called for this step
break;
}
doStep(stepScope);
stepEnded(stepScope);
phaseScope.setLastCompletedStepScope(stepScope);
if (phaseTermination.isPhaseTerminated(phaseScope)
|| (supportsUnassignedValues && stepScope.getStepIndex() >= maxStepCount)) {
break;
}
}
phaseEnded(phaseScope);
}
private void doStep(ConstructionHeuristicStepScope<Solution_> stepScope) {
Move<Solution_> step = stepScope.getStep();
step.doMoveOnly(stepScope.getScoreDirector());
predictWorkingStepScore(stepScope, step);
solver.getBestSolutionRecaller().processWorkingSolutionDuringConstructionHeuristicsStep(stepScope);
}
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
super.solvingStarted(solverScope);
entityPlacer.solvingStarted(solverScope);
decider.solvingStarted(solverScope);
}
public void phaseStarted(ConstructionHeuristicPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
entityPlacer.phaseStarted(phaseScope);
decider.phaseStarted(phaseScope);
}
public void stepStarted(ConstructionHeuristicStepScope<Solution_> stepScope) {
super.stepStarted(stepScope);
entityPlacer.stepStarted(stepScope);
decider.stepStarted(stepScope);
}
public void stepEnded(ConstructionHeuristicStepScope<Solution_> stepScope) {
super.stepEnded(stepScope);
entityPlacer.stepEnded(stepScope);
decider.stepEnded(stepScope);
if (logger.isDebugEnabled()) {
long timeMillisSpent = stepScope.getPhaseScope().calculateSolverTimeMillisSpentUpToNow();
logger.debug("{} CH step ({}), time spent ({}), score ({}), selected move count ({}),"
+ " picked move ({}).",
logIndentation,
stepScope.getStepIndex(), timeMillisSpent,
stepScope.getScore(),
stepScope.getSelectedMoveCount(),
stepScope.getStepString());
}
}
public void phaseEnded(ConstructionHeuristicPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
// Only update the best solution if the CH made any change.
if (!phaseScope.getStartingScore().equals(phaseScope.getBestScore())) {
solver.getBestSolutionRecaller().updateBestSolutionAndFire(phaseScope.getSolverScope());
}
entityPlacer.phaseEnded(phaseScope);
decider.phaseEnded(phaseScope);
phaseScope.endingNow();
logger.info("{}Construction Heuristic phase ({}) ended: time spent ({}), best score ({}),"
+ " score calculation speed ({}/sec), step total ({}).",
logIndentation,
phaseIndex,
phaseScope.calculateSolverTimeMillisSpentUpToNow(),
phaseScope.getBestScore(),
phaseScope.getPhaseScoreCalculationSpeed(),
phaseScope.getNextStepIndex());
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
super.solvingEnded(solverScope);
entityPlacer.solvingEnded(solverScope);
decider.solvingEnded(solverScope);
}
@Override
public void solvingError(SolverScope<Solution_> solverScope, Exception exception) {
super.solvingError(solverScope, exception);
decider.solvingError(solverScope, exception);
}
public static class Builder<Solution_> extends AbstractPhase.Builder<Solution_> {
private final EntityPlacer<Solution_> entityPlacer;
private final ConstructionHeuristicDecider<Solution_> decider;
public Builder(int phaseIndex, String logIndentation, Termination<Solution_> phaseTermination,
EntityPlacer<Solution_> entityPlacer, ConstructionHeuristicDecider<Solution_> decider) {
super(phaseIndex, logIndentation, phaseTermination);
this.entityPlacer = entityPlacer;
this.decider = decider;
}
@Override
public DefaultConstructionHeuristicPhase<Solution_> build() {
return new DefaultConstructionHeuristicPhase<>(this);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/DefaultConstructionHeuristicPhaseFactory.java | package ai.timefold.solver.core.impl.constructionheuristic;
import java.util.Objects;
import java.util.Optional;
import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig;
import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicType;
import ai.timefold.solver.core.config.constructionheuristic.decider.forager.ConstructionHeuristicForagerConfig;
import ai.timefold.solver.core.config.constructionheuristic.placer.EntityPlacerConfig;
import ai.timefold.solver.core.config.constructionheuristic.placer.PooledEntityPlacerConfig;
import ai.timefold.solver.core.config.constructionheuristic.placer.QueuedEntityPlacerConfig;
import ai.timefold.solver.core.config.constructionheuristic.placer.QueuedValuePlacerConfig;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySorterManner;
import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.composite.CartesianProductMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.value.ValueSorterManner;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.enterprise.TimefoldSolverEnterpriseService;
import ai.timefold.solver.core.impl.constructionheuristic.decider.ConstructionHeuristicDecider;
import ai.timefold.solver.core.impl.constructionheuristic.decider.forager.ConstructionHeuristicForager;
import ai.timefold.solver.core.impl.constructionheuristic.decider.forager.ConstructionHeuristicForagerFactory;
import ai.timefold.solver.core.impl.constructionheuristic.placer.EntityPlacer;
import ai.timefold.solver.core.impl.constructionheuristic.placer.EntityPlacerFactory;
import ai.timefold.solver.core.impl.constructionheuristic.placer.PooledEntityPlacerFactory;
import ai.timefold.solver.core.impl.constructionheuristic.placer.QueuedEntityPlacerFactory;
import ai.timefold.solver.core.impl.constructionheuristic.placer.QueuedValuePlacerFactory;
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.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.Termination;
public class DefaultConstructionHeuristicPhaseFactory<Solution_>
extends AbstractPhaseFactory<Solution_, ConstructionHeuristicPhaseConfig> {
public DefaultConstructionHeuristicPhaseFactory(ConstructionHeuristicPhaseConfig phaseConfig) {
super(phaseConfig);
}
@Override
public ConstructionHeuristicPhase<Solution_> buildPhase(int phaseIndex, HeuristicConfigPolicy<Solution_> solverConfigPolicy,
BestSolutionRecaller<Solution_> bestSolutionRecaller, Termination<Solution_> solverTermination) {
ConstructionHeuristicType constructionHeuristicType_ = Objects.requireNonNullElse(
phaseConfig.getConstructionHeuristicType(),
ConstructionHeuristicType.ALLOCATE_ENTITY_FROM_QUEUE);
EntitySorterManner entitySorterManner = Objects.requireNonNullElse(
phaseConfig.getEntitySorterManner(),
constructionHeuristicType_.getDefaultEntitySorterManner());
ValueSorterManner valueSorterManner = Objects.requireNonNullElse(
phaseConfig.getValueSorterManner(),
constructionHeuristicType_.getDefaultValueSorterManner());
HeuristicConfigPolicy<Solution_> phaseConfigPolicy = solverConfigPolicy.cloneBuilder()
.withReinitializeVariableFilterEnabled(true)
.withInitializedChainedValueFilterEnabled(true)
.withUnassignedValuesAllowed(true)
.withEntitySorterManner(entitySorterManner)
.withValueSorterManner(valueSorterManner)
.build();
Termination<Solution_> phaseTermination = buildPhaseTermination(phaseConfigPolicy, solverTermination);
EntityPlacerConfig entityPlacerConfig_ = getValidEntityPlacerConfig()
.orElseGet(() -> buildDefaultEntityPlacerConfig(phaseConfigPolicy, constructionHeuristicType_));
EntityPlacer<Solution_> entityPlacer = EntityPlacerFactory.<Solution_> create(entityPlacerConfig_)
.buildEntityPlacer(phaseConfigPolicy);
DefaultConstructionHeuristicPhase.Builder<Solution_> builder = new DefaultConstructionHeuristicPhase.Builder<>(
phaseIndex,
solverConfigPolicy.getLogIndentation(),
phaseTermination,
entityPlacer,
buildDecider(phaseConfigPolicy, phaseTermination));
EnvironmentMode environmentMode = phaseConfigPolicy.getEnvironmentMode();
if (environmentMode.isNonIntrusiveFullAsserted()) {
builder.setAssertStepScoreFromScratch(true);
}
if (environmentMode.isIntrusiveFastAsserted()) {
builder.setAssertExpectedStepScore(true);
builder.setAssertShadowVariablesAreNotStaleAfterStep(true);
}
return builder.build();
}
private Optional<EntityPlacerConfig> getValidEntityPlacerConfig() {
EntityPlacerConfig entityPlacerConfig = phaseConfig.getEntityPlacerConfig();
if (entityPlacerConfig == null) {
return Optional.empty();
}
if (phaseConfig.getConstructionHeuristicType() != null) {
throw new IllegalArgumentException(
"The constructionHeuristicType (" + phaseConfig.getConstructionHeuristicType()
+ ") must not be configured if the entityPlacerConfig (" + entityPlacerConfig
+ ") is explicitly configured.");
}
if (phaseConfig.getMoveSelectorConfigList() != null) {
throw new IllegalArgumentException("The moveSelectorConfigList (" + phaseConfig.getMoveSelectorConfigList()
+ ") cannot be configured if the entityPlacerConfig (" + entityPlacerConfig
+ ") is explicitly configured.");
}
return Optional.of(entityPlacerConfig);
}
private EntityPlacerConfig buildDefaultEntityPlacerConfig(HeuristicConfigPolicy<Solution_> configPolicy,
ConstructionHeuristicType constructionHeuristicType) {
return findValidListVariableDescriptor(configPolicy.getSolutionDescriptor())
.map(listVariableDescriptor -> buildListVariableQueuedValuePlacerConfig(configPolicy, listVariableDescriptor))
.orElseGet(() -> buildUnfoldedEntityPlacerConfig(configPolicy, constructionHeuristicType));
}
private Optional<ListVariableDescriptor<?>>
findValidListVariableDescriptor(SolutionDescriptor<Solution_> solutionDescriptor) {
var listVariableDescriptor = solutionDescriptor.getListVariableDescriptor();
if (listVariableDescriptor == null) {
return Optional.empty();
}
failIfConfigured(phaseConfig.getConstructionHeuristicType(), "constructionHeuristicType");
failIfConfigured(phaseConfig.getEntityPlacerConfig(), "entityPlacerConfig");
failIfConfigured(phaseConfig.getMoveSelectorConfigList(), "moveSelectorConfigList");
return Optional.of(listVariableDescriptor);
}
private static void failIfConfigured(Object configValue, String configName) {
if (configValue != null) {
throw new IllegalArgumentException("Construction Heuristic phase with a list variable does not support "
+ configName + " configuration. Remove the " + configName + " (" + configValue + ") from the config.");
}
}
public static EntityPlacerConfig buildListVariableQueuedValuePlacerConfig(
HeuristicConfigPolicy<?> configPolicy,
ListVariableDescriptor<?> variableDescriptor) {
String mimicSelectorId = variableDescriptor.getVariableName();
// Prepare recording ValueSelector config.
ValueSelectorConfig mimicRecordingValueSelectorConfig = new ValueSelectorConfig(variableDescriptor.getVariableName())
.withId(mimicSelectorId);
if (ValueSelectorConfig.hasSorter(configPolicy.getValueSorterManner(), variableDescriptor)) {
mimicRecordingValueSelectorConfig = mimicRecordingValueSelectorConfig.withCacheType(SelectionCacheType.PHASE)
.withSelectionOrder(SelectionOrder.SORTED)
.withSorterManner(configPolicy.getValueSorterManner());
}
// Prepare replaying ValueSelector config.
ValueSelectorConfig mimicReplayingValueSelectorConfig = new ValueSelectorConfig()
.withMimicSelectorRef(mimicSelectorId);
// ListChangeMoveSelector uses the replaying ValueSelector.
ListChangeMoveSelectorConfig listChangeMoveSelectorConfig = new ListChangeMoveSelectorConfig()
.withValueSelectorConfig(mimicReplayingValueSelectorConfig);
// Finally, QueuedValuePlacer uses the recording ValueSelector and a ListChangeMoveSelector.
// The ListChangeMoveSelector's replaying ValueSelector mimics the QueuedValuePlacer's recording ValueSelector.
return new QueuedValuePlacerConfig()
.withValueSelectorConfig(mimicRecordingValueSelectorConfig)
.withMoveSelectorConfig(listChangeMoveSelectorConfig);
}
private ConstructionHeuristicDecider<Solution_> buildDecider(HeuristicConfigPolicy<Solution_> configPolicy,
Termination<Solution_> termination) {
ConstructionHeuristicForagerConfig foragerConfig_ =
Objects.requireNonNullElseGet(phaseConfig.getForagerConfig(), ConstructionHeuristicForagerConfig::new);
ConstructionHeuristicForager<Solution_> forager =
ConstructionHeuristicForagerFactory.<Solution_> create(foragerConfig_).buildForager(configPolicy);
EnvironmentMode environmentMode = configPolicy.getEnvironmentMode();
ConstructionHeuristicDecider<Solution_> decider;
Integer moveThreadCount = configPolicy.getMoveThreadCount();
if (moveThreadCount == null) {
decider = new ConstructionHeuristicDecider<>(configPolicy.getLogIndentation(), termination, forager);
} else {
decider = TimefoldSolverEnterpriseService
.loadOrFail(TimefoldSolverEnterpriseService.Feature.MULTITHREADED_SOLVING)
.buildConstructionHeuristic(moveThreadCount, termination, forager, environmentMode, configPolicy);
}
if (environmentMode.isNonIntrusiveFullAsserted()) {
decider.setAssertMoveScoreFromScratch(true);
}
if (environmentMode.isIntrusiveFastAsserted()) {
decider.setAssertExpectedUndoMoveScore(true);
}
return decider;
}
private EntityPlacerConfig buildUnfoldedEntityPlacerConfig(HeuristicConfigPolicy<Solution_> phaseConfigPolicy,
ConstructionHeuristicType constructionHeuristicType) {
switch (constructionHeuristicType) {
case FIRST_FIT:
case FIRST_FIT_DECREASING:
case WEAKEST_FIT:
case WEAKEST_FIT_DECREASING:
case STRONGEST_FIT:
case STRONGEST_FIT_DECREASING:
case ALLOCATE_ENTITY_FROM_QUEUE:
if (!ConfigUtils.isEmptyCollection(phaseConfig.getMoveSelectorConfigList())) {
return QueuedEntityPlacerFactory.unfoldNew(phaseConfigPolicy, phaseConfig.getMoveSelectorConfigList());
}
return new QueuedEntityPlacerConfig();
case ALLOCATE_TO_VALUE_FROM_QUEUE:
if (!ConfigUtils.isEmptyCollection(phaseConfig.getMoveSelectorConfigList())) {
return QueuedValuePlacerFactory.unfoldNew(checkSingleMoveSelectorConfig());
}
return new QueuedValuePlacerConfig();
case CHEAPEST_INSERTION:
case ALLOCATE_FROM_POOL:
if (!ConfigUtils.isEmptyCollection(phaseConfig.getMoveSelectorConfigList())) {
return PooledEntityPlacerFactory.unfoldNew(phaseConfigPolicy, checkSingleMoveSelectorConfig());
}
return new PooledEntityPlacerConfig();
default:
throw new IllegalStateException(
"The constructionHeuristicType (" + constructionHeuristicType + ") is not implemented.");
}
}
private MoveSelectorConfig<?> checkSingleMoveSelectorConfig() {
if (phaseConfig.getMoveSelectorConfigList().size() != 1) {
throw new IllegalArgumentException("For the constructionHeuristicType ("
+ phaseConfig.getConstructionHeuristicType() + "), the moveSelectorConfigList ("
+ phaseConfig.getMoveSelectorConfigList()
+ ") must be a singleton. Use a single " + UnionMoveSelectorConfig.class.getSimpleName()
+ " or " + CartesianProductMoveSelectorConfig.class.getSimpleName()
+ " element to nest multiple MoveSelectors.");
}
return phaseConfig.getMoveSelectorConfigList().get(0);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/decider/ConstructionHeuristicDecider.java | package ai.timefold.solver.core.impl.constructionheuristic.decider;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.constructionheuristic.decider.forager.ConstructionHeuristicForager;
import ai.timefold.solver.core.impl.constructionheuristic.placer.Placement;
import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicMoveScope;
import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicPhaseScope;
import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicStepScope;
import ai.timefold.solver.core.impl.heuristic.move.Move;
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.Termination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class ConstructionHeuristicDecider<Solution_> {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected final String logIndentation;
protected final Termination<Solution_> termination;
protected final ConstructionHeuristicForager<Solution_> forager;
protected boolean assertMoveScoreFromScratch = false;
protected boolean assertExpectedUndoMoveScore = false;
public ConstructionHeuristicDecider(String logIndentation, Termination<Solution_> termination,
ConstructionHeuristicForager<Solution_> forager) {
this.logIndentation = logIndentation;
this.termination = termination;
this.forager = forager;
}
public ConstructionHeuristicForager<Solution_> getForager() {
return forager;
}
public void setAssertMoveScoreFromScratch(boolean assertMoveScoreFromScratch) {
this.assertMoveScoreFromScratch = assertMoveScoreFromScratch;
}
public void setAssertExpectedUndoMoveScore(boolean assertExpectedUndoMoveScore) {
this.assertExpectedUndoMoveScore = assertExpectedUndoMoveScore;
}
// ************************************************************************
// Worker methods
// ************************************************************************
public void solvingStarted(SolverScope<Solution_> solverScope) {
forager.solvingStarted(solverScope);
}
public void phaseStarted(ConstructionHeuristicPhaseScope<Solution_> phaseScope) {
forager.phaseStarted(phaseScope);
}
public void stepStarted(ConstructionHeuristicStepScope<Solution_> stepScope) {
forager.stepStarted(stepScope);
}
public void stepEnded(ConstructionHeuristicStepScope<Solution_> stepScope) {
forager.stepEnded(stepScope);
}
public void phaseEnded(ConstructionHeuristicPhaseScope<Solution_> phaseScope) {
forager.phaseEnded(phaseScope);
}
public void solvingEnded(SolverScope<Solution_> solverScope) {
forager.solvingEnded(solverScope);
}
public void solvingError(SolverScope<Solution_> solverScope, Exception exception) {
// Overridable by a subclass.
}
public void decideNextStep(ConstructionHeuristicStepScope<Solution_> stepScope, Placement<Solution_> placement) {
int moveIndex = 0;
for (Move<Solution_> move : placement) {
ConstructionHeuristicMoveScope<Solution_> moveScope = new ConstructionHeuristicMoveScope<>(stepScope, moveIndex,
move);
moveIndex++;
doMove(moveScope);
if (forager.isQuitEarly()) {
break;
}
stepScope.getPhaseScope().getSolverScope().checkYielding();
if (termination.isPhaseTerminated(stepScope.getPhaseScope())) {
break;
}
}
pickMove(stepScope);
}
protected void pickMove(ConstructionHeuristicStepScope<Solution_> stepScope) {
ConstructionHeuristicMoveScope<Solution_> pickedMoveScope = forager.pickMove(stepScope);
if (pickedMoveScope != null) {
Move<Solution_> step = pickedMoveScope.getMove();
stepScope.setStep(step);
if (logger.isDebugEnabled()) {
stepScope.setStepString(step.toString());
}
stepScope.setScore(pickedMoveScope.getScore());
}
}
protected <Score_ extends Score<Score_>> void doMove(ConstructionHeuristicMoveScope<Solution_> moveScope) {
InnerScoreDirector<Solution_, Score_> scoreDirector = moveScope.getScoreDirector();
scoreDirector.doAndProcessMove(moveScope.getMove(), assertMoveScoreFromScratch, score -> {
moveScope.setScore(score);
forager.addMove(moveScope);
});
if (assertExpectedUndoMoveScore) {
scoreDirector.assertExpectedUndoMoveScore(moveScope.getMove(),
(Score_) moveScope.getStepScope().getPhaseScope().getLastCompletedStepScope().getScore());
}
logger.trace("{} Move index ({}), score ({}), move ({}).",
logIndentation,
moveScope.getMoveIndex(), moveScope.getScore(), moveScope.getMove());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/decider | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/decider/forager/DefaultConstructionHeuristicForager.java | package ai.timefold.solver.core.impl.constructionheuristic.decider.forager;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.config.constructionheuristic.decider.forager.ConstructionHeuristicPickEarlyType;
import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicMoveScope;
import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicStepScope;
public class DefaultConstructionHeuristicForager<Solution_> extends AbstractConstructionHeuristicForager<Solution_> {
protected final ConstructionHeuristicPickEarlyType pickEarlyType;
protected long selectedMoveCount;
protected ConstructionHeuristicMoveScope<Solution_> earlyPickedMoveScope;
protected ConstructionHeuristicMoveScope<Solution_> maxScoreMoveScope;
public DefaultConstructionHeuristicForager(ConstructionHeuristicPickEarlyType pickEarlyType) {
this.pickEarlyType = pickEarlyType;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public void stepStarted(ConstructionHeuristicStepScope<Solution_> stepScope) {
super.stepStarted(stepScope);
selectedMoveCount = 0L;
earlyPickedMoveScope = null;
maxScoreMoveScope = null;
}
@Override
public void stepEnded(ConstructionHeuristicStepScope<Solution_> stepScope) {
super.stepEnded(stepScope);
earlyPickedMoveScope = null;
maxScoreMoveScope = null;
}
@Override
public void addMove(ConstructionHeuristicMoveScope<Solution_> moveScope) {
selectedMoveCount++;
checkPickEarly(moveScope);
if (maxScoreMoveScope == null || moveScope.getScore().compareTo(maxScoreMoveScope.getScore()) > 0) {
maxScoreMoveScope = moveScope;
}
}
protected void checkPickEarly(ConstructionHeuristicMoveScope<Solution_> moveScope) {
switch (pickEarlyType) {
case NEVER:
break;
case FIRST_NON_DETERIORATING_SCORE:
Score lastStepScore = moveScope.getStepScope().getPhaseScope()
.getLastCompletedStepScope().getScore();
if (moveScope.getScore().withInitScore(0).compareTo(lastStepScore.withInitScore(0)) >= 0) {
earlyPickedMoveScope = moveScope;
}
break;
case FIRST_FEASIBLE_SCORE:
if (moveScope.getScore().withInitScore(0).isFeasible()) {
earlyPickedMoveScope = moveScope;
}
break;
case FIRST_FEASIBLE_SCORE_OR_NON_DETERIORATING_HARD:
Score lastStepScore2 = moveScope.getStepScope().getPhaseScope()
.getLastCompletedStepScope().getScore();
Score lastStepScoreDifference = moveScope.getScore().withInitScore(0)
.subtract(lastStepScore2.withInitScore(0));
if (lastStepScoreDifference.isFeasible()) {
earlyPickedMoveScope = moveScope;
}
break;
default:
throw new IllegalStateException("The pickEarlyType (" + pickEarlyType + ") is not implemented.");
}
}
@Override
public boolean isQuitEarly() {
return earlyPickedMoveScope != null;
}
@Override
public ConstructionHeuristicMoveScope<Solution_> pickMove(ConstructionHeuristicStepScope<Solution_> stepScope) {
stepScope.setSelectedMoveCount(selectedMoveCount);
if (earlyPickedMoveScope != null) {
return earlyPickedMoveScope;
} else {
return maxScoreMoveScope;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/placer/AbstractEntityPlacer.java | package ai.timefold.solver.core.impl.constructionheuristic.placer;
import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleSupport;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract superclass for {@link EntityPlacer}.
*
* @see EntityPlacer
*/
public abstract class AbstractEntityPlacer<Solution_> implements EntityPlacer<Solution_> {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected PhaseLifecycleSupport<Solution_> phaseLifecycleSupport = new PhaseLifecycleSupport<>();
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
phaseLifecycleSupport.fireSolvingStarted(solverScope);
}
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
phaseLifecycleSupport.firePhaseStarted(phaseScope);
}
@Override
public void stepStarted(AbstractStepScope<Solution_> stepScope) {
phaseLifecycleSupport.fireStepStarted(stepScope);
}
@Override
public void stepEnded(AbstractStepScope<Solution_> stepScope) {
phaseLifecycleSupport.fireStepEnded(stepScope);
}
@Override
public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) {
phaseLifecycleSupport.firePhaseEnded(phaseScope);
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
phaseLifecycleSupport.fireSolvingEnded(solverScope);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/placer/AbstractEntityPlacerFactory.java | package ai.timefold.solver.core.impl.constructionheuristic.placer;
import static ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType.PHASE;
import static ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType.STEP;
import ai.timefold.solver.core.config.constructionheuristic.placer.EntityPlacerConfig;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig;
import ai.timefold.solver.core.impl.AbstractFromConfigFactory;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
abstract class AbstractEntityPlacerFactory<Solution_, EntityPlacerConfig_ extends EntityPlacerConfig<EntityPlacerConfig_>>
extends AbstractFromConfigFactory<Solution_, EntityPlacerConfig_> implements EntityPlacerFactory<Solution_> {
protected AbstractEntityPlacerFactory(EntityPlacerConfig_ placerConfig) {
super(placerConfig);
}
protected ChangeMoveSelectorConfig buildChangeMoveSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy,
String entitySelectorConfigId, GenuineVariableDescriptor<Solution_> variableDescriptor) {
ChangeMoveSelectorConfig changeMoveSelectorConfig = new ChangeMoveSelectorConfig();
changeMoveSelectorConfig.setEntitySelectorConfig(
EntitySelectorConfig.newMimicSelectorConfig(entitySelectorConfigId));
ValueSelectorConfig changeValueSelectorConfig = new ValueSelectorConfig()
.withVariableName(variableDescriptor.getVariableName());
if (ValueSelectorConfig.hasSorter(configPolicy.getValueSorterManner(), variableDescriptor)) {
changeValueSelectorConfig = changeValueSelectorConfig
.withCacheType(variableDescriptor.isValueRangeEntityIndependent() ? PHASE : STEP)
.withSelectionOrder(SelectionOrder.SORTED)
.withSorterManner(configPolicy.getValueSorterManner());
}
return changeMoveSelectorConfig.withValueSelectorConfig(changeValueSelectorConfig);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/placer/EntityPlacer.java | package ai.timefold.solver.core.impl.constructionheuristic.placer;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter;
import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleListener;
public interface EntityPlacer<Solution_> extends Iterable<Placement<Solution_>>, PhaseLifecycleListener<Solution_> {
EntityPlacer<Solution_> rebuildWithFilter(SelectionFilter<Solution_, Object> filter);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/placer/EntityPlacerFactory.java | package ai.timefold.solver.core.impl.constructionheuristic.placer;
import ai.timefold.solver.core.config.constructionheuristic.placer.EntityPlacerConfig;
import ai.timefold.solver.core.config.constructionheuristic.placer.PooledEntityPlacerConfig;
import ai.timefold.solver.core.config.constructionheuristic.placer.QueuedEntityPlacerConfig;
import ai.timefold.solver.core.config.constructionheuristic.placer.QueuedValuePlacerConfig;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
public interface EntityPlacerFactory<Solution_> {
static <Solution_> EntityPlacerFactory<Solution_> create(EntityPlacerConfig<?> entityPlacerConfig) {
if (PooledEntityPlacerConfig.class.isAssignableFrom(entityPlacerConfig.getClass())) {
return new PooledEntityPlacerFactory<>((PooledEntityPlacerConfig) entityPlacerConfig);
} else if (QueuedEntityPlacerConfig.class.isAssignableFrom(entityPlacerConfig.getClass())) {
return new QueuedEntityPlacerFactory<>((QueuedEntityPlacerConfig) entityPlacerConfig);
} else if (QueuedValuePlacerConfig.class.isAssignableFrom(entityPlacerConfig.getClass())) {
return new QueuedValuePlacerFactory<>((QueuedValuePlacerConfig) entityPlacerConfig);
} else {
throw new IllegalArgumentException(String.format("Unknown %s type: (%s).",
EntityPlacerConfig.class.getSimpleName(), entityPlacerConfig.getClass().getName()));
}
}
EntityPlacer<Solution_> buildEntityPlacer(HeuristicConfigPolicy<Solution_> configPolicy);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/placer/Placement.java | package ai.timefold.solver.core.impl.constructionheuristic.placer;
import java.util.Iterator;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.heuristic.move.Move;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class Placement<Solution_> implements Iterable<Move<Solution_>> {
private final Iterator<Move<Solution_>> moveIterator;
public Placement(Iterator<Move<Solution_>> moveIterator) {
this.moveIterator = moveIterator;
}
@Override
public Iterator<Move<Solution_>> iterator() {
return moveIterator;
}
@Override
public String toString() {
return "Placement (" + moveIterator + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/placer/PooledEntityPlacer.java | package ai.timefold.solver.core.impl.constructionheuristic.placer;
import java.util.Iterator;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.decorator.FilteringMoveSelector;
public class PooledEntityPlacer<Solution_> extends AbstractEntityPlacer<Solution_> implements EntityPlacer<Solution_> {
protected final MoveSelector<Solution_> moveSelector;
public PooledEntityPlacer(MoveSelector<Solution_> moveSelector) {
this.moveSelector = moveSelector;
phaseLifecycleSupport.addEventListener(moveSelector);
}
@Override
public Iterator<Placement<Solution_>> iterator() {
return new PooledEntityPlacingIterator();
}
@Override
public EntityPlacer<Solution_> rebuildWithFilter(SelectionFilter<Solution_, Object> filter) {
return new PooledEntityPlacer<>(FilteringMoveSelector.of(moveSelector, filter::accept));
}
private class PooledEntityPlacingIterator extends UpcomingSelectionIterator<Placement<Solution_>> {
private PooledEntityPlacingIterator() {
}
@Override
protected Placement<Solution_> createUpcomingSelection() {
Iterator<Move<Solution_>> moveIterator = moveSelector.iterator();
if (!moveIterator.hasNext()) {
return noUpcomingSelection();
}
return new Placement<>(moveIterator);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/placer/PooledEntityPlacerFactory.java | package ai.timefold.solver.core.impl.constructionheuristic.placer;
import java.util.ArrayList;
import java.util.List;
import ai.timefold.solver.core.config.constructionheuristic.placer.PooledEntityPlacerConfig;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.composite.CartesianProductMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig;
import ai.timefold.solver.core.impl.AbstractFromConfigFactory;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelectorFactory;
public class PooledEntityPlacerFactory<Solution_>
extends AbstractEntityPlacerFactory<Solution_, PooledEntityPlacerConfig> {
public static <Solution_> PooledEntityPlacerConfig unfoldNew(HeuristicConfigPolicy<Solution_> configPolicy,
MoveSelectorConfig templateMoveSelectorConfig) {
PooledEntityPlacerConfig config = new PooledEntityPlacerConfig();
List<MoveSelectorConfig> leafMoveSelectorConfigList = new ArrayList<>();
MoveSelectorConfig moveSelectorConfig = (MoveSelectorConfig) templateMoveSelectorConfig.copyConfig();
moveSelectorConfig.extractLeafMoveSelectorConfigsIntoList(leafMoveSelectorConfigList);
config.setMoveSelectorConfig(moveSelectorConfig);
EntitySelectorConfig entitySelectorConfig = null;
for (MoveSelectorConfig leafMoveSelectorConfig : leafMoveSelectorConfigList) {
if (!(leafMoveSelectorConfig instanceof ChangeMoveSelectorConfig)) {
throw new IllegalStateException("The <constructionHeuristic> contains a moveSelector ("
+ leafMoveSelectorConfig + ") that isn't a <changeMoveSelector>, a <unionMoveSelector>"
+ " or a <cartesianProductMoveSelector>.\n"
+ "Maybe you're using a moveSelector in <constructionHeuristic>"
+ " that's only supported for <localSearch>.");
}
ChangeMoveSelectorConfig changeMoveSelectorConfig =
(ChangeMoveSelectorConfig) leafMoveSelectorConfig;
if (changeMoveSelectorConfig.getEntitySelectorConfig() != null) {
throw new IllegalStateException("The <constructionHeuristic> contains a changeMoveSelector ("
+ changeMoveSelectorConfig + ") that contains an entitySelector ("
+ changeMoveSelectorConfig.getEntitySelectorConfig()
+ ") without explicitly configuring the <pooledEntityPlacer>.");
}
if (entitySelectorConfig == null) {
EntityDescriptor<Solution_> entityDescriptor = new PooledEntityPlacerFactory<Solution_>(config)
.getTheOnlyEntityDescriptor(configPolicy.getSolutionDescriptor());
entitySelectorConfig =
AbstractFromConfigFactory.getDefaultEntitySelectorConfigForEntity(configPolicy, entityDescriptor);
changeMoveSelectorConfig.setEntitySelectorConfig(entitySelectorConfig);
}
changeMoveSelectorConfig.setEntitySelectorConfig(
EntitySelectorConfig.newMimicSelectorConfig(entitySelectorConfig.getId()));
}
return config;
}
public PooledEntityPlacerFactory(PooledEntityPlacerConfig placerConfig) {
super(placerConfig);
}
@Override
public PooledEntityPlacer<Solution_> buildEntityPlacer(HeuristicConfigPolicy<Solution_> configPolicy) {
MoveSelectorConfig moveSelectorConfig_ =
config.getMoveSelectorConfig() == null ? buildMoveSelectorConfig(configPolicy) : config.getMoveSelectorConfig();
MoveSelector<Solution_> moveSelector = MoveSelectorFactory.<Solution_> create(moveSelectorConfig_)
.buildMoveSelector(configPolicy, SelectionCacheType.JUST_IN_TIME, SelectionOrder.ORIGINAL, false);
return new PooledEntityPlacer<>(moveSelector);
}
private MoveSelectorConfig buildMoveSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy) {
EntityDescriptor<Solution_> entityDescriptor = getTheOnlyEntityDescriptor(configPolicy.getSolutionDescriptor());
EntitySelectorConfig entitySelectorConfig =
AbstractFromConfigFactory.getDefaultEntitySelectorConfigForEntity(configPolicy, entityDescriptor);
List<GenuineVariableDescriptor<Solution_>> variableDescriptors = entityDescriptor.getGenuineVariableDescriptorList();
List<MoveSelectorConfig> subMoveSelectorConfigList = new ArrayList<>(variableDescriptors.size());
for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptors) {
subMoveSelectorConfigList
.add(buildChangeMoveSelectorConfig(configPolicy, entitySelectorConfig.getId(), variableDescriptor));
}
// The first entitySelectorConfig must be the mimic recorder, not the mimic replayer
((ChangeMoveSelectorConfig) subMoveSelectorConfigList.get(0)).setEntitySelectorConfig(entitySelectorConfig);
MoveSelectorConfig moveSelectorConfig_;
if (subMoveSelectorConfigList.size() > 1) {
// Default to cartesian product (not a union) of planning variables.
moveSelectorConfig_ = new CartesianProductMoveSelectorConfig(subMoveSelectorConfigList);
} else {
moveSelectorConfig_ = subMoveSelectorConfigList.get(0);
}
return moveSelectorConfig_;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/placer/QueuedEntityPlacer.java | package ai.timefold.solver.core.impl.constructionheuristic.placer;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.decorator.FilteringEntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
public class QueuedEntityPlacer<Solution_> extends AbstractEntityPlacer<Solution_> implements EntityPlacer<Solution_> {
protected final EntitySelector<Solution_> entitySelector;
protected final List<MoveSelector<Solution_>> moveSelectorList;
public QueuedEntityPlacer(EntitySelector<Solution_> entitySelector, List<MoveSelector<Solution_>> moveSelectorList) {
this.entitySelector = entitySelector;
this.moveSelectorList = moveSelectorList;
phaseLifecycleSupport.addEventListener(entitySelector);
for (MoveSelector<Solution_> moveSelector : moveSelectorList) {
phaseLifecycleSupport.addEventListener(moveSelector);
}
}
@Override
public Iterator<Placement<Solution_>> iterator() {
return new QueuedEntityPlacingIterator(entitySelector.iterator());
}
@Override
public EntityPlacer<Solution_> rebuildWithFilter(SelectionFilter<Solution_, Object> filter) {
return new QueuedEntityPlacer<>(FilteringEntitySelector.of(entitySelector, filter), moveSelectorList);
}
private class QueuedEntityPlacingIterator extends UpcomingSelectionIterator<Placement<Solution_>> {
private final Iterator<Object> entityIterator;
private Iterator<MoveSelector<Solution_>> moveSelectorIterator;
private QueuedEntityPlacingIterator(Iterator<Object> entityIterator) {
this.entityIterator = entityIterator;
moveSelectorIterator = Collections.emptyIterator();
}
@Override
protected Placement<Solution_> createUpcomingSelection() {
Iterator<Move<Solution_>> moveIterator = null;
// Skip empty placements to avoid no-operation steps
while (moveIterator == null || !moveIterator.hasNext()) {
// If a moveSelector's iterator is empty, it might not be empty the next time
// (because the entity changes)
while (!moveSelectorIterator.hasNext()) {
if (!entityIterator.hasNext()) {
return noUpcomingSelection();
}
entityIterator.next();
moveSelectorIterator = moveSelectorList.iterator();
}
MoveSelector<Solution_> moveSelector = moveSelectorIterator.next();
moveIterator = moveSelector.iterator();
}
return new Placement<>(moveIterator);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/placer/QueuedEntityPlacerFactory.java | package ai.timefold.solver.core.impl.constructionheuristic.placer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import ai.timefold.solver.core.config.constructionheuristic.placer.QueuedEntityPlacerConfig;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.composite.CartesianProductMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig;
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.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelector;
import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelectorFactory;
public class QueuedEntityPlacerFactory<Solution_>
extends AbstractEntityPlacerFactory<Solution_, QueuedEntityPlacerConfig> {
public static <Solution_> QueuedEntityPlacerConfig unfoldNew(HeuristicConfigPolicy<Solution_> configPolicy,
List<MoveSelectorConfig> templateMoveSelectorConfigList) {
QueuedEntityPlacerConfig config = new QueuedEntityPlacerConfig();
config.setEntitySelectorConfig(new QueuedEntityPlacerFactory<Solution_>(config)
.buildEntitySelectorConfig(configPolicy));
config.setMoveSelectorConfigList(new ArrayList<>(templateMoveSelectorConfigList.size()));
List<MoveSelectorConfig> leafMoveSelectorConfigList = new ArrayList<>(templateMoveSelectorConfigList.size());
for (MoveSelectorConfig templateMoveSelectorConfig : templateMoveSelectorConfigList) {
MoveSelectorConfig moveSelectorConfig = (MoveSelectorConfig) templateMoveSelectorConfig.copyConfig();
moveSelectorConfig.extractLeafMoveSelectorConfigsIntoList(leafMoveSelectorConfigList);
config.getMoveSelectorConfigList().add(moveSelectorConfig);
}
for (MoveSelectorConfig leafMoveSelectorConfig : leafMoveSelectorConfigList) {
if (!(leafMoveSelectorConfig instanceof ChangeMoveSelectorConfig)) {
throw new IllegalStateException("The <constructionHeuristic> contains a moveSelector ("
+ leafMoveSelectorConfig + ") that isn't a <changeMoveSelector>, a <unionMoveSelector>"
+ " or a <cartesianProductMoveSelector>.\n"
+ "Maybe you're using a moveSelector in <constructionHeuristic>"
+ " that's only supported for <localSearch>.");
}
ChangeMoveSelectorConfig changeMoveSelectorConfig = (ChangeMoveSelectorConfig) leafMoveSelectorConfig;
if (changeMoveSelectorConfig.getEntitySelectorConfig() != null) {
throw new IllegalStateException("The <constructionHeuristic> contains a changeMoveSelector ("
+ changeMoveSelectorConfig + ") that contains an entitySelector ("
+ changeMoveSelectorConfig.getEntitySelectorConfig()
+ ") without explicitly configuring the <queuedEntityPlacer>.");
}
changeMoveSelectorConfig.setEntitySelectorConfig(
EntitySelectorConfig.newMimicSelectorConfig(config.getEntitySelectorConfig().getId()));
}
return config;
}
public QueuedEntityPlacerFactory(QueuedEntityPlacerConfig placerConfig) {
super(placerConfig);
}
@Override
public QueuedEntityPlacer<Solution_> buildEntityPlacer(HeuristicConfigPolicy<Solution_> configPolicy) {
EntitySelectorConfig entitySelectorConfig_ = buildEntitySelectorConfig(configPolicy);
EntitySelector<Solution_> entitySelector =
EntitySelectorFactory.<Solution_> create(entitySelectorConfig_)
.buildEntitySelector(configPolicy, SelectionCacheType.PHASE, SelectionOrder.ORIGINAL);
List<MoveSelectorConfig> moveSelectorConfigList_;
if (ConfigUtils.isEmptyCollection(config.getMoveSelectorConfigList())) {
EntityDescriptor<Solution_> entityDescriptor = entitySelector.getEntityDescriptor();
List<GenuineVariableDescriptor<Solution_>> variableDescriptorList =
entityDescriptor.getGenuineVariableDescriptorList();
List<MoveSelectorConfig> subMoveSelectorConfigList = new ArrayList<>(variableDescriptorList.size());
for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) {
subMoveSelectorConfigList
.add(buildChangeMoveSelectorConfig(configPolicy, entitySelectorConfig_.getId(), variableDescriptor));
}
MoveSelectorConfig subMoveSelectorConfig;
if (subMoveSelectorConfigList.size() > 1) {
// Default to cartesian product (not a queue) of planning variables.
subMoveSelectorConfig = new CartesianProductMoveSelectorConfig(subMoveSelectorConfigList);
} else {
subMoveSelectorConfig = subMoveSelectorConfigList.get(0);
}
moveSelectorConfigList_ = Collections.singletonList(subMoveSelectorConfig);
} else {
moveSelectorConfigList_ = config.getMoveSelectorConfigList();
}
List<MoveSelector<Solution_>> moveSelectorList = new ArrayList<>(moveSelectorConfigList_.size());
for (MoveSelectorConfig moveSelectorConfig : moveSelectorConfigList_) {
MoveSelector<Solution_> moveSelector = MoveSelectorFactory.<Solution_> create(moveSelectorConfig)
.buildMoveSelector(configPolicy, SelectionCacheType.JUST_IN_TIME, SelectionOrder.ORIGINAL, false);
moveSelectorList.add(moveSelector);
}
return new QueuedEntityPlacer<>(entitySelector, moveSelectorList);
}
public EntitySelectorConfig buildEntitySelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy) {
EntitySelectorConfig entitySelectorConfig_;
if (config.getEntitySelectorConfig() == null) {
EntityDescriptor<Solution_> entityDescriptor = getTheOnlyEntityDescriptor(configPolicy.getSolutionDescriptor());
entitySelectorConfig_ = getDefaultEntitySelectorConfigForEntity(configPolicy, entityDescriptor);
} else {
entitySelectorConfig_ = config.getEntitySelectorConfig();
}
if (entitySelectorConfig_.getCacheType() != null
&& entitySelectorConfig_.getCacheType().compareTo(SelectionCacheType.PHASE) < 0) {
throw new IllegalArgumentException("The queuedEntityPlacer (" + config
+ ") cannot have an entitySelectorConfig (" + entitySelectorConfig_
+ ") with a cacheType (" + entitySelectorConfig_.getCacheType()
+ ") lower than " + SelectionCacheType.PHASE + ".");
}
return entitySelectorConfig_;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/placer/QueuedValuePlacer.java | package ai.timefold.solver.core.impl.constructionheuristic.placer;
import java.util.Collections;
import java.util.Iterator;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.EntityIndependentFilteringValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.decorator.FilteringValueSelector;
public class QueuedValuePlacer<Solution_> extends AbstractEntityPlacer<Solution_> implements EntityPlacer<Solution_> {
protected final EntityIndependentValueSelector<Solution_> valueSelector;
protected final MoveSelector<Solution_> moveSelector;
public QueuedValuePlacer(EntityIndependentValueSelector<Solution_> valueSelector,
MoveSelector<Solution_> moveSelector) {
this.valueSelector = valueSelector;
this.moveSelector = moveSelector;
phaseLifecycleSupport.addEventListener(valueSelector);
phaseLifecycleSupport.addEventListener(moveSelector);
}
@Override
public Iterator<Placement<Solution_>> iterator() {
return new QueuedValuePlacingIterator();
}
private class QueuedValuePlacingIterator extends UpcomingSelectionIterator<Placement<Solution_>> {
private Iterator<Object> valueIterator;
private QueuedValuePlacingIterator() {
valueIterator = Collections.emptyIterator();
}
@Override
protected Placement<Solution_> createUpcomingSelection() {
// If all values are used, there can still be entities uninitialized
if (!valueIterator.hasNext()) {
valueIterator = valueSelector.iterator();
if (!valueIterator.hasNext()) {
return noUpcomingSelection();
}
}
valueIterator.next();
var moveIterator = moveSelector.iterator();
// Because the valueSelector is entity independent, there is always a move if there's still an entity
if (!moveIterator.hasNext()) {
return noUpcomingSelection();
}
return new Placement<>(moveIterator);
}
}
@Override
public EntityPlacer<Solution_> rebuildWithFilter(SelectionFilter<Solution_, Object> filter) {
return new QueuedValuePlacer<>(
(EntityIndependentFilteringValueSelector<Solution_>) FilteringValueSelector.of(valueSelector, filter),
moveSelector);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/placer/QueuedValuePlacerFactory.java | package ai.timefold.solver.core.impl.constructionheuristic.placer;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.config.constructionheuristic.placer.QueuedValuePlacerConfig;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType;
import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig;
import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector;
import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelectorFactory;
import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelector;
import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory;
public class QueuedValuePlacerFactory<Solution_>
extends AbstractEntityPlacerFactory<Solution_, QueuedValuePlacerConfig> {
public static QueuedValuePlacerConfig unfoldNew(MoveSelectorConfig templateMoveSelectorConfig) {
throw new UnsupportedOperationException("The <constructionHeuristic> contains a moveSelector ("
+ templateMoveSelectorConfig + ") and the <queuedValuePlacer> does not support unfolding those yet.");
}
public QueuedValuePlacerFactory(QueuedValuePlacerConfig placerConfig) {
super(placerConfig);
}
@Override
public QueuedValuePlacer<Solution_> buildEntityPlacer(HeuristicConfigPolicy<Solution_> configPolicy) {
EntityDescriptor<Solution_> entityDescriptor = deduceEntityDescriptor(configPolicy, config.getEntityClass());
ValueSelectorConfig valueSelectorConfig_ = buildValueSelectorConfig(configPolicy, entityDescriptor);
// TODO improve the ValueSelectorFactory API (avoid the boolean flags).
ValueSelector<Solution_> valueSelector = ValueSelectorFactory.<Solution_> create(valueSelectorConfig_)
.buildValueSelector(configPolicy, entityDescriptor, SelectionCacheType.PHASE, SelectionOrder.ORIGINAL,
false, // override applyReinitializeVariableFiltering
ValueSelectorFactory.ListValueFilteringType.ACCEPT_UNASSIGNED);
MoveSelectorConfig<?> moveSelectorConfig_ = config.getMoveSelectorConfig() == null
? buildChangeMoveSelectorConfig(configPolicy, valueSelectorConfig_.getId(),
valueSelector.getVariableDescriptor())
: config.getMoveSelectorConfig();
MoveSelector<Solution_> moveSelector = MoveSelectorFactory.<Solution_> create(moveSelectorConfig_)
.buildMoveSelector(configPolicy, SelectionCacheType.JUST_IN_TIME, SelectionOrder.ORIGINAL, false);
if (!(valueSelector instanceof EntityIndependentValueSelector)) {
throw new IllegalArgumentException("The queuedValuePlacer (" + this
+ ") needs to be based on an "
+ EntityIndependentValueSelector.class.getSimpleName() + " (" + valueSelector + ")."
+ " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations.");
}
return new QueuedValuePlacer<>((EntityIndependentValueSelector<Solution_>) valueSelector, moveSelector);
}
private ValueSelectorConfig buildValueSelectorConfig(HeuristicConfigPolicy<Solution_> configPolicy,
EntityDescriptor<Solution_> entityDescriptor) {
ValueSelectorConfig valueSelectorConfig_;
if (config.getValueSelectorConfig() == null) {
Class<?> entityClass = entityDescriptor.getEntityClass();
GenuineVariableDescriptor<Solution_> variableDescriptor = getTheOnlyVariableDescriptor(entityDescriptor);
valueSelectorConfig_ = new ValueSelectorConfig()
.withId(entityClass.getName() + "." + variableDescriptor.getVariableName())
.withVariableName(variableDescriptor.getVariableName());
if (ValueSelectorConfig.hasSorter(configPolicy.getValueSorterManner(), variableDescriptor)) {
valueSelectorConfig_ = valueSelectorConfig_.withCacheType(SelectionCacheType.PHASE)
.withSelectionOrder(SelectionOrder.SORTED)
.withSorterManner(configPolicy.getValueSorterManner());
}
} else {
valueSelectorConfig_ = config.getValueSelectorConfig();
}
if (valueSelectorConfig_.getCacheType() != null
&& valueSelectorConfig_.getCacheType().compareTo(SelectionCacheType.PHASE) < 0) {
throw new IllegalArgumentException("The queuedValuePlacer (" + this
+ ") cannot have a valueSelectorConfig (" + valueSelectorConfig_
+ ") with a cacheType (" + valueSelectorConfig_.getCacheType()
+ ") lower than " + SelectionCacheType.PHASE + ".");
}
return valueSelectorConfig_;
}
@Override
protected ChangeMoveSelectorConfig buildChangeMoveSelectorConfig(
HeuristicConfigPolicy<Solution_> configPolicy, String valueSelectorConfigId,
GenuineVariableDescriptor<Solution_> variableDescriptor) {
ChangeMoveSelectorConfig changeMoveSelectorConfig = new ChangeMoveSelectorConfig();
EntityDescriptor<Solution_> entityDescriptor = variableDescriptor.getEntityDescriptor();
EntitySelectorConfig changeEntitySelectorConfig = new EntitySelectorConfig()
.withEntityClass(entityDescriptor.getEntityClass());
if (EntitySelectorConfig.hasSorter(configPolicy.getEntitySorterManner(), entityDescriptor)) {
changeEntitySelectorConfig = changeEntitySelectorConfig.withCacheType(SelectionCacheType.PHASE)
.withSelectionOrder(SelectionOrder.SORTED)
.withSorterManner(configPolicy.getEntitySorterManner());
}
ValueSelectorConfig changeValueSelectorConfig = new ValueSelectorConfig()
.withMimicSelectorRef(valueSelectorConfigId);
return changeMoveSelectorConfig.withEntitySelectorConfig(changeEntitySelectorConfig)
.withValueSelectorConfig(changeValueSelectorConfig);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/scope/ConstructionHeuristicMoveScope.java | package ai.timefold.solver.core.impl.constructionheuristic.scope;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.phase.scope.AbstractMoveScope;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class ConstructionHeuristicMoveScope<Solution_> extends AbstractMoveScope<Solution_> {
private final ConstructionHeuristicStepScope<Solution_> stepScope;
public ConstructionHeuristicMoveScope(ConstructionHeuristicStepScope<Solution_> stepScope,
int moveIndex, Move<Solution_> move) {
super(moveIndex, move);
this.stepScope = stepScope;
}
@Override
public ConstructionHeuristicStepScope<Solution_> getStepScope() {
return stepScope;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/scope/ConstructionHeuristicPhaseScope.java | package ai.timefold.solver.core.impl.constructionheuristic.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 class ConstructionHeuristicPhaseScope<Solution_> extends AbstractPhaseScope<Solution_> {
private ConstructionHeuristicStepScope<Solution_> lastCompletedStepScope;
public ConstructionHeuristicPhaseScope(SolverScope<Solution_> solverScope) {
super(solverScope);
lastCompletedStepScope = new ConstructionHeuristicStepScope<>(this, -1);
}
@Override
public ConstructionHeuristicStepScope<Solution_> getLastCompletedStepScope() {
return lastCompletedStepScope;
}
public void setLastCompletedStepScope(ConstructionHeuristicStepScope<Solution_> lastCompletedStepScope) {
this.lastCompletedStepScope = lastCompletedStepScope;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/constructionheuristic/scope/ConstructionHeuristicStepScope.java | package ai.timefold.solver.core.impl.constructionheuristic.scope;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class ConstructionHeuristicStepScope<Solution_> extends AbstractStepScope<Solution_> {
private final ConstructionHeuristicPhaseScope<Solution_> phaseScope;
private Object entity = null;
private Move<Solution_> step = null;
private String stepString = null;
private Long selectedMoveCount = null;
public ConstructionHeuristicStepScope(ConstructionHeuristicPhaseScope<Solution_> phaseScope) {
this(phaseScope, phaseScope.getNextStepIndex());
}
public ConstructionHeuristicStepScope(ConstructionHeuristicPhaseScope<Solution_> phaseScope, int stepIndex) {
super(stepIndex);
this.phaseScope = phaseScope;
}
@Override
public ConstructionHeuristicPhaseScope<Solution_> getPhaseScope() {
return phaseScope;
}
public Object getEntity() {
return entity;
}
public void setEntity(Object entity) {
this.entity = entity;
}
public Move<Solution_> getStep() {
return step;
}
public void setStep(Move<Solution_> step) {
this.step = step;
}
/**
* @return null if logging level is too high
*/
public String getStepString() {
return stepString;
}
public void setStepString(String stepString) {
this.stepString = stepString;
}
public Long getSelectedMoveCount() {
return selectedMoveCount;
}
public void setSelectedMoveCount(Long selectedMoveCount) {
this.selectedMoveCount = selectedMoveCount;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/common/ReflectionHelper.java | /*
* Copied from the Hibernate Validator project
* Original authors: Hardy Ferentschik, Gunnar Morling and Kevin Pollet.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.timefold.solver.core.impl.domain.common;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public final class ReflectionHelper {
private static final String PROPERTY_ACCESSOR_PREFIX_GET = "get";
private static final String PROPERTY_ACCESSOR_PREFIX_IS = "is";
private static final String[] PROPERTY_ACCESSOR_PREFIXES = {
PROPERTY_ACCESSOR_PREFIX_GET,
PROPERTY_ACCESSOR_PREFIX_IS
};
private static final String PROPERTY_MUTATOR_PREFIX = "set";
/**
* Returns the JavaBeans property name of the given member.
*
* @param member never null
* @return null if the member is neither a field nor a getter method according to the JavaBeans standard
*/
public static String getGetterPropertyName(Member member) {
if (member instanceof Field) {
return member.getName();
} else if (member instanceof Method) {
String methodName = member.getName();
for (String prefix : PROPERTY_ACCESSOR_PREFIXES) {
if (methodName.startsWith(prefix)) {
return decapitalizePropertyName(methodName.substring(prefix.length()));
}
}
}
return null;
}
private static String decapitalizePropertyName(String propertyName) {
if (propertyName.isEmpty() || startsWithSeveralUpperCaseLetters(propertyName)) {
return propertyName;
} else {
return propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1);
}
}
private static boolean startsWithSeveralUpperCaseLetters(String propertyName) {
return propertyName.length() > 1 &&
Character.isUpperCase(propertyName.charAt(0)) &&
Character.isUpperCase(propertyName.charAt(1));
}
/**
* Checks whether the given method is a valid getter method according to the JavaBeans standard.
*
* @param method never null
* @return true if the given method is a getter method
*/
public static boolean isGetterMethod(Method method) {
if (method.getParameterTypes().length != 0) {
return false;
}
String methodName = method.getName();
if (methodName.startsWith(PROPERTY_ACCESSOR_PREFIX_GET) && method.getReturnType() != void.class) {
return true;
} else if (methodName.startsWith(PROPERTY_ACCESSOR_PREFIX_IS) && method.getReturnType() == boolean.class) {
return true;
}
return false;
}
/**
* @param containingClass never null
* @param propertyName never null
* @return true if that getter exists
*/
public static boolean hasGetterMethod(Class<?> containingClass, String propertyName) {
return getGetterMethod(containingClass, propertyName) != null;
}
/**
* @param containingClass never null
* @param propertyName never null
* @return sometimes null
*/
public static Method getGetterMethod(Class<?> containingClass, String propertyName) {
String getterName = PROPERTY_ACCESSOR_PREFIX_GET
+ (propertyName.isEmpty() ? "" : propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1));
try {
return containingClass.getMethod(getterName);
} catch (NoSuchMethodException e) {
// intentionally empty
}
String isserName = PROPERTY_ACCESSOR_PREFIX_IS
+ (propertyName.isEmpty() ? "" : propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1));
try {
Method method = containingClass.getMethod(isserName);
if (method.getReturnType() == boolean.class) {
return method;
}
} catch (NoSuchMethodException e) {
// intentionally empty
}
return null;
}
/**
* @param containingClass never null
* @param fieldName never null
* @return true if that field exists
*/
public static boolean hasField(Class<?> containingClass, String fieldName) {
return getField(containingClass, fieldName) != null;
}
/**
* @param containingClass never null
* @param fieldName never null
* @return sometimes null
*/
public static Field getField(Class<?> containingClass, String fieldName) {
try {
return containingClass.getField(fieldName);
} catch (NoSuchFieldException e) {
return null;
}
}
/**
* @param containingClass never null
* @param propertyType never null
* @param propertyName never null
* @return null if it doesn't exist
*/
public static Method getSetterMethod(Class<?> containingClass, Class<?> propertyType, String propertyName) {
String setterName = PROPERTY_MUTATOR_PREFIX
+ (propertyName.isEmpty() ? "" : propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1));
try {
return containingClass.getMethod(setterName, propertyType);
} catch (NoSuchMethodException e) {
return null;
}
}
/**
* @param containingClass never null
* @param propertyName never null
* @return null if it doesn't exist
*/
public static Method getSetterMethod(Class<?> containingClass, String propertyName) {
String setterName = PROPERTY_MUTATOR_PREFIX
+ (propertyName.isEmpty() ? "" : propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1));
Method[] methods = Arrays.stream(containingClass.getMethods())
.filter(method -> method.getName().equals(setterName))
.toArray(Method[]::new);
if (methods.length == 0) {
return null;
}
if (methods.length > 1) {
throw new IllegalStateException("The containingClass (" + containingClass
+ ") has multiple setter methods (" + Arrays.toString(methods)
+ ") with the propertyName (" + propertyName + ").");
}
return methods[0];
}
public static boolean isMethodOverwritten(Method parentMethod, Class<?> childClass) {
Method leafMethod;
try {
leafMethod = childClass.getDeclaredMethod(parentMethod.getName(), parentMethod.getParameterTypes());
} catch (NoSuchMethodException e) {
return false;
}
return !leafMethod.getDeclaringClass().equals(parentMethod.getClass());
}
public static void assertGetterMethod(Method getterMethod, Class<? extends Annotation> annotationClass) {
if (getterMethod.getParameterTypes().length != 0) {
throw new IllegalStateException("The getterMethod (" + getterMethod + ") with a "
+ annotationClass.getSimpleName() + " annotation must not have any parameters ("
+ Arrays.toString(getterMethod.getParameterTypes()) + ").");
}
String methodName = getterMethod.getName();
if (methodName.startsWith(PROPERTY_ACCESSOR_PREFIX_GET)) {
if (getterMethod.getReturnType() == void.class) {
throw new IllegalStateException("The getterMethod (" + getterMethod + ") with a "
+ annotationClass.getSimpleName() + " annotation must have a non-void return type ("
+ getterMethod.getReturnType() + ").");
}
} else if (methodName.startsWith(PROPERTY_ACCESSOR_PREFIX_IS)) {
if (getterMethod.getReturnType() != boolean.class) {
throw new IllegalStateException("The getterMethod (" + getterMethod + ") with a "
+ annotationClass.getSimpleName() + " annotation must have a primitive boolean return type ("
+ getterMethod.getReturnType() + ") or use another prefix in its methodName ("
+ methodName + ").\n"
+ "Maybe use '" + PROPERTY_ACCESSOR_PREFIX_GET + "' instead of '" + PROPERTY_ACCESSOR_PREFIX_IS + "'?");
}
} else {
throw new IllegalStateException("The getterMethod (" + getterMethod + ") with a "
+ annotationClass.getSimpleName() + " annotation has a methodName ("
+ methodName + ") that does not start with a valid prefix ("
+ Arrays.toString(PROPERTY_ACCESSOR_PREFIXES) + ").");
}
}
public static void assertReadMethod(Method readMethod, Class<? extends Annotation> annotationClass) {
if (readMethod.getParameterTypes().length != 0) {
throw new IllegalStateException("The readMethod (" + readMethod + ") with a "
+ annotationClass.getSimpleName() + " annotation must not have any parameters ("
+ Arrays.toString(readMethod.getParameterTypes()) + ").");
}
if (readMethod.getReturnType() == void.class) {
throw new IllegalStateException("The readMethod (" + readMethod + ") with a "
+ annotationClass.getSimpleName() + " annotation must have a non-void return type ("
+ readMethod.getReturnType() + ").");
}
}
/**
* @param type never null
* @return true if it is a {@link Map}
*/
public static boolean isMap(Type type) {
if (type instanceof Class class1 && Map.class.isAssignableFrom(class1)) {
return true;
}
if (type instanceof ParameterizedType parameterizedType) {
return isMap(parameterizedType.getRawType());
}
if (type instanceof WildcardType wildcardType) {
Type[] upperBounds = wildcardType.getUpperBounds();
return upperBounds.length != 0 && isMap(upperBounds[0]);
}
return false;
}
/**
* @param type never null
* @return true if it is a {@link List}
*/
public static boolean isList(Type type) {
if (type instanceof Class class1 && List.class.isAssignableFrom(class1)) {
return true;
}
if (type instanceof ParameterizedType parameterizedType) {
return isList(parameterizedType.getRawType());
}
if (type instanceof WildcardType wildcardType) {
Type[] upperBounds = wildcardType.getUpperBounds();
return upperBounds.length != 0 && isList(upperBounds[0]);
}
return false;
}
public static List<Object> transformArrayToList(Object arrayObject) {
if (arrayObject == null) {
return null;
}
int arrayLength = Array.getLength(arrayObject);
List<Object> list = new ArrayList<>(arrayLength);
for (int i = 0; i < arrayLength; i++) {
list.add(Array.get(arrayObject, i));
}
return list;
}
private ReflectionHelper() {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/common | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/common/accessor/MemberAccessorFactory.java | package ai.timefold.solver.core.impl.domain.common.accessor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.solver.SolverFactory;
import ai.timefold.solver.core.impl.domain.common.ReflectionHelper;
import ai.timefold.solver.core.impl.domain.common.accessor.gizmo.GizmoClassLoader;
import ai.timefold.solver.core.impl.domain.common.accessor.gizmo.GizmoMemberAccessorFactory;
public final class MemberAccessorFactory {
// exists only so that the various member accessors can share the same text in their exception messages
static final String CLASSLOADER_NUDGE_MESSAGE =
"Maybe add getClass().getClassLoader() as a parameter to the %s.create...() method call."
.formatted(SolverFactory.class.getSimpleName());
/**
* Creates a new member accessor based on the given parameters.
*
* @param member never null, method or field to access
* @param memberAccessorType
* @param annotationClass the annotation the member was annotated with (used for error reporting)
* @param domainAccessType
* @param classLoader null or {@link GizmoClassLoader} if domainAccessType is {@link DomainAccessType#GIZMO}.
* @return never null, new instance of the member accessor
*/
public static MemberAccessor buildMemberAccessor(Member member, MemberAccessorType memberAccessorType,
Class<? extends Annotation> annotationClass, DomainAccessType domainAccessType, ClassLoader classLoader) {
switch (domainAccessType) {
case GIZMO:
return GizmoMemberAccessorFactory.buildGizmoMemberAccessor(member, annotationClass,
(GizmoClassLoader) Objects.requireNonNull(classLoader));
case REFLECTION:
return buildReflectiveMemberAccessor(member, memberAccessorType, annotationClass);
default:
throw new IllegalStateException("The domainAccessType (" + domainAccessType + ") is not implemented.");
}
}
private static MemberAccessor buildReflectiveMemberAccessor(Member member, MemberAccessorType memberAccessorType,
Class<? extends Annotation> annotationClass) {
if (member instanceof Field field) {
return new ReflectionFieldMemberAccessor(field);
} else if (member instanceof Method method) {
MemberAccessor memberAccessor;
switch (memberAccessorType) {
case FIELD_OR_READ_METHOD:
if (!ReflectionHelper.isGetterMethod(method)) {
ReflectionHelper.assertReadMethod(method, annotationClass);
memberAccessor = new ReflectionMethodMemberAccessor(method);
break;
}
// Intentionally fall through (no break)
case FIELD_OR_GETTER_METHOD:
case FIELD_OR_GETTER_METHOD_WITH_SETTER:
boolean getterOnly = memberAccessorType != MemberAccessorType.FIELD_OR_GETTER_METHOD_WITH_SETTER;
ReflectionHelper.assertGetterMethod(method, annotationClass);
memberAccessor = new ReflectionBeanPropertyMemberAccessor(method, getterOnly);
break;
default:
throw new IllegalStateException("The memberAccessorType (" + memberAccessorType
+ ") is not implemented.");
}
if (memberAccessorType == MemberAccessorType.FIELD_OR_GETTER_METHOD_WITH_SETTER
&& !memberAccessor.supportSetter()) {
throw new IllegalStateException("The class (" + method.getDeclaringClass()
+ ") has a @" + annotationClass.getSimpleName()
+ " annotated getter method (" + method
+ "), but lacks a setter for that property (" + memberAccessor.getName() + ").");
}
return memberAccessor;
} else {
throw new IllegalStateException("Impossible state: the member (" + member + ")'s type is not a "
+ Field.class.getSimpleName() + " or a " + Method.class.getSimpleName() + ".");
}
}
private final Map<String, MemberAccessor> memberAccessorCache;
private final GizmoClassLoader gizmoClassLoader = new GizmoClassLoader();
public MemberAccessorFactory() {
this(null);
}
/**
* Prefills the member accessor cache.
*
* @param memberAccessorMap key is the fully qualified member name
*/
public MemberAccessorFactory(Map<String, MemberAccessor> memberAccessorMap) {
// The MemberAccessorFactory may be accessed, and this cache both read and updated, by multiple threads.
this.memberAccessorCache =
memberAccessorMap == null ? new ConcurrentHashMap<>() : new ConcurrentHashMap<>(memberAccessorMap);
}
/**
* Creates a new member accessor based on the given parameters. Caches the result.
*
* @param member never null, method or field to access
* @param memberAccessorType
* @param annotationClass the annotation the member was annotated with (used for error reporting)
* @param domainAccessType
* @return never null, new {@link MemberAccessor} instance unless already found in memberAccessorMap
*/
public MemberAccessor buildAndCacheMemberAccessor(Member member, MemberAccessorType memberAccessorType,
Class<? extends Annotation> annotationClass, DomainAccessType domainAccessType) {
String generatedClassName = GizmoMemberAccessorFactory.getGeneratedClassName(member);
return memberAccessorCache.computeIfAbsent(generatedClassName,
k -> MemberAccessorFactory.buildMemberAccessor(member, memberAccessorType, annotationClass, domainAccessType,
gizmoClassLoader));
}
public GizmoClassLoader getGizmoClassLoader() {
return gizmoClassLoader;
}
public enum MemberAccessorType {
FIELD_OR_READ_METHOD,
FIELD_OR_GETTER_METHOD,
FIELD_OR_GETTER_METHOD_WITH_SETTER
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/common | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/common/accessor/ReflectionBeanPropertyMemberAccessor.java | package ai.timefold.solver.core.impl.domain.common.accessor;
import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import ai.timefold.solver.core.impl.domain.common.ReflectionHelper;
/**
* A {@link MemberAccessor} based on a getter and optionally a setter.
*/
public final class ReflectionBeanPropertyMemberAccessor extends AbstractMemberAccessor {
private final Class<?> propertyType;
private final String propertyName;
private final Method getterMethod;
private final MethodHandle getherMethodHandle;
private final Method setterMethod;
private final MethodHandle setterMethodHandle;
public ReflectionBeanPropertyMemberAccessor(Method getterMethod) {
this(getterMethod, false);
}
public ReflectionBeanPropertyMemberAccessor(Method getterMethod, boolean getterOnly) {
this.getterMethod = getterMethod;
MethodHandles.Lookup lookup = MethodHandles.lookup();
try {
getterMethod.setAccessible(true); // Performance hack by avoiding security checks
this.getherMethodHandle = lookup.unreflect(getterMethod)
.asFixedArity();
} catch (IllegalAccessException e) {
throw new IllegalStateException("""
Impossible state: method (%s) not accessible.
%s
"""
.strip()
.formatted(getterMethod, MemberAccessorFactory.CLASSLOADER_NUDGE_MESSAGE), e);
}
Class<?> declaringClass = getterMethod.getDeclaringClass();
if (!ReflectionHelper.isGetterMethod(getterMethod)) {
throw new IllegalArgumentException("The getterMethod (" + getterMethod + ") is not a valid getter.");
}
propertyType = getterMethod.getReturnType();
propertyName = ReflectionHelper.getGetterPropertyName(getterMethod);
if (getterOnly) {
setterMethod = null;
setterMethodHandle = null;
} else {
setterMethod = ReflectionHelper.getSetterMethod(declaringClass, getterMethod.getReturnType(), propertyName);
if (setterMethod != null) {
try {
setterMethod.setAccessible(true); // Performance hack by avoiding security checks
this.setterMethodHandle = lookup.unreflect(setterMethod)
.asFixedArity();
} catch (IllegalAccessException e) {
throw new IllegalStateException("""
Impossible state: method (%s) not accessible.
%s
"""
.strip()
.formatted(setterMethod, MemberAccessorFactory.CLASSLOADER_NUDGE_MESSAGE), e);
}
} else {
setterMethodHandle = null;
}
}
}
@Override
public Class<?> getDeclaringClass() {
return getterMethod.getDeclaringClass();
}
@Override
public String getName() {
return propertyName;
}
@Override
public Class<?> getType() {
return propertyType;
}
@Override
public Type getGenericType() {
return getterMethod.getGenericReturnType();
}
@Override
public Object executeGetter(Object bean) {
if (bean == null) {
throw new IllegalArgumentException("Requested property (%s) getterMethod (%s) on a null bean."
.formatted(propertyName, getterMethod));
}
try {
return getherMethodHandle.invoke(bean);
} catch (Throwable e) {
throw new IllegalStateException("The property (%s) getterMethod (%s) on bean of class (%s) throws an exception."
.formatted(propertyName, getterMethod, bean.getClass()), e);
}
}
@Override
public boolean supportSetter() {
return setterMethod != null;
}
@Override
public void executeSetter(Object bean, Object value) {
if (bean == null) {
throw new IllegalArgumentException("Requested property (%s) setterMethod (%s) on a null bean."
.formatted(propertyName, setterMethod));
}
try {
setterMethodHandle.invoke(bean, value);
} catch (Throwable e) {
throw new IllegalStateException("The property (%s) setterMethod (%s) on bean of class (%s) throws an exception."
.formatted(propertyName, setterMethod, bean.getClass()), e);
}
}
@Override
public String getSpeedNote() {
return "MethodHandle";
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
return getterMethod.getAnnotation(annotationClass);
}
@Override
public <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
return getterMethod.getDeclaredAnnotationsByType(annotationClass);
}
@Override
public String toString() {
return "bean property " + propertyName + " on " + getterMethod.getDeclaringClass();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/common | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/common/accessor/ReflectionFieldMemberAccessor.java | package ai.timefold.solver.core.impl.domain.common.accessor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
/**
* A {@link MemberAccessor} based on a field.
*/
public final class ReflectionFieldMemberAccessor extends AbstractMemberAccessor {
private final Field field;
public ReflectionFieldMemberAccessor(Field field) {
this.field = field;
// Performance hack by avoiding security checks
field.setAccessible(true);
}
@Override
public Class<?> getDeclaringClass() {
return field.getDeclaringClass();
}
@Override
public String getName() {
return field.getName();
}
@Override
public Class<?> getType() {
return field.getType();
}
@Override
public Type getGenericType() {
return field.getGenericType();
}
@Override
public Object executeGetter(Object bean) {
if (bean == null) {
throw new IllegalArgumentException("Requested field (%s) on a null bean."
.formatted(field));
}
try {
return field.get(bean);
} catch (IllegalAccessException e) {
throw new IllegalStateException("""
Cannot get the field (%s) on bean of class (%s).
%s"""
.formatted(field.getName(), bean.getClass(), MemberAccessorFactory.CLASSLOADER_NUDGE_MESSAGE),
e);
}
}
@Override
public boolean supportSetter() {
return true;
}
@Override
public void executeSetter(Object bean, Object value) {
if (bean == null) {
throw new IllegalArgumentException("Requested field (%s) on a null bean."
.formatted(field));
}
try {
field.set(bean, value);
} catch (IllegalAccessException e) {
throw new IllegalStateException("""
Cannot set the field (%s) on bean of class (%s).
%s"""
.formatted(field.getName(), bean.getClass(), MemberAccessorFactory.CLASSLOADER_NUDGE_MESSAGE),
e);
}
}
@Override
public String getSpeedNote() {
return "reflection";
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
return field.getAnnotation(annotationClass);
}
@Override
public <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
return field.getDeclaredAnnotationsByType(annotationClass);
}
@Override
public String toString() {
return "field " + field;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/common | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/common/accessor/ReflectionMethodMemberAccessor.java | package ai.timefold.solver.core.impl.domain.common.accessor;
import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Arrays;
/**
* A {@link MemberAccessor} based on a single read {@link Method}.
* Do not confuse with {@link ReflectionBeanPropertyMemberAccessor} which is richer.
*/
public final class ReflectionMethodMemberAccessor extends AbstractMemberAccessor {
private final Class<?> returnType;
private final String methodName;
private final Method readMethod;
private final MethodHandle methodHandle;
public ReflectionMethodMemberAccessor(Method readMethod) {
this.readMethod = readMethod;
this.returnType = readMethod.getReturnType();
this.methodName = readMethod.getName();
try {
readMethod.setAccessible(true);
this.methodHandle = MethodHandles.lookup()
.unreflect(readMethod)
.asFixedArity();
} catch (IllegalAccessException e) {
throw new IllegalStateException("""
Impossible state: Method (%s) not accessible.
%s
""".formatted(readMethod, MemberAccessorFactory.CLASSLOADER_NUDGE_MESSAGE), e);
}
if (readMethod.getParameterTypes().length != 0) {
throw new IllegalArgumentException("The readMethod (" + readMethod + ") must not have any parameters ("
+ Arrays.toString(readMethod.getParameterTypes()) + ").");
}
if (readMethod.getReturnType() == void.class) {
throw new IllegalArgumentException("The readMethod (" + readMethod + ") must have a return type ("
+ readMethod.getReturnType() + ").");
}
}
@Override
public Class<?> getDeclaringClass() {
return readMethod.getDeclaringClass();
}
@Override
public String getName() {
return methodName;
}
@Override
public Class<?> getType() {
return returnType;
}
@Override
public Type getGenericType() {
return readMethod.getGenericReturnType();
}
@Override
public Object executeGetter(Object bean) {
try {
return methodHandle.invoke(bean);
} catch (Throwable e) {
throw new IllegalStateException("The property (%s) getterMethod (%s) on bean of class (%s) throws an exception."
.formatted(methodName, readMethod, bean.getClass()), e);
}
}
@Override
public String getSpeedNote() {
return "MethodHandle";
}
@Override
public boolean supportSetter() {
return false;
}
@Override
public void executeSetter(Object bean, Object value) {
throw new UnsupportedOperationException();
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
return readMethod.getAnnotation(annotationClass);
}
@Override
public <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
return readMethod.getDeclaredAnnotationsByType(annotationClass);
}
@Override
public String toString() {
return "method " + methodName + " on " + readMethod.getDeclaringClass();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/common/accessor | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/common/accessor/gizmo/GizmoMemberAccessorFactory.java | package ai.timefold.solver.core.impl.domain.common.accessor.gizmo;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.impl.domain.common.ReflectionHelper;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
public class GizmoMemberAccessorFactory {
/**
* Returns the generated class name for a given member.
* (Here as accessing any method of GizmoMemberAccessorImplementor
* will try to load Gizmo code)
*
* @param member The member to get the generated class name for
* @return The generated class name for member
*/
public static String getGeneratedClassName(Member member) {
String memberName = Objects.requireNonNullElse(ReflectionHelper.getGetterPropertyName(member), member.getName());
String memberType = (member instanceof Field) ? "Field" : "Method";
return member.getDeclaringClass().getName() + "$Timefold$MemberAccessor$" + memberType + "$" + memberName;
}
public static MemberAccessor buildGizmoMemberAccessor(Member member, Class<? extends Annotation> annotationClass,
GizmoClassLoader gizmoClassLoader) {
try {
// Check if Gizmo on the classpath by verifying we can access one of its classes
Class.forName("io.quarkus.gizmo.ClassCreator", false,
Thread.currentThread().getContextClassLoader());
} catch (ClassNotFoundException e) {
throw new IllegalStateException("When using the domainAccessType (" +
DomainAccessType.GIZMO +
") the classpath or modulepath must contain io.quarkus.gizmo:gizmo.\n" +
"Maybe add a dependency to io.quarkus.gizmo:gizmo.");
}
return GizmoMemberAccessorImplementor.createAccessorFor(member, annotationClass, gizmoClassLoader);
}
private GizmoMemberAccessorFactory() {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/common/accessor | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/common/accessor/gizmo/GizmoMemberAccessorImplementor.java | package ai.timefold.solver.core.impl.domain.common.accessor.gizmo;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.util.MutableReference;
import io.quarkus.gizmo.ClassCreator;
import io.quarkus.gizmo.ClassOutput;
import io.quarkus.gizmo.FieldDescriptor;
import io.quarkus.gizmo.MethodCreator;
import io.quarkus.gizmo.MethodDescriptor;
import io.quarkus.gizmo.ResultHandle;
/**
* Generates the bytecode for the MemberAccessor of a particular Member
*/
public final class GizmoMemberAccessorImplementor {
final static String GENERIC_TYPE_FIELD = "genericType";
final static String ANNOTATED_ELEMENT_FIELD = "annotatedElement";
/**
* Generates the constructor and implementations of {@link AbstractGizmoMemberAccessor} methods for the given
* {@link Member}.
*
* @param className never null
* @param classOutput never null, defines how to write the bytecode
* @param memberInfo never null, member to generate MemberAccessor methods implementation for
*/
public static void defineAccessorFor(String className, ClassOutput classOutput, GizmoMemberInfo memberInfo) {
Class<? extends AbstractGizmoMemberAccessor> superClass = getCorrectSuperclass(memberInfo);
try (ClassCreator classCreator = ClassCreator.builder()
.className(className)
.superClass(superClass)
.classOutput(classOutput)
.setFinal(true)
.build()) {
classCreator.getFieldCreator("genericType", Type.class)
.setModifiers(Modifier.FINAL);
classCreator.getFieldCreator("annotatedElement", AnnotatedElement.class)
.setModifiers(Modifier.FINAL);
// ************************************************************************
// MemberAccessor methods
// ************************************************************************
createConstructor(classCreator, memberInfo);
createGetDeclaringClass(classCreator, memberInfo);
createGetType(classCreator, memberInfo);
createGetGenericType(classCreator);
createGetName(classCreator, memberInfo);
createExecuteGetter(classCreator, memberInfo);
if (superClass == AbstractReadWriteGizmoMemberAccessor.class) {
createExecuteSetter(classCreator, memberInfo);
}
createGetAnnotation(classCreator);
createDeclaredAnnotationsByType(classCreator);
}
}
private static Class<? extends AbstractGizmoMemberAccessor> getCorrectSuperclass(GizmoMemberInfo memberInfo) {
AtomicBoolean supportsSetter = new AtomicBoolean();
memberInfo.getDescriptor().whenIsMethod(method -> {
supportsSetter.set(memberInfo.getDescriptor().getSetter().isPresent());
});
memberInfo.getDescriptor().whenIsField(field -> {
supportsSetter.set(true);
});
if (supportsSetter.get()) {
return AbstractReadWriteGizmoMemberAccessor.class;
} else {
return AbstractReadOnlyGizmoMemberAccessor.class;
}
}
/**
* Creates a MemberAccessor for a given member, generating
* the MemberAccessor bytecode if required
*
* @param member The member to generate a MemberAccessor for
* @param annotationClass The annotation it was annotated with (used for
* error reporting)
* @param gizmoClassLoader never null
* @return A new MemberAccessor that uses Gizmo generated bytecode.
* Will generate the bytecode the first type it is called
* for a member, unless a classloader has been set,
* in which case no Gizmo code will be generated.
*/
static MemberAccessor createAccessorFor(Member member, Class<? extends Annotation> annotationClass,
GizmoClassLoader gizmoClassLoader) {
String className = GizmoMemberAccessorFactory.getGeneratedClassName(member);
if (gizmoClassLoader.hasBytecodeFor(className)) {
return createInstance(className, gizmoClassLoader);
}
final MutableReference<byte[]> classBytecodeHolder = new MutableReference<>(null);
ClassOutput classOutput = (path, byteCode) -> classBytecodeHolder.setValue(byteCode);
GizmoMemberInfo memberInfo = new GizmoMemberInfo(new GizmoMemberDescriptor(member), annotationClass);
defineAccessorFor(className, classOutput, memberInfo);
byte[] classBytecode = classBytecodeHolder.getValue();
gizmoClassLoader.storeBytecode(className, classBytecode);
return createInstance(className, gizmoClassLoader);
}
private static MemberAccessor createInstance(String className, GizmoClassLoader gizmoClassLoader) {
try {
return (MemberAccessor) gizmoClassLoader.loadClass(className)
.getConstructor().newInstance();
} catch (InvocationTargetException | InstantiationException | IllegalAccessException | ClassNotFoundException
| NoSuchMethodException e) {
throw new IllegalStateException(e);
}
}
// ************************************************************************
// MemberAccessor methods
// ************************************************************************
private static MethodCreator getMethodCreator(ClassCreator classCreator, Class<?> returnType, String methodName,
Class<?>... parameters) {
return classCreator.getMethodCreator(methodName, returnType, parameters);
}
private static void createConstructor(ClassCreator classCreator, GizmoMemberInfo memberInfo) {
MethodCreator methodCreator =
classCreator.getMethodCreator(MethodDescriptor.ofConstructor(classCreator.getClassName()));
ResultHandle thisObj = methodCreator.getThis();
// Invoke Object's constructor
methodCreator.invokeSpecialMethod(MethodDescriptor.ofConstructor(classCreator.getSuperClass()), thisObj);
ResultHandle declaringClass = methodCreator.loadClass(memberInfo.getDescriptor().getDeclaringClassName());
memberInfo.getDescriptor().whenMetadataIsOnField(fd -> {
ResultHandle name = methodCreator.load(fd.getName());
ResultHandle field = methodCreator.invokeVirtualMethod(MethodDescriptor.ofMethod(Class.class, "getDeclaredField",
Field.class, String.class),
declaringClass, name);
ResultHandle type =
methodCreator.invokeVirtualMethod(MethodDescriptor.ofMethod(Field.class, "getGenericType", Type.class),
field);
methodCreator.writeInstanceField(FieldDescriptor.of(classCreator.getClassName(), GENERIC_TYPE_FIELD, Type.class),
thisObj, type);
methodCreator.writeInstanceField(
FieldDescriptor.of(classCreator.getClassName(), ANNOTATED_ELEMENT_FIELD, AnnotatedElement.class),
thisObj, field);
});
memberInfo.getDescriptor().whenMetadataIsOnMethod(md -> {
ResultHandle name = methodCreator.load(md.getName());
ResultHandle method = methodCreator.invokeVirtualMethod(MethodDescriptor.ofMethod(Class.class, "getDeclaredMethod",
Method.class, String.class, Class[].class),
declaringClass, name,
methodCreator.newArray(Class.class, 0));
ResultHandle type =
methodCreator.invokeVirtualMethod(
MethodDescriptor.ofMethod(Method.class, "getGenericReturnType", Type.class),
method);
methodCreator.writeInstanceField(FieldDescriptor.of(classCreator.getClassName(), GENERIC_TYPE_FIELD, Type.class),
thisObj, type);
methodCreator.writeInstanceField(
FieldDescriptor.of(classCreator.getClassName(), ANNOTATED_ELEMENT_FIELD, AnnotatedElement.class),
thisObj, method);
});
// Return this (it a constructor)
methodCreator.returnValue(thisObj);
}
/**
* Generates the following code:
*
* <pre>
* Class getDeclaringClass() {
* return ClassThatDeclaredMember.class;
* }
* </pre>
*/
private static void createGetDeclaringClass(ClassCreator classCreator, GizmoMemberInfo memberInfo) {
MethodCreator methodCreator = getMethodCreator(classCreator, Class.class, "getDeclaringClass");
ResultHandle out = methodCreator.loadClass(memberInfo.getDescriptor().getDeclaringClassName());
methodCreator.returnValue(out);
}
/**
* Asserts method is a getter or read method
*
* @param method Method to assert is getter or read
* @param annotationClass Used in exception message
*/
private static void assertIsGoodMethod(MethodDescriptor method, Class<? extends Annotation> annotationClass) {
// V = void return type
// Z = primitive boolean return type
String methodName = method.getName();
if (method.getParameterTypes().length != 0) {
// not read or getter method
throw new IllegalStateException("The getterMethod (" + methodName + ") with a "
+ annotationClass.getSimpleName() + " annotation must not have any parameters, but has parameters ("
+ Arrays.toString(method.getParameterTypes()) + ").");
}
if (methodName.startsWith("get")) {
if (method.getReturnType().equals("V")) {
throw new IllegalStateException("The getterMethod (" + methodName + ") with a "
+ annotationClass.getSimpleName() + " annotation must have a non-void return type.");
}
} else if (methodName.startsWith("is")) {
if (!method.getReturnType().equals("Z")) {
throw new IllegalStateException("The getterMethod (" + methodName + ") with a "
+ annotationClass.getSimpleName()
+ " annotation must have a primitive boolean return type but returns ("
+ method.getReturnType() + "). Maybe rename the method ("
+ "get" + methodName.substring(2) + ")?");
}
} else {
// must be a read method
if (method.getReturnType().equals("V")) {
throw new IllegalStateException("The readMethod (" + methodName + ") with a "
+ annotationClass.getSimpleName() + " annotation must have a non-void return type.");
}
}
}
/**
* Generates the following code:
*
* <pre>
* String getName() {
* return "fieldOrMethodName";
* }
* </pre>
*
* If it is a getter method, "get" is removed and the first
* letter become lowercase
*/
private static void createGetName(ClassCreator classCreator, GizmoMemberInfo memberInfo) {
MethodCreator methodCreator = getMethodCreator(classCreator, String.class, "getName");
// If it is a method, assert that it has the required
// properties
memberInfo.getDescriptor().whenIsMethod(method -> {
assertIsGoodMethod(method, memberInfo.getAnnotationClass());
});
String fieldName = memberInfo.getDescriptor().getName();
ResultHandle out = methodCreator.load(fieldName);
methodCreator.returnValue(out);
}
/**
* Generates the following code:
*
* <pre>
* Class getType() {
* return FieldTypeOrMethodReturnType.class;
* }
* </pre>
*/
private static void createGetType(ClassCreator classCreator, GizmoMemberInfo memberInfo) {
MethodCreator methodCreator = getMethodCreator(classCreator, Class.class, "getType");
ResultHandle out = methodCreator.loadClass(memberInfo.getDescriptor().getTypeName());
methodCreator.returnValue(out);
}
/**
* Generates the following code:
*
* <pre>
* Type getGenericType() {
* return GizmoMemberAccessorImplementor.getGenericTypeFor(this.getClass().getName());
* }
* </pre>
*
* We are unable to load a non-primitive object constant, so we need to store it
* in the implementor, which then can return us the Type when needed. The type
* is stored in gizmoMemberAccessorNameToGenericType when this method is called.
*/
private static void createGetGenericType(ClassCreator classCreator) {
MethodCreator methodCreator = getMethodCreator(classCreator, Type.class, "getGenericType");
ResultHandle thisObj = methodCreator.getThis();
ResultHandle out =
methodCreator.readInstanceField(FieldDescriptor.of(classCreator.getClassName(), GENERIC_TYPE_FIELD, Type.class),
thisObj);
methodCreator.returnValue(out);
}
/**
* Generates the following code:
*
* For a field
*
* <pre>
* Object executeGetter(Object bean) {
* return ((DeclaringClass) bean).field;
* }
* </pre>
*
* For a method
*
* <pre>
* Object executeGetter(Object bean) {
* return ((DeclaringClass) bean).method();
* }
* </pre>
*
* The member MUST be public if not called in Quarkus
* (i.e. we don't delegate to the field getter/setter).
* In Quarkus, we generate simple getter/setter for the
* member if it is private (which get passed to the MemberDescriptor).
*/
private static void createExecuteGetter(ClassCreator classCreator, GizmoMemberInfo memberInfo) {
MethodCreator methodCreator = getMethodCreator(classCreator, Object.class, "executeGetter", Object.class);
ResultHandle bean = methodCreator.getMethodParam(0);
methodCreator.returnValue(memberInfo.getDescriptor().readMemberValue(methodCreator, bean));
}
/**
* Generates the following code:
*
* For a field
*
* <pre>
* void executeSetter(Object bean, Object value) {
* return ((DeclaringClass) bean).field = value;
* }
* </pre>
*
* For a getter method with a corresponding setter
*
* <pre>
* void executeSetter(Object bean, Object value) {
* return ((DeclaringClass) bean).setValue(value);
* }
* </pre>
*
* For a read method or a getter method without a setter
*
* <pre>
* void executeSetter(Object bean, Object value) {
* throw new UnsupportedOperationException("Setter not supported");
* }
* </pre>
*/
private static void createExecuteSetter(ClassCreator classCreator, GizmoMemberInfo memberInfo) {
MethodCreator methodCreator = getMethodCreator(classCreator, void.class, "executeSetter", Object.class,
Object.class);
ResultHandle bean = methodCreator.getMethodParam(0);
ResultHandle value = methodCreator.getMethodParam(1);
if (memberInfo.getDescriptor().writeMemberValue(methodCreator, bean, value)) {
// we are here only if the write is successful
methodCreator.returnValue(null);
} else {
methodCreator.throwException(UnsupportedOperationException.class, "Setter not supported");
}
}
private static MethodCreator getAnnotationMethodCreator(ClassCreator classCreator, Class<?> returnType, String methodName,
Class<?>... parameters) {
return classCreator.getMethodCreator(getAnnotationMethod(returnType, methodName, parameters));
}
private static MethodDescriptor getAnnotationMethod(Class<?> returnType, String methodName, Class<?>... parameters) {
return MethodDescriptor.ofMethod(AnnotatedElement.class, methodName, returnType, parameters);
}
/**
* Generates the following code:
*
* <pre>
* Object getAnnotation(Class annotationClass) {
* AnnotatedElement annotatedElement = GizmoMemberAccessorImplementor
* .getAnnotatedElementFor(this.getClass().getName());
* return annotatedElement.getAnnotation(annotationClass);
* }
* </pre>
*/
private static void createGetAnnotation(ClassCreator classCreator) {
MethodCreator methodCreator = getAnnotationMethodCreator(classCreator, Annotation.class, "getAnnotation", Class.class);
ResultHandle thisObj = methodCreator.getThis();
ResultHandle annotatedElement = methodCreator.readInstanceField(
FieldDescriptor.of(classCreator.getClassName(), ANNOTATED_ELEMENT_FIELD, AnnotatedElement.class),
thisObj);
ResultHandle query = methodCreator.getMethodParam(0);
ResultHandle out =
methodCreator.invokeInterfaceMethod(getAnnotationMethod(Annotation.class, "getAnnotation", Class.class),
annotatedElement, query);
methodCreator.returnValue(out);
}
private static void createDeclaredAnnotationsByType(ClassCreator classCreator) {
MethodCreator methodCreator =
getAnnotationMethodCreator(classCreator, Annotation[].class, "getDeclaredAnnotationsByType", Class.class);
ResultHandle thisObj = methodCreator.getThis();
ResultHandle annotatedElement = methodCreator.readInstanceField(
FieldDescriptor.of(classCreator.getClassName(), ANNOTATED_ELEMENT_FIELD, AnnotatedElement.class),
thisObj);
ResultHandle query = methodCreator.getMethodParam(0);
ResultHandle out = methodCreator.invokeInterfaceMethod(
getAnnotationMethod(Annotation[].class, "getDeclaredAnnotationsByType", Class.class),
annotatedElement, query);
methodCreator.returnValue(out);
}
private GizmoMemberAccessorImplementor() {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/common/accessor | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/common/accessor/gizmo/GizmoMemberInfo.java | package ai.timefold.solver.core.impl.domain.common.accessor.gizmo;
import java.lang.annotation.Annotation;
public final class GizmoMemberInfo {
private final GizmoMemberDescriptor descriptor;
private final Class<? extends Annotation> annotationClass;
public GizmoMemberInfo(GizmoMemberDescriptor descriptor, Class<? extends Annotation> annotationClass) {
this.descriptor = descriptor;
this.annotationClass = annotationClass;
}
public GizmoMemberDescriptor getDescriptor() {
return descriptor;
}
public Class<? extends Annotation> getAnnotationClass() {
return annotationClass;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/constraintweight | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/constraintweight/descriptor/ConstraintConfigurationDescriptor.java | package ai.timefold.solver.core.impl.domain.constraintweight.descriptor;
import static ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory.MemberAccessorType.FIELD_OR_READ_METHOD;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import ai.timefold.solver.core.api.domain.constraintweight.ConstraintConfiguration;
import ai.timefold.solver.core.api.domain.constraintweight.ConstraintConfigurationProvider;
import ai.timefold.solver.core.api.domain.constraintweight.ConstraintWeight;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.constraint.ConstraintRef;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.common.ReflectionHelper;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class ConstraintConfigurationDescriptor<Solution_> {
private final SolutionDescriptor<Solution_> solutionDescriptor;
private final Class<?> constraintConfigurationClass;
private String constraintPackage;
private final Map<String, ConstraintWeightDescriptor<Solution_>> constraintWeightDescriptorMap;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public ConstraintConfigurationDescriptor(SolutionDescriptor<Solution_> solutionDescriptor,
Class<?> constraintConfigurationClass) {
this.solutionDescriptor = solutionDescriptor;
this.constraintConfigurationClass = constraintConfigurationClass;
constraintWeightDescriptorMap = new LinkedHashMap<>();
}
public String getConstraintPackage() {
return constraintPackage;
}
public ConstraintWeightDescriptor<Solution_> getConstraintWeightDescriptor(String propertyName) {
return constraintWeightDescriptorMap.get(propertyName);
}
// ************************************************************************
// Lifecycle methods
// ************************************************************************
public void processAnnotations(DescriptorPolicy descriptorPolicy,
ScoreDefinition scoreDefinition) {
processPackAnnotation(descriptorPolicy);
ArrayList<Method> potentiallyOverwritingMethodList = new ArrayList<>();
// Iterate inherited members too (unlike for EntityDescriptor where each one is declared)
// to make sure each one is registered
for (Class<?> lineageClass : ConfigUtils.getAllAnnotatedLineageClasses(constraintConfigurationClass,
ConstraintConfiguration.class)) {
List<Member> memberList = ConfigUtils.getDeclaredMembers(lineageClass);
for (Member member : memberList) {
if (member instanceof Method method && potentiallyOverwritingMethodList.stream().anyMatch(
m -> member.getName().equals(m.getName()) // Shortcut to discard negatives faster
&& ReflectionHelper.isMethodOverwritten(method, m.getDeclaringClass()))) {
// Ignore member because it is an overwritten method
continue;
}
processParameterAnnotation(descriptorPolicy, member, scoreDefinition);
}
potentiallyOverwritingMethodList.ensureCapacity(potentiallyOverwritingMethodList.size() + memberList.size());
memberList.stream().filter(member -> member instanceof Method)
.forEach(member -> potentiallyOverwritingMethodList.add((Method) member));
}
if (constraintWeightDescriptorMap.isEmpty()) {
throw new IllegalStateException("The constraintConfigurationClass (" + constraintConfigurationClass
+ ") must have at least 1 member with a "
+ ConstraintWeight.class.getSimpleName() + " annotation.");
}
}
private void processPackAnnotation(DescriptorPolicy descriptorPolicy) {
ConstraintConfiguration packAnnotation = constraintConfigurationClass.getAnnotation(ConstraintConfiguration.class);
if (packAnnotation == null) {
throw new IllegalStateException("The constraintConfigurationClass (" + constraintConfigurationClass
+ ") has been specified as a @" + ConstraintConfigurationProvider.class.getSimpleName()
+ " in the solution class (" + solutionDescriptor.getSolutionClass() + ")," +
" but does not have a @" + ConstraintConfiguration.class.getSimpleName() + " annotation.");
}
// If a @ConstraintConfiguration extends a @ConstraintConfiguration, their constraintPackage might differ.
// So the ConstraintWeightDescriptors parse packAnnotation.constraintPackage() themselves.
constraintPackage = packAnnotation.constraintPackage();
if (constraintPackage.isEmpty()) {
Package pack = constraintConfigurationClass.getPackage();
constraintPackage = (pack == null) ? "" : pack.getName();
}
}
private void processParameterAnnotation(DescriptorPolicy descriptorPolicy, Member member,
ScoreDefinition scoreDefinition) {
if (((AnnotatedElement) member).isAnnotationPresent(ConstraintWeight.class)) {
MemberAccessor memberAccessor = descriptorPolicy.getMemberAccessorFactory().buildAndCacheMemberAccessor(member,
FIELD_OR_READ_METHOD, ConstraintWeight.class, descriptorPolicy.getDomainAccessType());
if (constraintWeightDescriptorMap.containsKey(memberAccessor.getName())) {
MemberAccessor duplicate = constraintWeightDescriptorMap.get(memberAccessor.getName()).getMemberAccessor();
throw new IllegalStateException("The constraintConfigurationClass (" + constraintConfigurationClass
+ ") has a @" + ConstraintWeight.class.getSimpleName()
+ " annotated member (" + memberAccessor
+ ") that is duplicated by a member (" + duplicate + ").\n"
+ "Maybe the annotation is defined on both the field and its getter.");
}
if (!scoreDefinition.getScoreClass().isAssignableFrom(memberAccessor.getType())) {
throw new IllegalStateException("The constraintConfigurationClass (" + constraintConfigurationClass
+ ") has a @" + ConstraintWeight.class.getSimpleName()
+ " annotated member (" + memberAccessor
+ ") with a return type (" + memberAccessor.getType()
+ ") that is not assignable to the score class (" + scoreDefinition.getScoreClass() + ").\n"
+ "Maybe make that member (" + memberAccessor.getName() + ") return the score class ("
+ scoreDefinition.getScoreClass().getSimpleName() + ") instead.");
}
ConstraintWeightDescriptor<Solution_> constraintWeightDescriptor = new ConstraintWeightDescriptor<>(this,
memberAccessor);
constraintWeightDescriptorMap.put(memberAccessor.getName(), constraintWeightDescriptor);
}
}
// ************************************************************************
// Worker methods
// ************************************************************************
public SolutionDescriptor<Solution_> getSolutionDescriptor() {
return solutionDescriptor;
}
public Class<?> getConstraintConfigurationClass() {
return constraintConfigurationClass;
}
public ConstraintWeightDescriptor<Solution_> findConstraintWeightDescriptor(ConstraintRef constraintRef) {
return constraintWeightDescriptorMap.values().stream()
.filter(constraintWeightDescriptor -> constraintWeightDescriptor.getConstraintRef().equals(constraintRef))
.findFirst()
.orElse(null);
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + constraintConfigurationClass.getName() + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/constraintweight | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/constraintweight/descriptor/ConstraintWeightDescriptor.java | package ai.timefold.solver.core.impl.domain.constraintweight.descriptor;
import java.util.Objects;
import java.util.function.Function;
import ai.timefold.solver.core.api.domain.constraintweight.ConstraintConfiguration;
import ai.timefold.solver.core.api.domain.constraintweight.ConstraintWeight;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintRef;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class ConstraintWeightDescriptor<Solution_> {
private final ConstraintConfigurationDescriptor<Solution_> constraintConfigurationDescriptor;
private final ConstraintRef constraintRef;
private final MemberAccessor memberAccessor;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public ConstraintWeightDescriptor(ConstraintConfigurationDescriptor<Solution_> constraintConfigurationDescriptor,
MemberAccessor memberAccessor) {
this.constraintConfigurationDescriptor = constraintConfigurationDescriptor;
ConstraintWeight constraintWeightAnnotation = memberAccessor.getAnnotation(ConstraintWeight.class);
String constraintPackage = constraintWeightAnnotation.constraintPackage();
if (constraintPackage.isEmpty()) {
// If a @ConstraintConfiguration extends a @ConstraintConfiguration, their constraintPackage might differ.
ConstraintConfiguration constraintConfigurationAnnotation = memberAccessor.getDeclaringClass()
.getAnnotation(ConstraintConfiguration.class);
if (constraintConfigurationAnnotation == null) {
throw new IllegalStateException("Impossible state: " + ConstraintConfigurationDescriptor.class.getSimpleName()
+ " only reflects over members with a @" + ConstraintConfiguration.class.getSimpleName()
+ " annotation.");
}
constraintPackage = constraintConfigurationAnnotation.constraintPackage();
if (constraintPackage.isEmpty()) {
Package pack = memberAccessor.getDeclaringClass().getPackage();
constraintPackage = (pack == null) ? "" : pack.getName();
}
}
this.constraintRef = ConstraintRef.of(constraintPackage, constraintWeightAnnotation.value());
this.memberAccessor = memberAccessor;
}
public ConstraintRef getConstraintRef() {
return constraintRef;
}
public MemberAccessor getMemberAccessor() {
return memberAccessor;
}
public Function<Solution_, Score<?>> createExtractor() {
SolutionDescriptor<Solution_> solutionDescriptor = constraintConfigurationDescriptor.getSolutionDescriptor();
MemberAccessor constraintConfigurationMemberAccessor = solutionDescriptor.getConstraintConfigurationMemberAccessor();
return (Solution_ solution) -> {
Object constraintConfiguration = Objects.requireNonNull(
constraintConfigurationMemberAccessor.executeGetter(solution),
"Constraint configuration provider (" + constraintConfigurationMemberAccessor +
") returns null.");
return (Score<?>) memberAccessor.executeGetter(constraintConfiguration);
};
}
@Override
public String toString() {
return constraintRef.toString();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/entity | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/entity/descriptor/EntityDescriptor.java | package ai.timefold.solver.core.impl.domain.entity.descriptor;
import static ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory.MemberAccessorType.FIELD_OR_GETTER_METHOD;
import static ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory.MemberAccessorType.FIELD_OR_GETTER_METHOD_WITH_SETTER;
import static ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory.MemberAccessorType.FIELD_OR_READ_METHOD;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Member;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Predicate;
import ai.timefold.solver.core.api.domain.entity.PinningFilter;
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.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.api.domain.variable.AnchorShadowVariable;
import ai.timefold.solver.core.api.domain.variable.CustomShadowVariable;
import ai.timefold.solver.core.api.domain.variable.IndexShadowVariable;
import ai.timefold.solver.core.api.domain.variable.InverseRelationShadowVariable;
import ai.timefold.solver.core.api.domain.variable.NextElementShadowVariable;
import ai.timefold.solver.core.api.domain.variable.PiggybackShadowVariable;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
import ai.timefold.solver.core.api.domain.variable.PreviousElementShadowVariable;
import ai.timefold.solver.core.api.domain.variable.ShadowVariable;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.config.heuristic.selector.common.decorator.SelectionSorterOrder;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.common.ReflectionHelper;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory;
import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy;
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.variable.anchor.AnchorShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.custom.CustomShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.custom.LegacyCustomShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.custom.PiggybackShadowVariableDescriptor;
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.ShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.index.IndexShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.InverseRelationShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.nextprev.NextElementShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.nextprev.PreviousElementShadowVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.ComparatorSelectionSorter;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionSorter;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionSorterWeightFactory;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.WeightFactorySelectionSorter;
import ai.timefold.solver.core.impl.heuristic.selector.entity.decorator.PinEntityFilter;
import ai.timefold.solver.core.impl.util.CollectionUtils;
import ai.timefold.solver.core.impl.util.MutableInt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class EntityDescriptor<Solution_> {
private static final Class[] VARIABLE_ANNOTATION_CLASSES = {
PlanningVariable.class,
PlanningListVariable.class,
InverseRelationShadowVariable.class,
AnchorShadowVariable.class,
IndexShadowVariable.class,
PreviousElementShadowVariable.class,
NextElementShadowVariable.class,
ShadowVariable.class,
ShadowVariable.List.class,
PiggybackShadowVariable.class,
CustomShadowVariable.class };
private static final Logger LOGGER = LoggerFactory.getLogger(EntityDescriptor.class);
private final int ordinal;
private final SolutionDescriptor<Solution_> solutionDescriptor;
private final Class<?> entityClass;
private final Predicate<Object> isInitializedPredicate;
private final List<MemberAccessor> declaredPlanningPinIndexMemberAccessorList = new ArrayList<>();
private Predicate<Object> hasNoNullVariablesBasicVar;
private Predicate<Object> hasNoNullVariablesListVar;
// Only declared movable filter, excludes inherited and descending movable filters
private SelectionFilter<Solution_, Object> declaredMovableEntitySelectionFilter;
private SelectionSorter<Solution_, Object> decreasingDifficultySorter;
// Only declared variable descriptors, excludes inherited variable descriptors
private Map<String, GenuineVariableDescriptor<Solution_>> declaredGenuineVariableDescriptorMap;
private Map<String, ShadowVariableDescriptor<Solution_>> declaredShadowVariableDescriptorMap;
private List<SelectionFilter<Solution_, Object>> declaredPinEntityFilterList;
private List<EntityDescriptor<Solution_>> inheritedEntityDescriptorList;
// Caches the inherited, declared and descending movable filters (including @PlanningPin filters) as a composite filter
private SelectionFilter<Solution_, Object> effectiveMovableEntitySelectionFilter;
private PlanningPinToIndexReader<Solution_> effectivePlanningPinToIndexReader;
// Caches the inherited and declared variable descriptors
private Map<String, GenuineVariableDescriptor<Solution_>> effectiveGenuineVariableDescriptorMap;
private Map<String, ShadowVariableDescriptor<Solution_>> effectiveShadowVariableDescriptorMap;
private Map<String, VariableDescriptor<Solution_>> effectiveVariableDescriptorMap;
// Duplicate of effectiveGenuineVariableDescriptorMap.values() for faster iteration on the hot path.
private List<GenuineVariableDescriptor<Solution_>> effectiveGenuineVariableDescriptorList;
private List<ListVariableDescriptor<Solution_>> effectiveGenuineListVariableDescriptorList;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public EntityDescriptor(int ordinal, SolutionDescriptor<Solution_> solutionDescriptor, Class<?> entityClass) {
this.ordinal = ordinal;
SolutionDescriptor.assertMutable(entityClass, "entityClass");
this.solutionDescriptor = solutionDescriptor;
this.entityClass = entityClass;
isInitializedPredicate = this::isInitialized;
if (entityClass.getPackage() == null) {
LOGGER.warn("The entityClass ({}) should be in a proper java package.", entityClass);
}
}
/**
* A number unique within a {@link SolutionDescriptor}, increasing sequentially from zero.
* Used for indexing in arrays to avoid object hash lookups in maps.
*
* @return zero or higher
*/
public int getOrdinal() {
return ordinal;
}
/**
* Using entityDescriptor::isInitialized directly breaks node sharing
* because it creates multiple instances of this {@link Predicate}.
*
* @deprecated Prefer {@link #getHasNoNullVariablesPredicateListVar()}.
* @return never null, always the same {@link Predicate} instance to {@link #isInitialized(Object)}
*/
@Deprecated(forRemoval = true)
public Predicate<Object> getIsInitializedPredicate() {
return isInitializedPredicate;
}
public <A> Predicate<A> getHasNoNullVariablesPredicateBasicVar() {
if (hasNoNullVariablesBasicVar == null) {
hasNoNullVariablesBasicVar = this::hasNoNullVariables;
}
return (Predicate<A>) hasNoNullVariablesBasicVar;
}
public <A> Predicate<A> getHasNoNullVariablesPredicateListVar() {
/*
* This code depends on all entity descriptors and solution descriptor to be fully initialized.
* For absolute safety, we only construct the predicate the first time it is requested.
* That will be during the building of the score director, when the descriptors are already set in stone.
*/
if (hasNoNullVariablesListVar == null) {
var listVariableDescriptor = solutionDescriptor.getListVariableDescriptor();
if (listVariableDescriptor == null || !listVariableDescriptor.acceptsValueType(entityClass)) {
throw new IllegalStateException(
"Impossible state: method called without an applicable list variable descriptor.");
}
var applicableShadowDescriptor = listVariableDescriptor.getInverseRelationShadowVariableDescriptor();
if (applicableShadowDescriptor == null) {
throw new IllegalStateException(
"Impossible state: method called without an applicable list variable descriptor.");
}
hasNoNullVariablesListVar = getHasNoNullVariablesPredicateBasicVar()
.and(entity -> applicableShadowDescriptor.getValue(entity) != null);
}
return (Predicate<A>) hasNoNullVariablesListVar;
}
// ************************************************************************
// Lifecycle methods
// ************************************************************************
public void processAnnotations(DescriptorPolicy descriptorPolicy) {
processEntityAnnotations(descriptorPolicy);
declaredGenuineVariableDescriptorMap = new LinkedHashMap<>();
declaredShadowVariableDescriptorMap = new LinkedHashMap<>();
declaredPinEntityFilterList = new ArrayList<>(2);
// Only iterate declared fields and methods, not inherited members, to avoid registering the same one twice
var memberList = ConfigUtils.getDeclaredMembers(entityClass);
var variableDescriptorCounter = new MutableInt(0);
for (var member : memberList) {
processValueRangeProviderAnnotation(descriptorPolicy, member);
processPlanningVariableAnnotation(variableDescriptorCounter, descriptorPolicy, member);
processPlanningPinAnnotation(descriptorPolicy, member);
}
if (declaredGenuineVariableDescriptorMap.isEmpty() && declaredShadowVariableDescriptorMap.isEmpty()) {
throw new IllegalStateException("The entityClass (" + entityClass
+ ") should have at least 1 getter method or 1 field with a "
+ PlanningVariable.class.getSimpleName() + " annotation or a shadow variable annotation.");
}
processVariableAnnotations(descriptorPolicy);
}
private void processEntityAnnotations(DescriptorPolicy descriptorPolicy) {
PlanningEntity entityAnnotation = entityClass.getAnnotation(PlanningEntity.class);
if (entityAnnotation == null) {
throw new IllegalStateException("The entityClass (" + entityClass
+ ") has been specified as a planning entity in the configuration," +
" but does not have a @" + PlanningEntity.class.getSimpleName() + " annotation.");
}
processMovable(descriptorPolicy, entityAnnotation);
processDifficulty(descriptorPolicy, entityAnnotation);
}
private void processMovable(DescriptorPolicy descriptorPolicy, PlanningEntity entityAnnotation) {
Class<? extends PinningFilter> pinningFilterClass = entityAnnotation.pinningFilter();
boolean hasPinningFilter = pinningFilterClass != PlanningEntity.NullPinningFilter.class;
if (hasPinningFilter) {
PinningFilter<Solution_, Object> pinningFilter = ConfigUtils.newInstance(this::toString, "pinningFilterClass",
(Class<? extends PinningFilter<Solution_, Object>>) pinningFilterClass);
declaredMovableEntitySelectionFilter =
(scoreDirector, selection) -> !pinningFilter.accept(scoreDirector.getWorkingSolution(), selection);
}
}
private void processDifficulty(DescriptorPolicy descriptorPolicy, PlanningEntity entityAnnotation) {
Class<? extends Comparator> difficultyComparatorClass = entityAnnotation.difficultyComparatorClass();
if (difficultyComparatorClass == PlanningEntity.NullDifficultyComparator.class) {
difficultyComparatorClass = null;
}
Class<? extends SelectionSorterWeightFactory> difficultyWeightFactoryClass = entityAnnotation
.difficultyWeightFactoryClass();
if (difficultyWeightFactoryClass == PlanningEntity.NullDifficultyWeightFactory.class) {
difficultyWeightFactoryClass = null;
}
if (difficultyComparatorClass != null && difficultyWeightFactoryClass != null) {
throw new IllegalStateException("The entityClass (" + entityClass
+ ") cannot have a difficultyComparatorClass (" + difficultyComparatorClass.getName()
+ ") and a difficultyWeightFactoryClass (" + difficultyWeightFactoryClass.getName()
+ ") at the same time.");
}
if (difficultyComparatorClass != null) {
Comparator<Object> difficultyComparator = ConfigUtils.newInstance(this::toString,
"difficultyComparatorClass", difficultyComparatorClass);
decreasingDifficultySorter = new ComparatorSelectionSorter<>(
difficultyComparator, SelectionSorterOrder.DESCENDING);
}
if (difficultyWeightFactoryClass != null) {
SelectionSorterWeightFactory<Solution_, Object> difficultyWeightFactory = ConfigUtils.newInstance(this::toString,
"difficultyWeightFactoryClass", difficultyWeightFactoryClass);
decreasingDifficultySorter = new WeightFactorySelectionSorter<>(
difficultyWeightFactory, SelectionSorterOrder.DESCENDING);
}
}
private void processValueRangeProviderAnnotation(DescriptorPolicy descriptorPolicy, Member member) {
if (((AnnotatedElement) member).isAnnotationPresent(ValueRangeProvider.class)) {
MemberAccessor memberAccessor = descriptorPolicy.getMemberAccessorFactory().buildAndCacheMemberAccessor(member,
FIELD_OR_READ_METHOD, ValueRangeProvider.class, descriptorPolicy.getDomainAccessType());
descriptorPolicy.addFromEntityValueRangeProvider(
memberAccessor);
}
}
private void processPlanningVariableAnnotation(MutableInt variableDescriptorCounter, DescriptorPolicy descriptorPolicy,
Member member) {
Class<? extends Annotation> variableAnnotationClass = ConfigUtils.extractAnnotationClass(
member, VARIABLE_ANNOTATION_CLASSES);
if (variableAnnotationClass != null) {
MemberAccessorFactory.MemberAccessorType memberAccessorType;
if (variableAnnotationClass.equals(CustomShadowVariable.class)
|| variableAnnotationClass.equals(ShadowVariable.class)
|| variableAnnotationClass.equals(ShadowVariable.List.class)
|| variableAnnotationClass.equals(PiggybackShadowVariable.class)) {
memberAccessorType = FIELD_OR_GETTER_METHOD;
} else {
memberAccessorType = FIELD_OR_GETTER_METHOD_WITH_SETTER;
}
MemberAccessor memberAccessor = descriptorPolicy.getMemberAccessorFactory().buildAndCacheMemberAccessor(member,
memberAccessorType, variableAnnotationClass, descriptorPolicy.getDomainAccessType());
registerVariableAccessor(variableDescriptorCounter.intValue(), variableAnnotationClass, memberAccessor);
variableDescriptorCounter.increment();
}
}
private void registerVariableAccessor(int nextVariableDescriptorOrdinal,
Class<? extends Annotation> variableAnnotationClass, MemberAccessor memberAccessor) {
var memberName = memberAccessor.getName();
if (declaredGenuineVariableDescriptorMap.containsKey(memberName)
|| declaredShadowVariableDescriptorMap.containsKey(memberName)) {
VariableDescriptor<Solution_> duplicate = declaredGenuineVariableDescriptorMap.get(memberName);
if (duplicate == null) {
duplicate = declaredShadowVariableDescriptorMap.get(memberName);
}
throw new IllegalStateException("""
The entityClass (%s) has a @%s annotated member (%s), duplicated by member for variableDescriptor (%s).
Maybe the annotation is defined on both the field and its getter."""
.formatted(entityClass, variableAnnotationClass.getSimpleName(), memberAccessor, duplicate));
} else if (variableAnnotationClass.equals(PlanningVariable.class)) {
var variableDescriptor = new BasicVariableDescriptor<>(nextVariableDescriptorOrdinal, this, memberAccessor);
declaredGenuineVariableDescriptorMap.put(memberName, variableDescriptor);
} else if (variableAnnotationClass.equals(PlanningListVariable.class)) {
if (List.class.isAssignableFrom(memberAccessor.getType())) {
var variableDescriptor = new ListVariableDescriptor<>(nextVariableDescriptorOrdinal, this, memberAccessor);
declaredGenuineVariableDescriptorMap.put(memberName, variableDescriptor);
} else {
throw new IllegalStateException("""
The entityClass (%s) has a @%s annotated member (%s) that has an unsupported type (%s).
Maybe use %s."""
.formatted(entityClass, PlanningListVariable.class.getSimpleName(), memberAccessor,
memberAccessor.getType(), List.class.getCanonicalName()));
}
} else if (variableAnnotationClass.equals(InverseRelationShadowVariable.class)) {
var variableDescriptor =
new InverseRelationShadowVariableDescriptor<>(nextVariableDescriptorOrdinal, this, memberAccessor);
declaredShadowVariableDescriptorMap.put(memberName, variableDescriptor);
} else if (variableAnnotationClass.equals(AnchorShadowVariable.class)) {
var variableDescriptor = new AnchorShadowVariableDescriptor<>(nextVariableDescriptorOrdinal, this, memberAccessor);
declaredShadowVariableDescriptorMap.put(memberName, variableDescriptor);
} else if (variableAnnotationClass.equals(IndexShadowVariable.class)) {
var variableDescriptor = new IndexShadowVariableDescriptor<>(nextVariableDescriptorOrdinal, this, memberAccessor);
declaredShadowVariableDescriptorMap.put(memberName, variableDescriptor);
} else if (variableAnnotationClass.equals(PreviousElementShadowVariable.class)) {
var variableDescriptor =
new PreviousElementShadowVariableDescriptor<>(nextVariableDescriptorOrdinal, this, memberAccessor);
declaredShadowVariableDescriptorMap.put(memberName, variableDescriptor);
} else if (variableAnnotationClass.equals(NextElementShadowVariable.class)) {
var variableDescriptor =
new NextElementShadowVariableDescriptor<>(nextVariableDescriptorOrdinal, this, memberAccessor);
declaredShadowVariableDescriptorMap.put(memberName, variableDescriptor);
} else if (variableAnnotationClass.equals(ShadowVariable.class)
|| variableAnnotationClass.equals(ShadowVariable.List.class)) {
var variableDescriptor = new CustomShadowVariableDescriptor<>(nextVariableDescriptorOrdinal, this, memberAccessor);
declaredShadowVariableDescriptorMap.put(memberName, variableDescriptor);
} else if (variableAnnotationClass.equals(PiggybackShadowVariable.class)) {
var variableDescriptor =
new PiggybackShadowVariableDescriptor<>(nextVariableDescriptorOrdinal, this, memberAccessor);
declaredShadowVariableDescriptorMap.put(memberName, variableDescriptor);
} else if (variableAnnotationClass.equals(CustomShadowVariable.class)) {
var variableDescriptor =
new LegacyCustomShadowVariableDescriptor<>(nextVariableDescriptorOrdinal, this, memberAccessor);
declaredShadowVariableDescriptorMap.put(memberName, variableDescriptor);
} else {
throw new IllegalStateException("The variableAnnotationClass (%s) is not implemented."
.formatted(variableAnnotationClass));
}
}
private void processPlanningPinAnnotation(DescriptorPolicy descriptorPolicy, Member member) {
var annotatedMember = ((AnnotatedElement) member);
if (annotatedMember.isAnnotationPresent(PlanningPin.class)) {
var memberAccessor = descriptorPolicy.getMemberAccessorFactory().buildAndCacheMemberAccessor(member,
FIELD_OR_READ_METHOD, PlanningPin.class, descriptorPolicy.getDomainAccessType());
var type = memberAccessor.getType();
if (!Boolean.TYPE.isAssignableFrom(type) && !Boolean.class.isAssignableFrom(type)) {
throw new IllegalStateException(
"The entityClass (%s) has a %s annotated member (%s) that is not a boolean or Boolean."
.formatted(entityClass, PlanningPin.class.getSimpleName(), member));
}
declaredPinEntityFilterList.add(new PinEntityFilter<>(memberAccessor));
}
}
private void processPlanningPinIndexAnnotation(DescriptorPolicy descriptorPolicy, Member member) {
var annotatedMember = ((AnnotatedElement) member);
if (annotatedMember.isAnnotationPresent(PlanningPinToIndex.class)) {
if (!hasAnyGenuineListVariables()) {
throw new IllegalStateException(
"The entityClass (%s) has a %s annotated member (%s) but no %s annotated member."
.formatted(entityClass, PlanningPinToIndex.class.getSimpleName(), member,
PlanningListVariable.class.getSimpleName()));
}
var memberAccessor = descriptorPolicy.getMemberAccessorFactory().buildAndCacheMemberAccessor(member,
FIELD_OR_READ_METHOD, PlanningPinToIndex.class, descriptorPolicy.getDomainAccessType());
var type = memberAccessor.getType();
if (!Integer.TYPE.isAssignableFrom(type)) {
throw new IllegalStateException(
"The entityClass (%s) has a %s annotated member (%s) that is not a primitive int."
.formatted(entityClass, PlanningPinToIndex.class.getSimpleName(), member));
}
declaredPlanningPinIndexMemberAccessorList.add(memberAccessor);
}
}
private void processVariableAnnotations(DescriptorPolicy descriptorPolicy) {
for (GenuineVariableDescriptor<Solution_> variableDescriptor : declaredGenuineVariableDescriptorMap.values()) {
variableDescriptor.processAnnotations(descriptorPolicy);
}
for (ShadowVariableDescriptor<Solution_> variableDescriptor : declaredShadowVariableDescriptorMap.values()) {
variableDescriptor.processAnnotations(descriptorPolicy);
}
}
public void linkEntityDescriptors(DescriptorPolicy descriptorPolicy) {
investigateParentsToLinkInherited(entityClass);
createEffectiveVariableDescriptorMaps();
createEffectiveMovableEntitySelectionFilter();
// linkVariableDescriptors() is in a separate loop
}
private void investigateParentsToLinkInherited(Class<?> investigateClass) {
inheritedEntityDescriptorList = new ArrayList<>(4);
if (investigateClass == null || investigateClass.isArray()) {
return;
}
linkInherited(investigateClass.getSuperclass());
for (Class<?> superInterface : investigateClass.getInterfaces()) {
linkInherited(superInterface);
}
}
private void linkInherited(Class<?> potentialEntityClass) {
EntityDescriptor<Solution_> entityDescriptor = solutionDescriptor.getEntityDescriptorStrict(
potentialEntityClass);
if (entityDescriptor != null) {
inheritedEntityDescriptorList.add(entityDescriptor);
} else {
investigateParentsToLinkInherited(potentialEntityClass);
}
}
private void createEffectiveVariableDescriptorMaps() {
effectiveGenuineVariableDescriptorMap = new LinkedHashMap<>(declaredGenuineVariableDescriptorMap.size());
effectiveShadowVariableDescriptorMap = new LinkedHashMap<>(declaredShadowVariableDescriptorMap.size());
for (EntityDescriptor<Solution_> inheritedEntityDescriptor : inheritedEntityDescriptorList) {
effectiveGenuineVariableDescriptorMap.putAll(inheritedEntityDescriptor.effectiveGenuineVariableDescriptorMap);
effectiveShadowVariableDescriptorMap.putAll(inheritedEntityDescriptor.effectiveShadowVariableDescriptorMap);
}
effectiveGenuineVariableDescriptorMap.putAll(declaredGenuineVariableDescriptorMap);
effectiveShadowVariableDescriptorMap.putAll(declaredShadowVariableDescriptorMap);
effectiveVariableDescriptorMap = CollectionUtils
.newLinkedHashMap(effectiveGenuineVariableDescriptorMap.size() + effectiveShadowVariableDescriptorMap.size());
effectiveVariableDescriptorMap.putAll(effectiveGenuineVariableDescriptorMap);
effectiveVariableDescriptorMap.putAll(effectiveShadowVariableDescriptorMap);
effectiveGenuineVariableDescriptorList = new ArrayList<>(effectiveGenuineVariableDescriptorMap.values());
effectiveGenuineListVariableDescriptorList = effectiveGenuineVariableDescriptorList.stream()
.filter(VariableDescriptor::isListVariable)
.map(l -> (ListVariableDescriptor<Solution_>) l)
.toList();
}
private void createEffectiveMovableEntitySelectionFilter() {
if (declaredMovableEntitySelectionFilter != null && !hasAnyDeclaredGenuineVariableDescriptor()) {
throw new IllegalStateException("The entityClass (" + entityClass
+ ") has a movableEntitySelectionFilterClass (" + declaredMovableEntitySelectionFilter.getClass()
+ "), but it has no declared genuine variables, only shadow variables.");
}
List<SelectionFilter<Solution_, Object>> selectionFilterList = new ArrayList<>();
// TODO Also add in child entity selectors
for (EntityDescriptor<Solution_> inheritedEntityDescriptor : inheritedEntityDescriptorList) {
if (inheritedEntityDescriptor.hasEffectiveMovableEntitySelectionFilter()) {
// Includes movable and pinned
selectionFilterList.add(inheritedEntityDescriptor.getEffectiveMovableEntitySelectionFilter());
}
}
if (declaredMovableEntitySelectionFilter != null) {
selectionFilterList.add(declaredMovableEntitySelectionFilter);
}
selectionFilterList.addAll(declaredPinEntityFilterList);
if (selectionFilterList.isEmpty()) {
effectiveMovableEntitySelectionFilter = null;
} else {
effectiveMovableEntitySelectionFilter = SelectionFilter.compose(selectionFilterList);
}
}
private void createEffectivePlanningPinIndexReader() {
if (!hasAnyGenuineListVariables()) {
effectivePlanningPinToIndexReader = null;
return;
}
var planningPinIndexMemberAccessorList = new ArrayList<MemberAccessor>();
for (EntityDescriptor<Solution_> inheritedEntityDescriptor : inheritedEntityDescriptorList) {
if (inheritedEntityDescriptor.effectivePlanningPinToIndexReader != null) {
planningPinIndexMemberAccessorList.addAll(inheritedEntityDescriptor.declaredPlanningPinIndexMemberAccessorList);
}
}
planningPinIndexMemberAccessorList.addAll(declaredPlanningPinIndexMemberAccessorList);
switch (planningPinIndexMemberAccessorList.size()) {
case 0 -> effectivePlanningPinToIndexReader = null;
case 1 -> {
var memberAccessor = planningPinIndexMemberAccessorList.get(0);
effectivePlanningPinToIndexReader = (solution, entity) -> (int) memberAccessor.executeGetter(entity);
}
default -> throw new IllegalStateException(
"The entityClass (%s) has (%d) @%s-annotated members (%s), where it should only have one."
.formatted(entityClass, planningPinIndexMemberAccessorList.size(),
PlanningPinToIndex.class.getSimpleName(), planningPinIndexMemberAccessorList));
}
}
public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) {
for (GenuineVariableDescriptor<Solution_> variableDescriptor : declaredGenuineVariableDescriptorMap.values()) {
variableDescriptor.linkVariableDescriptors(descriptorPolicy);
}
for (ShadowVariableDescriptor<Solution_> shadowVariableDescriptor : declaredShadowVariableDescriptorMap.values()) {
shadowVariableDescriptor.linkVariableDescriptors(descriptorPolicy);
}
/*
* We can only create the PlanningPinIndexReader after we have processed all list variable descriptors.
* Only iterate declared fields and methods, not inherited members,
* to avoid registering the same one twice.
*/
for (Member member : ConfigUtils.getDeclaredMembers(entityClass)) {
processPlanningPinIndexAnnotation(descriptorPolicy, member);
}
createEffectivePlanningPinIndexReader();
}
// ************************************************************************
// Worker methods
// ************************************************************************
public SolutionDescriptor<Solution_> getSolutionDescriptor() {
return solutionDescriptor;
}
public Class<?> getEntityClass() {
return entityClass;
}
public boolean matchesEntity(Object entity) {
return entityClass.isAssignableFrom(entity.getClass());
}
public boolean hasEffectiveMovableEntitySelectionFilter() {
return effectiveMovableEntitySelectionFilter != null;
}
public boolean supportsPinning() {
return hasEffectiveMovableEntitySelectionFilter() || effectivePlanningPinToIndexReader != null;
}
public SelectionFilter<Solution_, Object> getEffectiveMovableEntitySelectionFilter() {
return effectiveMovableEntitySelectionFilter;
}
public SelectionSorter<Solution_, Object> getDecreasingDifficultySorter() {
return decreasingDifficultySorter;
}
public Collection<String> getGenuineVariableNameSet() {
return effectiveGenuineVariableDescriptorMap.keySet();
}
public GenuineVariableDescriptor<Solution_> getGenuineVariableDescriptor(String variableName) {
return effectiveGenuineVariableDescriptorMap.get(variableName);
}
public boolean hasAnyGenuineVariables() {
return !effectiveGenuineVariableDescriptorMap.isEmpty();
}
public boolean hasAnyGenuineListVariables() {
if (!isGenuine()) {
return false;
}
return getGenuineListVariableDescriptor() != null;
}
public boolean isGenuine() {
return hasAnyGenuineVariables();
}
public ListVariableDescriptor<Solution_> getGenuineListVariableDescriptor() {
if (effectiveGenuineListVariableDescriptorList.isEmpty()) {
return null;
}
// Earlier validation guarantees there will only ever be one.
return effectiveGenuineListVariableDescriptorList.get(0);
}
public List<GenuineVariableDescriptor<Solution_>> getGenuineVariableDescriptorList() {
return effectiveGenuineVariableDescriptorList;
}
public long getGenuineVariableCount() {
return effectiveGenuineVariableDescriptorList.size();
}
public Collection<ShadowVariableDescriptor<Solution_>> getShadowVariableDescriptors() {
return effectiveShadowVariableDescriptorMap.values();
}
public ShadowVariableDescriptor<Solution_> getShadowVariableDescriptor(String variableName) {
return effectiveShadowVariableDescriptorMap.get(variableName);
}
public Map<String, VariableDescriptor<Solution_>> getVariableDescriptorMap() {
return effectiveVariableDescriptorMap;
}
public boolean hasVariableDescriptor(String variableName) {
return effectiveVariableDescriptorMap.containsKey(variableName);
}
public VariableDescriptor<Solution_> getVariableDescriptor(String variableName) {
return effectiveVariableDescriptorMap.get(variableName);
}
public boolean hasAnyDeclaredGenuineVariableDescriptor() {
return !declaredGenuineVariableDescriptorMap.isEmpty();
}
public Collection<GenuineVariableDescriptor<Solution_>> getDeclaredGenuineVariableDescriptors() {
return declaredGenuineVariableDescriptorMap.values();
}
public Collection<ShadowVariableDescriptor<Solution_>> getDeclaredShadowVariableDescriptors() {
return declaredShadowVariableDescriptorMap.values();
}
public Collection<VariableDescriptor<Solution_>> getDeclaredVariableDescriptors() {
Collection<VariableDescriptor<Solution_>> variableDescriptors = new ArrayList<>(
declaredGenuineVariableDescriptorMap.size() + declaredShadowVariableDescriptorMap.size());
variableDescriptors.addAll(declaredGenuineVariableDescriptorMap.values());
variableDescriptors.addAll(declaredShadowVariableDescriptorMap.values());
return variableDescriptors;
}
public String buildInvalidVariableNameExceptionMessage(String variableName) {
if (!ReflectionHelper.hasGetterMethod(entityClass, variableName)
&& !ReflectionHelper.hasField(entityClass, variableName)) {
String exceptionMessage = "The variableName (" + variableName
+ ") for entityClass (" + entityClass
+ ") does not exist as a getter or field on that class.\n"
+ "Check the spelling of the variableName (" + variableName + ").";
if (variableName.length() >= 2
&& !Character.isUpperCase(variableName.charAt(0))
&& Character.isUpperCase(variableName.charAt(1))) {
String correctedVariableName = variableName.substring(0, 1).toUpperCase() + variableName.substring(1);
exceptionMessage += "Maybe it needs to be correctedVariableName (" + correctedVariableName
+ ") instead, if it's a getter, because the JavaBeans spec states that "
+ "the first letter should be a upper case if the second is upper case.";
}
return exceptionMessage;
}
return "The variableName (" + variableName
+ ") for entityClass (" + entityClass
+ ") exists as a getter or field on that class,"
+ " but isn't in the planning variables (" + effectiveVariableDescriptorMap.keySet() + ").\n"
+ (Character.isUpperCase(variableName.charAt(0))
? "Maybe the variableName (" + variableName + ") should start with a lowercase.\n"
: "")
+ "Maybe your planning entity's getter or field lacks a @" + PlanningVariable.class.getSimpleName()
+ " annotation or a shadow variable annotation.";
}
// ************************************************************************
// Extraction methods
// ************************************************************************
public List<Object> extractEntities(Solution_ solution) {
List<Object> entityList = new ArrayList<>();
visitAllEntities(solution, entityList::add);
return entityList;
}
public void visitAllEntities(Solution_ solution, Consumer<Object> visitor) {
solutionDescriptor.visitEntitiesByEntityClass(solution, entityClass, entity -> {
visitor.accept(entity);
return false; // Iterate over all entities.
});
}
public PlanningPinToIndexReader<Solution_> getEffectivePlanningPinToIndexReader() {
return effectivePlanningPinToIndexReader;
}
public long getMaximumValueCount(Solution_ solution, Object entity) {
long maximumValueCount = 0L;
for (GenuineVariableDescriptor<Solution_> variableDescriptor : effectiveGenuineVariableDescriptorList) {
maximumValueCount = Math.max(maximumValueCount, variableDescriptor.getValueRangeSize(solution, entity));
}
return maximumValueCount;
}
public void processProblemScale(ScoreDirector<Solution_> scoreDirector, Solution_ solution, Object entity,
ProblemScaleTracker tracker) {
for (GenuineVariableDescriptor<Solution_> variableDescriptor : effectiveGenuineVariableDescriptorList) {
long valueCount = variableDescriptor.getValueRangeSize(solution, 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 (!isMovable(scoreDirector, entity)) {
tracker.addPinnedListValueCount(1);
}
// Anchors are entities
ValueRange<?> valueRange = variableDescriptor.getValueRangeDescriptor().extractValueRange(solution, entity);
if (valueRange instanceof CountableValueRange<?> countableValueRange) {
Iterator<?> valueIterator = countableValueRange.createOriginalIterator();
while (valueIterator.hasNext()) {
Object value = valueIterator.next();
if (variableDescriptor.isValuePotentialAnchor(value)) {
if (tracker.isAnchorVisited(value)) {
continue;
}
// Assumes anchors are not pinned
tracker.incrementListEntityCount(true);
}
}
} else {
throw new IllegalStateException("""
The value range (%s) for variable (%s) is not countable.
Verify that a @%s does not return a %s when it can return %s or %s.
""".formatted(valueRange, variableDescriptor.getSimpleEntityAndVariableName(),
ValueRangeProvider.class.getSimpleName(), ValueRange.class.getSimpleName(),
CountableValueRange.class.getSimpleName(), Collection.class.getSimpleName()));
}
} else {
if (isMovable(scoreDirector, entity)) {
tracker.addBasicProblemScale(valueCount);
}
}
} else if (variableDescriptor instanceof ListVariableDescriptor<Solution_> listVariableDescriptor) {
tracker.setListTotalValueCount((int) listVariableDescriptor.getValueRangeSize(solution, entity));
if (isMovable(scoreDirector, 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()));
}
}
}
public int countUninitializedVariables(Object entity) {
int count = 0;
for (GenuineVariableDescriptor<Solution_> variableDescriptor : effectiveGenuineVariableDescriptorList) {
if (!variableDescriptor.isInitialized(entity)) {
count++;
}
}
return count;
}
public boolean isInitialized(Object entity) {
for (GenuineVariableDescriptor<Solution_> variableDescriptor : effectiveGenuineVariableDescriptorList) {
if (!variableDescriptor.isInitialized(entity)) {
return false;
}
}
return true;
}
public boolean hasNoNullVariables(Object entity) {
return switch (effectiveGenuineVariableDescriptorList.size()) { // Avoid excessive iterator allocation.
case 0 -> true;
case 1 -> effectiveGenuineVariableDescriptorList.get(0).getValue(entity) != null;
default -> {
for (var variableDescriptor : effectiveGenuineVariableDescriptorList) {
if (variableDescriptor.getValue(entity) == null) {
yield false;
}
}
yield true;
}
};
}
public int countReinitializableVariables(Object entity) {
int count = 0;
for (GenuineVariableDescriptor<Solution_> variableDescriptor : effectiveGenuineVariableDescriptorList) {
if (variableDescriptor.isReinitializable(entity)) {
count++;
}
}
return count;
}
public boolean isMovable(ScoreDirector<Solution_> scoreDirector, Object entity) {
return isGenuine() &&
(effectiveMovableEntitySelectionFilter == null
|| effectiveMovableEntitySelectionFilter.accept(scoreDirector, entity));
}
/**
* @param scoreDirector never null
* @param entity never null
* @return true if the entity is initialized or pinned
*/
public boolean isEntityInitializedOrPinned(ScoreDirector<Solution_> scoreDirector, Object entity) {
return !isGenuine() || isInitialized(entity) || !isMovable(scoreDirector, entity);
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + entityClass.getName() + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/entity | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/entity/descriptor/PlanningPinToIndexReader.java | package ai.timefold.solver.core.impl.domain.entity.descriptor;
import java.util.function.ToIntBiFunction;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
@FunctionalInterface
public interface PlanningPinToIndexReader<Solution_>
extends ToIntBiFunction<ScoreDirector<Solution_>, Object> {
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/lookup/ClassAndPlanningIdComparator.java | package ai.timefold.solver.core.impl.domain.lookup;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.domain.lookup.PlanningId;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory;
public final class ClassAndPlanningIdComparator implements Comparator<Object> {
private final MemberAccessorFactory memberAccessorFactory;
private final DomainAccessType domainAccessType;
private final boolean failFastIfNoPlanningId;
private final Map<Class, MemberAccessor> decisionCache = new HashMap<>();
public ClassAndPlanningIdComparator(MemberAccessorFactory memberAccessorFactory,
DomainAccessType domainAccessType, boolean failFastIfNoPlanningId) {
this.memberAccessorFactory = memberAccessorFactory;
this.domainAccessType = domainAccessType;
this.failFastIfNoPlanningId = failFastIfNoPlanningId;
}
@Override
public int compare(Object a, Object b) {
if (a == null) {
return b == null ? 0 : -1;
} else if (b == null) {
return 1;
}
Class<?> aClass = a.getClass();
Class<?> bClass = b.getClass();
if (aClass != bClass) {
return aClass.getName().compareTo(bClass.getName());
}
MemberAccessor aMemberAccessor = decisionCache.computeIfAbsent(aClass, this::findMemberAccessor);
MemberAccessor bMemberAccessor = decisionCache.computeIfAbsent(bClass, this::findMemberAccessor);
if (failFastIfNoPlanningId) {
if (aMemberAccessor == null) {
throw new IllegalArgumentException("The class (" + aClass
+ ") does not have a @" + PlanningId.class.getSimpleName() + " annotation.\n"
+ "Maybe add the @" + PlanningId.class.getSimpleName() + " annotation.");
}
if (bMemberAccessor == null) {
throw new IllegalArgumentException("The class (" + bClass
+ ") does not have a @" + PlanningId.class.getSimpleName() + " annotation.\n"
+ "Maybe add the @" + PlanningId.class.getSimpleName() + " annotation.");
}
} else {
if (aMemberAccessor == null) {
if (bMemberAccessor == null) {
if (a instanceof Comparable comparable) {
return comparable.compareTo(b);
} else { // Return 0 to keep original order.
return 0;
}
} else {
return -1;
}
} else if (bMemberAccessor == null) {
return 1;
}
}
Comparable aPlanningId = (Comparable) aMemberAccessor.executeGetter(a);
Comparable bPlanningId = (Comparable) bMemberAccessor.executeGetter(b);
if (aPlanningId == null) {
throw new IllegalArgumentException("The planningId (" + aPlanningId
+ ") of the member (" + aMemberAccessor + ") of the class (" + aClass
+ ") on object (" + a + ") must not be null.\n"
+ "Maybe initialize the planningId of the original object before solving..");
}
if (bPlanningId == null) {
throw new IllegalArgumentException("The planningId (" + bPlanningId
+ ") of the member (" + bMemberAccessor + ") of the class (" + bClass
+ ") on object (" + a + ") must not be null.\n"
+ "Maybe initialize the planningId of the original object before solving..");
}
// If a and b are different classes, this method would have already returned.
return aPlanningId.compareTo(bPlanningId);
}
private MemberAccessor findMemberAccessor(Class<?> clazz) {
return ConfigUtils.findPlanningIdMemberAccessor(clazz, memberAccessorFactory, domainAccessType);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/lookup/EqualsLookUpStrategy.java | package ai.timefold.solver.core.impl.domain.lookup;
import java.util.Map;
import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty;
public class EqualsLookUpStrategy implements LookUpStrategy {
@Override
public void addWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject) {
Object oldAddedObject = idToWorkingObjectMap.put(workingObject, workingObject);
if (oldAddedObject != null) {
throw new IllegalStateException("The workingObjects (" + oldAddedObject + ", " + workingObject
+ ") are equal (as in Object.equals()). Working objects must be unique.");
}
}
@Override
public void removeWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject) {
Object removedObject = idToWorkingObjectMap.remove(workingObject);
if (workingObject != removedObject) {
throw new IllegalStateException("The workingObject (" + workingObject
+ ") differs from the removedObject (" + removedObject + ").");
}
}
@Override
public <E> E lookUpWorkingObject(Map<Object, Object> idToWorkingObjectMap, E externalObject) {
E workingObject = (E) idToWorkingObjectMap.get(externalObject);
if (workingObject == null) {
throw new IllegalStateException("The externalObject (" + externalObject
+ ") has no known workingObject (" + workingObject + ").\n"
+ "Maybe the workingObject was never added because the planning solution doesn't have a @"
+ ProblemFactCollectionProperty.class.getSimpleName()
+ " annotation on a member with instances of the externalObject's class ("
+ externalObject.getClass() + ").");
}
return workingObject;
}
@Override
public <E> E lookUpWorkingObjectIfExists(Map<Object, Object> idToWorkingObjectMap, E externalObject) {
return (E) idToWorkingObjectMap.get(externalObject);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/lookup/ImmutableLookUpStrategy.java | package ai.timefold.solver.core.impl.domain.lookup;
import java.util.Map;
public class ImmutableLookUpStrategy implements LookUpStrategy {
@Override
public void addWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject) {
// Do nothing
}
@Override
public void removeWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject) {
// Do nothing
}
@Override
public <E> E lookUpWorkingObject(Map<Object, Object> idToWorkingObjectMap, E externalObject) {
// Because it is immutable, we can use the same one.
return externalObject;
}
@Override
public <E> E lookUpWorkingObjectIfExists(Map<Object, Object> idToWorkingObjectMap, E externalObject) {
// Because it is immutable, we can use the same one.
return externalObject;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/lookup/LookUpStrategy.java | package ai.timefold.solver.core.impl.domain.lookup;
import java.util.Map;
public interface LookUpStrategy {
void addWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject);
void removeWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject);
<E> E lookUpWorkingObject(Map<Object, Object> idToWorkingObjectMap, E externalObject);
<E> E lookUpWorkingObjectIfExists(Map<Object, Object> idToWorkingObjectMap, E externalObject);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/lookup/LookUpStrategyResolver.java | package ai.timefold.solver.core.impl.domain.lookup;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.MonthDay;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.Period;
import java.time.Year;
import java.time.YearMonth;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.domain.lookup.LookUpStrategyType;
import ai.timefold.solver.core.api.domain.lookup.PlanningId;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory;
import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy;
/**
* This class is thread-safe.
*/
public class LookUpStrategyResolver {
private final LookUpStrategyType lookUpStrategyType;
private final DomainAccessType domainAccessType;
private final MemberAccessorFactory memberAccessorFactory;
private final ConcurrentMap<Class<?>, LookUpStrategy> decisionCache = new ConcurrentHashMap<>();
public LookUpStrategyResolver(DescriptorPolicy descriptorPolicy, LookUpStrategyType lookUpStrategyType) {
this.lookUpStrategyType = lookUpStrategyType;
this.domainAccessType = descriptorPolicy.getDomainAccessType();
this.memberAccessorFactory = descriptorPolicy.getMemberAccessorFactory();
decisionCache.put(Boolean.class, new ImmutableLookUpStrategy());
decisionCache.put(Byte.class, new ImmutableLookUpStrategy());
decisionCache.put(Short.class, new ImmutableLookUpStrategy());
decisionCache.put(Integer.class, new ImmutableLookUpStrategy());
decisionCache.put(Long.class, new ImmutableLookUpStrategy());
decisionCache.put(Float.class, new ImmutableLookUpStrategy());
decisionCache.put(Double.class, new ImmutableLookUpStrategy());
decisionCache.put(BigInteger.class, new ImmutableLookUpStrategy());
decisionCache.put(BigDecimal.class, new ImmutableLookUpStrategy());
decisionCache.put(Character.class, new ImmutableLookUpStrategy());
decisionCache.put(String.class, new ImmutableLookUpStrategy());
decisionCache.put(UUID.class, new ImmutableLookUpStrategy());
decisionCache.put(Instant.class, new ImmutableLookUpStrategy());
decisionCache.put(LocalDateTime.class, new ImmutableLookUpStrategy());
decisionCache.put(LocalTime.class, new ImmutableLookUpStrategy());
decisionCache.put(LocalDate.class, new ImmutableLookUpStrategy());
decisionCache.put(MonthDay.class, new ImmutableLookUpStrategy());
decisionCache.put(YearMonth.class, new ImmutableLookUpStrategy());
decisionCache.put(Year.class, new ImmutableLookUpStrategy());
decisionCache.put(OffsetDateTime.class, new ImmutableLookUpStrategy());
decisionCache.put(OffsetTime.class, new ImmutableLookUpStrategy());
decisionCache.put(ZonedDateTime.class, new ImmutableLookUpStrategy());
decisionCache.put(ZoneOffset.class, new ImmutableLookUpStrategy());
decisionCache.put(Duration.class, new ImmutableLookUpStrategy());
decisionCache.put(Period.class, new ImmutableLookUpStrategy());
}
/**
* This method is thread-safe.
*
* @param object never null
* @return never null
*/
public LookUpStrategy determineLookUpStrategy(Object object) {
return decisionCache.computeIfAbsent(object.getClass(), objectClass -> {
if (objectClass.isEnum()) {
return new ImmutableLookUpStrategy();
}
switch (lookUpStrategyType) {
case PLANNING_ID_OR_NONE:
MemberAccessor memberAccessor1 =
ConfigUtils.findPlanningIdMemberAccessor(objectClass, memberAccessorFactory, domainAccessType);
if (memberAccessor1 == null) {
return new NoneLookUpStrategy();
}
return new PlanningIdLookUpStrategy(memberAccessor1);
case PLANNING_ID_OR_FAIL_FAST:
MemberAccessor memberAccessor2 =
ConfigUtils.findPlanningIdMemberAccessor(objectClass, memberAccessorFactory, domainAccessType);
if (memberAccessor2 == null) {
throw new IllegalArgumentException("The class (" + objectClass
+ ") does not have a @" + PlanningId.class.getSimpleName() + " annotation,"
+ " but the lookUpStrategyType (" + lookUpStrategyType + ") requires it.\n"
+ "Maybe add the @" + PlanningId.class.getSimpleName() + " annotation"
+ " or change the @" + PlanningSolution.class.getSimpleName() + " annotation's "
+ LookUpStrategyType.class.getSimpleName() + ".");
}
return new PlanningIdLookUpStrategy(memberAccessor2);
case EQUALITY:
Method equalsMethod;
Method hashCodeMethod;
try {
equalsMethod = objectClass.getMethod("equals", Object.class);
hashCodeMethod = objectClass.getMethod("hashCode");
} catch (NoSuchMethodException e) {
throw new IllegalStateException(
"Impossible state because equals() and hashCode() always exist.", e);
}
if (equalsMethod.getDeclaringClass().equals(Object.class)) {
throw new IllegalArgumentException("The class (" + objectClass.getSimpleName()
+ ") doesn't override the equals() method, neither does any superclass.");
}
if (hashCodeMethod.getDeclaringClass().equals(Object.class)) {
throw new IllegalArgumentException("The class (" + objectClass.getSimpleName()
+ ") overrides equals() but neither it nor any superclass"
+ " overrides the hashCode() method.");
}
return new EqualsLookUpStrategy();
case NONE:
return new NoneLookUpStrategy();
default:
throw new IllegalStateException("The lookUpStrategyType (" + lookUpStrategyType
+ ") is not implemented.");
}
});
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/lookup/NoneLookUpStrategy.java | package ai.timefold.solver.core.impl.domain.lookup;
import java.util.Map;
import ai.timefold.solver.core.api.domain.lookup.LookUpStrategyType;
import ai.timefold.solver.core.api.domain.lookup.PlanningId;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
public class NoneLookUpStrategy implements LookUpStrategy {
@Override
public void addWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject) {
// Do nothing
}
@Override
public void removeWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject) {
// Do nothing
}
@Override
public <E> E lookUpWorkingObject(Map<Object, Object> idToWorkingObjectMap, E externalObject) {
throw new IllegalArgumentException("The externalObject (" + externalObject
+ ") cannot be looked up. Some functionality, such as multithreaded solving, requires this ability.\n"
+ "Maybe add a @" + PlanningId.class.getSimpleName()
+ " annotation on an identifier property of the class (" + externalObject.getClass() + ").\n"
+ "Or otherwise, maybe change the @" + PlanningSolution.class.getSimpleName() + " annotation's "
+ LookUpStrategyType.class.getSimpleName() + " (not recommended).");
}
@Override
public <E> E lookUpWorkingObjectIfExists(Map<Object, Object> idToWorkingObjectMap, E externalObject) {
throw new IllegalArgumentException("The externalObject (" + externalObject
+ ") cannot be looked up. Some functionality, such as multithreaded solving, requires this ability.\n"
+ "Maybe add a @" + PlanningId.class.getSimpleName()
+ " annotation on an identifier property of the class (" + externalObject.getClass() + ").\n"
+ "Or otherwise, maybe change the @" + PlanningSolution.class.getSimpleName() + " annotation's "
+ LookUpStrategyType.class.getSimpleName() + " (not recommended).");
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/lookup/PlanningIdLookUpStrategy.java | package ai.timefold.solver.core.impl.domain.lookup;
import java.util.Map;
import ai.timefold.solver.core.api.domain.lookup.LookUpStrategyType;
import ai.timefold.solver.core.api.domain.lookup.PlanningId;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.util.Pair;
public class PlanningIdLookUpStrategy implements LookUpStrategy {
private final MemberAccessor planningIdMemberAccessor;
public PlanningIdLookUpStrategy(MemberAccessor planningIdMemberAccessor) {
this.planningIdMemberAccessor = planningIdMemberAccessor;
}
@Override
public void addWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject) {
Object planningId = extractPlanningId(workingObject);
if (planningId == null) {
throw new IllegalStateException("The workingObject (" + workingObject
+ ") returns a null value for its @" + PlanningId.class.getSimpleName()
+ " member (" + planningIdMemberAccessor + ").");
}
Object oldAddedObject = idToWorkingObjectMap.put(planningId, workingObject);
if (oldAddedObject != null) {
throw new IllegalStateException("The workingObjects (" + oldAddedObject + ", " + workingObject
+ ") have the same planningId (" + planningId + "). Working objects must be unique.");
}
}
@Override
public void removeWorkingObject(Map<Object, Object> idToWorkingObjectMap, Object workingObject) {
Object planningId = extractPlanningId(workingObject);
if (planningId == null) {
throw new IllegalStateException("The workingObject (" + workingObject
+ ") returns a null value for its @" + PlanningId.class.getSimpleName()
+ " member (" + planningIdMemberAccessor + ").");
}
Object removedObject = idToWorkingObjectMap.remove(planningId);
if (workingObject != removedObject) {
throw new IllegalStateException("The workingObject (" + workingObject
+ ") differs from the removedObject (" + removedObject + ") for planningId (" + planningId + ").");
}
}
@Override
public <E> E lookUpWorkingObject(Map<Object, Object> idToWorkingObjectMap, E externalObject) {
Object planningId = extractPlanningId(externalObject);
E workingObject = (E) idToWorkingObjectMap.get(planningId);
if (workingObject == null) {
throw new IllegalStateException("The externalObject (" + externalObject + ") with planningId (" + planningId
+ ") has no known workingObject (" + workingObject + ").\n"
+ "Maybe the workingObject was never added because the planning solution doesn't have a @"
+ ProblemFactCollectionProperty.class.getSimpleName()
+ " annotation on a member with instances of the externalObject's class ("
+ externalObject.getClass() + ").");
}
return workingObject;
}
@Override
public <E> E lookUpWorkingObjectIfExists(Map<Object, Object> idToWorkingObjectMap, E externalObject) {
Object planningId = extractPlanningId(externalObject);
return (E) idToWorkingObjectMap.get(planningId);
}
protected Object extractPlanningId(Object externalObject) {
Object planningId = planningIdMemberAccessor.executeGetter(externalObject);
if (planningId == null) {
throw new IllegalArgumentException("The planningId (" + planningId
+ ") of the member (" + planningIdMemberAccessor + ") of the class (" + externalObject.getClass()
+ ") on externalObject (" + externalObject
+ ") must not be null.\n"
+ "Maybe initialize the planningId of the class (" + externalObject.getClass().getSimpleName()
+ ") instance (" + externalObject + ") before solving.\n" +
"Maybe remove the @" + PlanningId.class.getSimpleName() + " annotation"
+ " or change the @" + PlanningSolution.class.getSimpleName() + " annotation's "
+ LookUpStrategyType.class.getSimpleName() + ".");
}
return new Pair<>(externalObject.getClass(), planningId);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/policy/DescriptorPolicy.java | package ai.timefold.solver.core.impl.domain.policy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory;
public class DescriptorPolicy {
private Map<String, SolutionCloner> generatedSolutionClonerMap = new LinkedHashMap<>();
private final Map<String, MemberAccessor> fromSolutionValueRangeProviderMap = new LinkedHashMap<>();
private final Set<MemberAccessor> anonymousFromSolutionValueRangeProviderSet = new LinkedHashSet<>();
private final Map<String, MemberAccessor> fromEntityValueRangeProviderMap = new LinkedHashMap<>();
private final Set<MemberAccessor> anonymousFromEntityValueRangeProviderSet = new LinkedHashSet<>();
private DomainAccessType domainAccessType = DomainAccessType.REFLECTION;
private MemberAccessorFactory memberAccessorFactory;
public void addFromSolutionValueRangeProvider(MemberAccessor memberAccessor) {
String id = extractValueRangeProviderId(memberAccessor);
if (id == null) {
anonymousFromSolutionValueRangeProviderSet.add(memberAccessor);
} else {
fromSolutionValueRangeProviderMap.put(id, memberAccessor);
}
}
public boolean isFromSolutionValueRangeProvider(MemberAccessor memberAccessor) {
return fromSolutionValueRangeProviderMap.containsValue(memberAccessor)
|| anonymousFromSolutionValueRangeProviderSet.contains(memberAccessor);
}
public boolean hasFromSolutionValueRangeProvider(String id) {
return fromSolutionValueRangeProviderMap.containsKey(id);
}
public MemberAccessor getFromSolutionValueRangeProvider(String id) {
return fromSolutionValueRangeProviderMap.get(id);
}
public Set<MemberAccessor> getAnonymousFromSolutionValueRangeProviderSet() {
return anonymousFromSolutionValueRangeProviderSet;
}
public void addFromEntityValueRangeProvider(MemberAccessor memberAccessor) {
String id = extractValueRangeProviderId(memberAccessor);
if (id == null) {
anonymousFromEntityValueRangeProviderSet.add(memberAccessor);
} else {
fromEntityValueRangeProviderMap.put(id, memberAccessor);
}
}
public boolean isFromEntityValueRangeProvider(MemberAccessor memberAccessor) {
return fromEntityValueRangeProviderMap.containsValue(memberAccessor)
|| anonymousFromEntityValueRangeProviderSet.contains(memberAccessor);
}
public boolean hasFromEntityValueRangeProvider(String id) {
return fromEntityValueRangeProviderMap.containsKey(id);
}
public Set<MemberAccessor> getAnonymousFromEntityValueRangeProviderSet() {
return anonymousFromEntityValueRangeProviderSet;
}
/**
* @return never null
*/
public DomainAccessType getDomainAccessType() {
return domainAccessType;
}
public void setDomainAccessType(DomainAccessType domainAccessType) {
this.domainAccessType = domainAccessType;
}
/**
* @return never null
*/
public Map<String, SolutionCloner> getGeneratedSolutionClonerMap() {
return generatedSolutionClonerMap;
}
public void setGeneratedSolutionClonerMap(Map<String, SolutionCloner> generatedSolutionClonerMap) {
this.generatedSolutionClonerMap = generatedSolutionClonerMap;
}
public MemberAccessorFactory getMemberAccessorFactory() {
return memberAccessorFactory;
}
public void setMemberAccessorFactory(MemberAccessorFactory memberAccessorFactory) {
this.memberAccessorFactory = memberAccessorFactory;
}
public MemberAccessor getFromEntityValueRangeProvider(String id) {
return fromEntityValueRangeProviderMap.get(id);
}
private String extractValueRangeProviderId(MemberAccessor memberAccessor) {
ValueRangeProvider annotation = memberAccessor.getAnnotation(ValueRangeProvider.class);
String id = annotation.id();
if (id == null || id.isEmpty()) {
return null;
}
validateUniqueValueRangeProviderId(id, memberAccessor);
return id;
}
private void validateUniqueValueRangeProviderId(String id, MemberAccessor memberAccessor) {
MemberAccessor duplicate = fromSolutionValueRangeProviderMap.get(id);
if (duplicate != null) {
throw new IllegalStateException("2 members (" + duplicate + ", " + memberAccessor
+ ") with a @" + ValueRangeProvider.class.getSimpleName()
+ " annotation must not have the same id (" + id + ").");
}
duplicate = fromEntityValueRangeProviderMap.get(id);
if (duplicate != null) {
throw new IllegalStateException("2 members (" + duplicate + ", " + memberAccessor
+ ") with a @" + ValueRangeProvider.class.getSimpleName()
+ " annotation must not have the same id (" + id + ").");
}
}
public Collection<String> getValueRangeProviderIds() {
List<String> valueRangeProviderIds = new ArrayList<>(
fromSolutionValueRangeProviderMap.size() + fromEntityValueRangeProviderMap.size());
valueRangeProviderIds.addAll(fromSolutionValueRangeProviderMap.keySet());
valueRangeProviderIds.addAll(fromEntityValueRangeProviderMap.keySet());
return valueRangeProviderIds;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/score | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/score/descriptor/ScoreDescriptor.java | package ai.timefold.solver.core.impl.domain.score.descriptor;
import static ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory.MemberAccessorType.FIELD_OR_GETTER_METHOD_WITH_SETTER;
import java.lang.reflect.Member;
import ai.timefold.solver.core.api.domain.solution.PlanningScore;
import ai.timefold.solver.core.api.score.IBendableScore;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.buildin.bendable.BendableScore;
import ai.timefold.solver.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore;
import ai.timefold.solver.core.api.score.buildin.bendablelong.BendableLongScore;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoftbigdecimal.HardMediumSoftBigDecimalScore;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoftlong.HardMediumSoftLongScore;
import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
import ai.timefold.solver.core.api.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScore;
import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
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.api.score.buildin.simplelong.SimpleLongScore;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy;
import ai.timefold.solver.core.impl.score.buildin.BendableBigDecimalScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.BendableLongScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.BendableScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.HardMediumSoftBigDecimalScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.HardMediumSoftLongScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.HardMediumSoftScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.HardSoftBigDecimalScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.HardSoftLongScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.HardSoftScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.SimpleBigDecimalScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.SimpleLongScoreDefinition;
import ai.timefold.solver.core.impl.score.buildin.SimpleScoreDefinition;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
public class ScoreDescriptor {
// Used to obtain default @PlanningScore attribute values from a score member that was auto-discovered,
// as if it had an empty @PlanningScore annotation on it.
@PlanningScore
private static final Object PLANNING_SCORE = new Object();
private final MemberAccessor scoreMemberAccessor;
private final ScoreDefinition<?> scoreDefinition;
private ScoreDescriptor(MemberAccessor scoreMemberAccessor, ScoreDefinition<?> scoreDefinition) {
this.scoreMemberAccessor = scoreMemberAccessor;
this.scoreDefinition = scoreDefinition;
}
public static ScoreDescriptor buildScoreDescriptor(
DescriptorPolicy descriptorPolicy,
Member member,
Class<?> solutionClass) {
MemberAccessor scoreMemberAccessor = buildScoreMemberAccessor(descriptorPolicy, member);
Class<? extends Score<?>> scoreType = extractScoreType(scoreMemberAccessor, solutionClass);
PlanningScore annotation = extractPlanningScoreAnnotation(scoreMemberAccessor);
ScoreDefinition<?> scoreDefinition = buildScoreDefinition(solutionClass, scoreMemberAccessor, scoreType, annotation);
return new ScoreDescriptor(scoreMemberAccessor, scoreDefinition);
}
private static MemberAccessor buildScoreMemberAccessor(DescriptorPolicy descriptorPolicy, Member member) {
return descriptorPolicy.getMemberAccessorFactory().buildAndCacheMemberAccessor(
member,
FIELD_OR_GETTER_METHOD_WITH_SETTER,
PlanningScore.class,
descriptorPolicy.getDomainAccessType());
}
private static Class<? extends Score<?>> extractScoreType(MemberAccessor scoreMemberAccessor, Class<?> solutionClass) {
Class<?> memberType = scoreMemberAccessor.getType();
if (!Score.class.isAssignableFrom(memberType)) {
throw new IllegalStateException("The solutionClass (" + solutionClass
+ ") has a @" + PlanningScore.class.getSimpleName()
+ " annotated member (" + scoreMemberAccessor + ") that does not return a subtype of Score.");
}
if (memberType == Score.class) {
throw new IllegalStateException("The solutionClass (" + solutionClass
+ ") has a @" + PlanningScore.class.getSimpleName()
+ " annotated member (" + scoreMemberAccessor
+ ") that doesn't return a non-abstract " + Score.class.getSimpleName() + " class.\n"
+ "Maybe make it return " + HardSoftScore.class.getSimpleName()
+ " or another specific " + Score.class.getSimpleName() + " implementation.");
}
return (Class<? extends Score<?>>) memberType;
}
private static PlanningScore extractPlanningScoreAnnotation(MemberAccessor scoreMemberAccessor) {
PlanningScore annotation = scoreMemberAccessor.getAnnotation(PlanningScore.class);
if (annotation != null) {
return annotation;
}
// The member was auto-discovered.
try {
return ScoreDescriptor.class.getDeclaredField("PLANNING_SCORE").getAnnotation(PlanningScore.class);
} catch (NoSuchFieldException e) {
throw new IllegalStateException("Impossible situation: the field (PLANNING_SCORE) must exist.", e);
}
}
private static ScoreDefinition<?> buildScoreDefinition(
Class<?> solutionClass,
MemberAccessor scoreMemberAccessor,
Class<? extends Score<?>> scoreType,
PlanningScore annotation) {
Class<? extends ScoreDefinition> scoreDefinitionClass = annotation.scoreDefinitionClass();
int bendableHardLevelsSize = annotation.bendableHardLevelsSize();
int bendableSoftLevelsSize = annotation.bendableSoftLevelsSize();
if (scoreDefinitionClass != PlanningScore.NullScoreDefinition.class) {
if (bendableHardLevelsSize != PlanningScore.NO_LEVEL_SIZE
|| bendableSoftLevelsSize != PlanningScore.NO_LEVEL_SIZE) {
throw new IllegalArgumentException("The solutionClass (" + solutionClass
+ ") has a @" + PlanningScore.class.getSimpleName()
+ " annotated member (" + scoreMemberAccessor
+ ") that has a scoreDefinition (" + scoreDefinitionClass
+ ") that must not have a bendableHardLevelsSize (" + bendableHardLevelsSize
+ ") or a bendableSoftLevelsSize (" + bendableSoftLevelsSize + ").");
}
return ConfigUtils.newInstance(() -> scoreMemberAccessor + " with @" + PlanningScore.class.getSimpleName(),
"scoreDefinitionClass", scoreDefinitionClass);
}
if (!IBendableScore.class.isAssignableFrom(scoreType)) {
if (bendableHardLevelsSize != PlanningScore.NO_LEVEL_SIZE
|| bendableSoftLevelsSize != PlanningScore.NO_LEVEL_SIZE) {
throw new IllegalArgumentException("The solutionClass (" + solutionClass
+ ") has a @" + PlanningScore.class.getSimpleName()
+ " annotated member (" + scoreMemberAccessor
+ ") that returns a scoreType (" + scoreType
+ ") that must not have a bendableHardLevelsSize (" + bendableHardLevelsSize
+ ") or a bendableSoftLevelsSize (" + bendableSoftLevelsSize + ").");
}
if (scoreType.equals(SimpleScore.class)) {
return new SimpleScoreDefinition();
} else if (scoreType.equals(SimpleLongScore.class)) {
return new SimpleLongScoreDefinition();
} else if (scoreType.equals(SimpleBigDecimalScore.class)) {
return new SimpleBigDecimalScoreDefinition();
} else if (scoreType.equals(HardSoftScore.class)) {
return new HardSoftScoreDefinition();
} else if (scoreType.equals(HardSoftLongScore.class)) {
return new HardSoftLongScoreDefinition();
} else if (scoreType.equals(HardSoftBigDecimalScore.class)) {
return new HardSoftBigDecimalScoreDefinition();
} else if (scoreType.equals(HardMediumSoftScore.class)) {
return new HardMediumSoftScoreDefinition();
} else if (scoreType.equals(HardMediumSoftLongScore.class)) {
return new HardMediumSoftLongScoreDefinition();
} else if (scoreType.equals(HardMediumSoftBigDecimalScore.class)) {
return new HardMediumSoftBigDecimalScoreDefinition();
} else {
throw new IllegalArgumentException("The solutionClass (" + solutionClass
+ ") has a @" + PlanningScore.class.getSimpleName()
+ " annotated member (" + scoreMemberAccessor
+ ") that returns a scoreType (" + scoreType
+ ") that is not recognized as a default " + Score.class.getSimpleName() + " implementation.\n"
+ " If you intend to use a custom implementation,"
+ " maybe set a scoreDefinition in the @" + PlanningScore.class.getSimpleName()
+ " annotation.");
}
} else {
if (bendableHardLevelsSize == PlanningScore.NO_LEVEL_SIZE
|| bendableSoftLevelsSize == PlanningScore.NO_LEVEL_SIZE) {
throw new IllegalArgumentException("The solutionClass (" + solutionClass
+ ") has a @" + PlanningScore.class.getSimpleName()
+ " annotated member (" + scoreMemberAccessor
+ ") that returns a scoreType (" + scoreType
+ ") that must have a bendableHardLevelsSize (" + bendableHardLevelsSize
+ ") and a bendableSoftLevelsSize (" + bendableSoftLevelsSize + ").");
}
if (scoreType.equals(BendableScore.class)) {
return new BendableScoreDefinition(bendableHardLevelsSize, bendableSoftLevelsSize);
} else if (scoreType.equals(BendableLongScore.class)) {
return new BendableLongScoreDefinition(bendableHardLevelsSize, bendableSoftLevelsSize);
} else if (scoreType.equals(BendableBigDecimalScore.class)) {
return new BendableBigDecimalScoreDefinition(bendableHardLevelsSize, bendableSoftLevelsSize);
} else {
throw new IllegalArgumentException("The solutionClass (" + solutionClass
+ ") has a @" + PlanningScore.class.getSimpleName()
+ " annotated member (" + scoreMemberAccessor
+ ") that returns a bendable scoreType (" + scoreType
+ ") that is not recognized as a default " + Score.class.getSimpleName() + " implementation.\n"
+ " If you intend to use a custom implementation,"
+ " maybe set a scoreDefinition in the annotation.");
}
}
}
public ScoreDefinition<?> getScoreDefinition() {
return scoreDefinition;
}
public Class<? extends Score<?>> getScoreClass() {
return scoreDefinition.getScoreClass();
}
public Score<?> getScore(Object solution) {
return (Score<?>) scoreMemberAccessor.executeGetter(solution);
}
public void setScore(Object solution, Score<?> score) {
scoreMemberAccessor.executeSetter(solution, score);
}
public void failFastOnDuplicateMember(DescriptorPolicy descriptorPolicy, Member member, Class<?> solutionClass) {
MemberAccessor memberAccessor = buildScoreMemberAccessor(descriptorPolicy, member);
// A solution class cannot have more than one score field or bean property (name check), and the @PlanningScore
// annotation cannot appear on both the score field and its getter (member accessor class check).
if (!scoreMemberAccessor.getName().equals(memberAccessor.getName())
|| !scoreMemberAccessor.getClass().equals(memberAccessor.getClass())) {
throw new IllegalStateException("The solutionClass (" + solutionClass
+ ") has a @" + PlanningScore.class.getSimpleName()
+ " annotated member (" + memberAccessor
+ ") that is duplicated by another member (" + scoreMemberAccessor + ").\n"
+ "Maybe the annotation is defined on both the field and its getter.");
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution/cloner/ConcurrentMemoization.java | package ai.timefold.solver.core.impl.domain.solution.cloner;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
/**
* A thread-safe memoization that caches a calculation.
*
* @param <K> the parameter of the calculation
* @param <V> the result of the calculation
*/
public final class ConcurrentMemoization<K, V> extends ConcurrentHashMap<K, V> {
/**
* An overridden implementation that heavily favors read access over write access speed.
* This is thread-safe.
*
* {@inheritDoc}
*/
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
V value = get(key);
if (value != null) {
return value;
}
return super.computeIfAbsent(key, mappingFunction);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution/cloner/DeepCloningFieldCloner.java | package ai.timefold.solver.core.impl.domain.solution.cloner;
import java.lang.reflect.Field;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
/**
* @implNote This class is thread-safe.
*/
final class DeepCloningFieldCloner {
private final AtomicReference<Metadata> valueDeepCloneDecision = new AtomicReference<>();
private final AtomicInteger fieldDeepCloneDecision = new AtomicInteger(-1);
private final Field field;
public DeepCloningFieldCloner(Field field) {
this.field = Objects.requireNonNull(field);
}
public Field getField() {
return field;
}
/**
*
* @param solutionDescriptor never null
* @param original never null, source object
* @param clone never null, target object
* @return null if cloned, the original uncloned value otherwise
* @param <C>
*/
public <C> Object clone(SolutionDescriptor<?> solutionDescriptor, C original, C clone) {
Object originalValue = FieldCloningUtils.getObjectFieldValue(original, field);
if (deepClone(solutionDescriptor, original.getClass(), originalValue)) { // Defer filling in the field.
return originalValue;
} else { // Shallow copy.
FieldCloningUtils.setObjectFieldValue(clone, field, originalValue);
return null;
}
}
/**
* Obtaining the decision on whether or not to deep-clone is expensive.
* This method exists to cache those computations as much as possible,
* while maintaining thread-safety.
*
* @param solutionDescriptor never null
* @param fieldTypeClass never null
* @param originalValue never null
* @return true if the value needs to be deep-cloned
*/
private boolean deepClone(SolutionDescriptor<?> solutionDescriptor, Class<?> fieldTypeClass, Object originalValue) {
if (originalValue == null) {
return false;
}
/*
* This caching mechanism takes advantage of the fact that, for a particular field on a particular class,
* the types of values contained are unlikely to change and therefore it is safe to cache the calculation.
* In the unlikely event of a cache miss, we recompute.
*/
boolean isValueDeepCloned = valueDeepCloneDecision.updateAndGet(old -> {
Class<?> originalClass = originalValue.getClass();
if (old == null || old.clz != originalClass) {
return new Metadata(originalClass, DeepCloningUtils.isClassDeepCloned(solutionDescriptor, originalClass));
} else {
return old;
}
}).decision;
if (isValueDeepCloned) { // The value has to be deep-cloned. Does not matter what the field says.
return true;
}
/*
* The decision to clone a field is constant once it has been made.
* The fieldTypeClass is guaranteed to not change for the particular field.
*/
if (fieldDeepCloneDecision.get() < 0) {
fieldDeepCloneDecision.set(DeepCloningUtils.isFieldDeepCloned(solutionDescriptor, field, fieldTypeClass) ? 1 : 0);
}
return fieldDeepCloneDecision.get() == 1;
}
private record Metadata(Class<?> clz, boolean decision) {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution/cloner/DeepCloningUtils.java | package ai.timefold.solver.core.impl.domain.solution.cloner;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.MonthDay;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.Period;
import java.time.Year;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.Set;
import java.util.UUID;
import ai.timefold.solver.core.api.domain.solution.cloner.DeepPlanningClone;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.domain.common.ReflectionHelper;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
public final class DeepCloningUtils {
// Instances of these JDK classes will never be deep-cloned.
private static final Set<Class<?>> IMMUTABLE_CLASSES = Set.of(
// Numbers
Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, BigInteger.class, BigDecimal.class,
// Optional
Optional.class, OptionalInt.class, OptionalLong.class, OptionalDouble.class,
// Date and time
Duration.class, Instant.class, LocalDate.class, LocalDateTime.class, LocalTime.class, MonthDay.class,
OffsetDateTime.class, OffsetTime.class, Period.class, Year.class, YearMonth.class, ZonedDateTime.class,
ZoneId.class, ZoneOffset.class,
// Others
Boolean.class, Character.class, String.class, UUID.class);
/**
* Gets the deep cloning decision for a particular value assigned to a field,
* memoizing the result.
*
* @param field the field to get the deep cloning decision of
* @param owningClass the class that owns the field; can be different
* from the field's declaring class (ex: subclass)
* @param actualValueClass the class of the value that is currently assigned
* to the field; can be different from the field type
* (ex: for the field "List myList", the actual value
* class might be ArrayList).
* @return true iff the field should be deep cloned with a particular value.
*/
public static boolean isDeepCloned(SolutionDescriptor<?> solutionDescriptor, Field field, Class<?> owningClass,
Class<?> actualValueClass) {
return isClassDeepCloned(solutionDescriptor, actualValueClass)
|| isFieldDeepCloned(solutionDescriptor, field, owningClass);
}
/**
* Gets the deep cloning decision for a field.
*
* @param field The field to get the deep cloning decision of
* @param owningClass The class that owns the field; can be different
* from the field's declaring class (ex: subclass).
* @return True iff the field should always be deep cloned (regardless of value).
*/
public static boolean isFieldDeepCloned(SolutionDescriptor<?> solutionDescriptor, Field field, Class<?> owningClass) {
Class<?> fieldType = field.getType();
if (isImmutable(fieldType)) {
return false;
} else {
return needsDeepClone(solutionDescriptor, field, owningClass);
}
}
public static boolean needsDeepClone(SolutionDescriptor<?> solutionDescriptor, Field field, Class<?> owningClass) {
return isFieldAnEntityPropertyOnSolution(solutionDescriptor, field, owningClass)
|| isFieldAnEntityOrSolution(solutionDescriptor, field)
|| isFieldAPlanningListVariable(field, owningClass)
|| isFieldADeepCloneProperty(field, owningClass);
}
static boolean isImmutable(Class<?> clz) {
if (clz.isPrimitive() || Score.class.isAssignableFrom(clz)) {
return true;
} else if (clz.isRecord() || clz.isEnum()) {
if (clz.isAnnotationPresent(DeepPlanningClone.class)) {
throw new IllegalStateException("""
The class (%s) is annotated with @%s, but it is immutable.
Deep-cloning enums and records is not supported."""
.formatted(clz.getName(), DeepPlanningClone.class.getSimpleName()));
}
return true;
}
return IMMUTABLE_CLASSES.contains(clz);
}
/**
* Return true only if a field represents an entity property on the solution class.
* An entity property is one who type is a PlanningEntity or a collection
* of PlanningEntity.
*
* @param field The field to get the deep cloning decision of
* @param owningClass The class that owns the field; can be different
* from the field's declaring class (ex: subclass).
* @return True only if the field is an entity property on the solution class.
* May return false if the field getter/setter is complex.
*/
static boolean isFieldAnEntityPropertyOnSolution(SolutionDescriptor<?> solutionDescriptor, Field field,
Class<?> owningClass) {
if (!solutionDescriptor.getSolutionClass().isAssignableFrom(owningClass)) {
return false;
}
// field.getDeclaringClass() is a superclass of or equal to the owningClass
String fieldName = field.getName();
// This assumes we're dealing with a simple getter/setter.
// If that assumption is false, validateCloneSolution(...) fails-fast.
if (solutionDescriptor.getEntityMemberAccessorMap().get(fieldName) != null) {
return true;
}
// This assumes we're dealing with a simple getter/setter.
// If that assumption is false, validateCloneSolution(...) fails-fast.
return solutionDescriptor.getEntityCollectionMemberAccessorMap().get(fieldName) != null;
}
/**
* Returns true iff a field represent an Entity/Solution or a collection
* of Entity/Solution.
*
* @param field The field to get the deep cloning decision of
* @return True only if the field represents or contains a PlanningEntity or PlanningSolution
*/
private static boolean isFieldAnEntityOrSolution(SolutionDescriptor<?> solutionDescriptor, Field field) {
Class<?> type = field.getType();
if (isClassDeepCloned(solutionDescriptor, type)) {
return true;
}
if (Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type)) {
return isTypeArgumentDeepCloned(solutionDescriptor, field.getGenericType());
} else if (type.isArray()) {
return isClassDeepCloned(solutionDescriptor, type.getComponentType());
}
return false;
}
public static boolean isClassDeepCloned(SolutionDescriptor<?> solutionDescriptor, Class<?> type) {
if (isImmutable(type)) {
return false;
}
return solutionDescriptor.hasEntityDescriptor(type)
|| solutionDescriptor.getSolutionClass().isAssignableFrom(type)
|| type.isAnnotationPresent(DeepPlanningClone.class);
}
private static boolean isTypeArgumentDeepCloned(SolutionDescriptor<?> solutionDescriptor, Type genericType) {
// Check the generic type arguments of the field.
// It is possible for fields and methods, but not instances.
if (genericType instanceof ParameterizedType parameterizedType) {
for (Type actualTypeArgument : parameterizedType.getActualTypeArguments()) {
if (actualTypeArgument instanceof Class class1
&& isClassDeepCloned(solutionDescriptor, class1)) {
return true;
}
if (isTypeArgumentDeepCloned(solutionDescriptor, actualTypeArgument)) {
return true;
}
}
}
return false;
}
private static boolean isFieldADeepCloneProperty(Field field, Class<?> owningClass) {
if (field.isAnnotationPresent(DeepPlanningClone.class)) {
return true;
}
Method getterMethod = ReflectionHelper.getGetterMethod(owningClass, field.getName());
return getterMethod != null && getterMethod.isAnnotationPresent(DeepPlanningClone.class);
}
private static boolean isFieldAPlanningListVariable(Field field, Class<?> owningClass) {
if (!field.isAnnotationPresent(PlanningListVariable.class)) {
Method getterMethod = ReflectionHelper.getGetterMethod(owningClass, field.getName());
return getterMethod != null && getterMethod.isAnnotationPresent(PlanningListVariable.class);
} else {
return true;
}
}
private DeepCloningUtils() {
// No external instances.
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution/cloner/FieldAccessingSolutionCloner.java | package ai.timefold.solver.core.impl.domain.solution.cloner;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentMap;
import ai.timefold.solver.core.api.domain.solution.cloner.DeepPlanningClone;
import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
/**
* This class is thread-safe.
*/
public final class FieldAccessingSolutionCloner<Solution_> implements SolutionCloner<Solution_> {
private final SolutionDescriptor<Solution_> solutionDescriptor;
private final ConcurrentMap<Class<?>, Constructor<?>> constructorMemoization = new ConcurrentMemoization<>();
private final ConcurrentMap<Class<?>, ClassMetadata> classMetadataMemoization = new ConcurrentMemoization<>();
public FieldAccessingSolutionCloner(SolutionDescriptor<Solution_> solutionDescriptor) {
this.solutionDescriptor = solutionDescriptor;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Solution_ cloneSolution(Solution_ originalSolution) {
Map<Object, Object> originalToCloneMap = new IdentityHashMap<>();
Queue<Unprocessed> unprocessedQueue = new ArrayDeque<>();
Solution_ cloneSolution = clone(originalSolution, originalToCloneMap, unprocessedQueue,
retrieveClassMetadata(originalSolution.getClass()));
while (!unprocessedQueue.isEmpty()) {
Unprocessed unprocessed = unprocessedQueue.remove();
Object cloneValue = process(unprocessed, originalToCloneMap, unprocessedQueue);
FieldCloningUtils.setObjectFieldValue(unprocessed.bean, unprocessed.field, cloneValue);
}
validateCloneSolution(originalSolution, cloneSolution);
return cloneSolution;
}
/**
* Used by GIZMO when it encounters an undeclared entity class, such as when an abstract planning entity is extended.
*/
public Object gizmoFallbackDeepClone(Object originalValue, Map<Object, Object> originalToCloneMap) {
if (originalValue == null) {
return null;
}
Queue<Unprocessed> unprocessedQueue = new ArrayDeque<>();
Class<?> fieldType = originalValue.getClass();
if (originalValue instanceof Collection<?> collection) {
return cloneCollection(fieldType, collection, originalToCloneMap, unprocessedQueue);
} else if (originalValue instanceof Map<?, ?> map) {
return cloneMap(fieldType, map, originalToCloneMap, unprocessedQueue);
} else if (originalValue.getClass().isArray()) {
return cloneArray(fieldType, originalValue, originalToCloneMap, unprocessedQueue);
} else {
return clone(originalValue, originalToCloneMap, unprocessedQueue,
retrieveClassMetadata(originalValue.getClass()));
}
}
private Object process(Unprocessed unprocessed, Map<Object, Object> originalToCloneMap,
Queue<Unprocessed> unprocessedQueue) {
Object originalValue = unprocessed.originalValue;
Field field = unprocessed.field;
Class<?> fieldType = field.getType();
if (originalValue instanceof Collection<?> collection) {
return cloneCollection(fieldType, collection, originalToCloneMap, unprocessedQueue);
} else if (originalValue instanceof Map<?, ?> map) {
return cloneMap(fieldType, map, originalToCloneMap, unprocessedQueue);
} else if (originalValue.getClass().isArray()) {
return cloneArray(fieldType, originalValue, originalToCloneMap, unprocessedQueue);
} else {
return clone(originalValue, originalToCloneMap, unprocessedQueue,
retrieveClassMetadata(originalValue.getClass()));
}
}
private <C> C clone(C original, Map<Object, Object> originalToCloneMap, Queue<Unprocessed> unprocessedQueue,
ClassMetadata declaringClassMetadata) {
if (original == null) {
return null;
}
C existingClone = (C) originalToCloneMap.get(original);
if (existingClone != null) {
return existingClone;
}
Class<C> declaringClass = (Class<C>) original.getClass();
C clone = constructClone(declaringClass);
originalToCloneMap.put(original, clone);
copyFields(declaringClass, original, clone, unprocessedQueue, declaringClassMetadata);
return clone;
}
private <C> C constructClone(Class<C> clazz) {
var constructor = constructorMemoization.computeIfAbsent(clazz, key -> {
try {
var ctor = (Constructor<C>) key.getDeclaredConstructor();
ctor.setAccessible(true);
return ctor;
} catch (ReflectiveOperationException e) {
throw new IllegalStateException(
"To create a planning clone, the class (%s) must have a no-arg constructor."
.formatted(key.getCanonicalName()),
e);
}
});
try {
return (C) constructor.newInstance();
} catch (Exception e) {
throw new IllegalStateException(
"Can not create a new instance of class (%s) for a planning clone, using its no-arg constructor."
.formatted(clazz.getCanonicalName()),
e);
}
}
private <C> void copyFields(Class<C> clazz, C original, C clone, Queue<Unprocessed> unprocessedQueue,
ClassMetadata declaringClassMetadata) {
for (ShallowCloningFieldCloner fieldCloner : declaringClassMetadata.getCopiedFieldArray()) {
fieldCloner.clone(original, clone);
}
for (DeepCloningFieldCloner fieldCloner : declaringClassMetadata.getClonedFieldArray()) {
Object unprocessedValue = fieldCloner.clone(solutionDescriptor, original, clone);
if (unprocessedValue != null) {
unprocessedQueue.add(new Unprocessed(clone, fieldCloner.getField(), unprocessedValue));
}
}
Class<? super C> superclass = clazz.getSuperclass();
if (superclass != null && superclass != Object.class) {
copyFields(superclass, original, clone, unprocessedQueue, retrieveClassMetadata(superclass));
}
}
private Object cloneArray(Class<?> expectedType, Object originalArray, Map<Object, Object> originalToCloneMap,
Queue<Unprocessed> unprocessedQueue) {
int arrayLength = Array.getLength(originalArray);
Object cloneArray = Array.newInstance(originalArray.getClass().getComponentType(), arrayLength);
if (!expectedType.isInstance(cloneArray)) {
throw new IllegalStateException("The cloneArrayClass (" + cloneArray.getClass()
+ ") created for originalArrayClass (" + originalArray.getClass()
+ ") is not assignable to the field's type (" + expectedType + ").\n"
+ "Maybe consider replacing the default " + SolutionCloner.class.getSimpleName() + ".");
}
for (int i = 0; i < arrayLength; i++) {
Object cloneElement =
cloneCollectionsElementIfNeeded(Array.get(originalArray, i), originalToCloneMap, unprocessedQueue);
Array.set(cloneArray, i, cloneElement);
}
return cloneArray;
}
private <E> Collection<E> cloneCollection(Class<?> expectedType, Collection<E> originalCollection,
Map<Object, Object> originalToCloneMap, Queue<Unprocessed> unprocessedQueue) {
Collection<E> cloneCollection = constructCloneCollection(originalCollection);
if (!expectedType.isInstance(cloneCollection)) {
throw new IllegalStateException("The cloneCollectionClass (" + cloneCollection.getClass()
+ ") created for originalCollectionClass (" + originalCollection.getClass()
+ ") is not assignable to the field's type (" + expectedType + ").\n"
+ "Maybe consider replacing the default " + SolutionCloner.class.getSimpleName() + ".");
}
for (E originalElement : originalCollection) {
E cloneElement = cloneCollectionsElementIfNeeded(originalElement, originalToCloneMap, unprocessedQueue);
cloneCollection.add(cloneElement);
}
return cloneCollection;
}
private static <E> Collection<E> constructCloneCollection(Collection<E> originalCollection) {
// TODO Don't hardcode all standard collections
if (originalCollection instanceof LinkedList) {
return new LinkedList<>();
}
var size = originalCollection.size();
if (originalCollection instanceof Set) {
if (originalCollection instanceof SortedSet<E> set) {
var setComparator = set.comparator();
return new TreeSet<>(setComparator);
} else if (!(originalCollection instanceof LinkedHashSet)) {
return new HashSet<>(size);
} else { // Default to a LinkedHashSet to respect order.
return new LinkedHashSet<>(size);
}
} else if (originalCollection instanceof Deque) {
return new ArrayDeque<>(size);
}
// Default collection
return new ArrayList<>(size);
}
private <K, V> Map<K, V> cloneMap(Class<?> expectedType, Map<K, V> originalMap, Map<Object, Object> originalToCloneMap,
Queue<Unprocessed> unprocessedQueue) {
Map<K, V> cloneMap = constructCloneMap(originalMap);
if (!expectedType.isInstance(cloneMap)) {
throw new IllegalStateException("The cloneMapClass (" + cloneMap.getClass()
+ ") created for originalMapClass (" + originalMap.getClass()
+ ") is not assignable to the field's type (" + expectedType + ").\n"
+ "Maybe consider replacing the default " + SolutionCloner.class.getSimpleName() + ".");
}
for (Map.Entry<K, V> originalEntry : originalMap.entrySet()) {
K cloneKey = cloneCollectionsElementIfNeeded(originalEntry.getKey(), originalToCloneMap, unprocessedQueue);
V cloneValue = cloneCollectionsElementIfNeeded(originalEntry.getValue(), originalToCloneMap, unprocessedQueue);
cloneMap.put(cloneKey, cloneValue);
}
return cloneMap;
}
private static <K, V> Map<K, V> constructCloneMap(Map<K, V> originalMap) {
// Normally, a Map will never be selected for cloning, but extending implementations might anyway.
if (originalMap instanceof SortedMap<K, V> map) {
var setComparator = map.comparator();
return new TreeMap<>(setComparator);
}
var originalMapSize = originalMap.size();
if (!(originalMap instanceof LinkedHashMap)) {
return new HashMap<>(originalMapSize);
} else { // Default to a LinkedHashMap to respect order.
return new LinkedHashMap<>(originalMapSize);
}
}
private ClassMetadata retrieveClassMetadata(Class<?> declaringClass) {
return classMetadataMemoization.computeIfAbsent(declaringClass, ClassMetadata::new);
}
private <C> C cloneCollectionsElementIfNeeded(C original, Map<Object, Object> originalToCloneMap,
Queue<Unprocessed> unprocessedQueue) {
if (original == null) {
return null;
}
/*
* Because an element which is itself a Collection or Map might hold an entity,
* we clone it too.
* The List<Long> in Map<String, List<Long>> needs to be cloned if the List<Long> is a shadow,
* despite that Long never needs to be cloned (because it's immutable).
*/
if (original instanceof Collection<?> collection) {
return (C) cloneCollection(Collection.class, collection, originalToCloneMap, unprocessedQueue);
} else if (original instanceof Map<?, ?> map) {
return (C) cloneMap(Map.class, map, originalToCloneMap, unprocessedQueue);
} else if (original.getClass().isArray()) {
return (C) cloneArray(original.getClass(), original, originalToCloneMap, unprocessedQueue);
}
ClassMetadata classMetadata = retrieveClassMetadata(original.getClass());
if (classMetadata.isDeepCloned) {
return clone(original, originalToCloneMap, unprocessedQueue, classMetadata);
} else {
return original;
}
}
/**
* Fails fast if {@link DeepCloningUtils#isFieldAnEntityPropertyOnSolution} assumptions were wrong.
*
* @param originalSolution never null
* @param cloneSolution never null
*/
private void validateCloneSolution(Solution_ originalSolution, Solution_ cloneSolution) {
for (MemberAccessor memberAccessor : solutionDescriptor.getEntityMemberAccessorMap().values()) {
validateCloneProperty(originalSolution, cloneSolution, memberAccessor);
}
for (MemberAccessor memberAccessor : solutionDescriptor.getEntityCollectionMemberAccessorMap().values()) {
validateCloneProperty(originalSolution, cloneSolution, memberAccessor);
}
}
private static <Solution_> void validateCloneProperty(Solution_ originalSolution, Solution_ cloneSolution,
MemberAccessor memberAccessor) {
Object originalProperty = memberAccessor.executeGetter(originalSolution);
if (originalProperty != null) {
Object cloneProperty = memberAccessor.executeGetter(cloneSolution);
if (originalProperty == cloneProperty) {
throw new IllegalStateException(
"The solutionProperty (" + memberAccessor.getName() + ") was not cloned as expected."
+ " The " + FieldAccessingSolutionCloner.class.getSimpleName() + " failed to recognize"
+ " that property's field, probably because its field name is different.");
}
}
}
private final class ClassMetadata {
private final Class<?> declaringClass;
private final boolean isDeepCloned;
/**
* Contains one cloner for every field that needs to be shallow cloned (= copied).
*/
private ShallowCloningFieldCloner[] copiedFieldArray;
/**
* Contains one cloner for every field that needs to be deep-cloned.
*/
private DeepCloningFieldCloner[] clonedFieldArray;
public ClassMetadata(Class<?> declaringClass) {
this.declaringClass = declaringClass;
this.isDeepCloned = DeepCloningUtils.isClassDeepCloned(solutionDescriptor, declaringClass);
}
public ShallowCloningFieldCloner[] getCopiedFieldArray() {
if (copiedFieldArray == null) { // Lazy-loaded; some types (such as String) will never get here.
copiedFieldArray = Arrays.stream(declaringClass.getDeclaredFields())
.filter(f -> !Modifier.isStatic(f.getModifiers()))
.filter(field -> DeepCloningUtils.isImmutable(field.getType()))
.peek(f -> {
if (DeepCloningUtils.needsDeepClone(solutionDescriptor, f, declaringClass)) {
throw new IllegalStateException("""
The field (%s) of class (%s) needs to be deep-cloned,
but its type (%s) is immutable and can not be deep-cloned.
Maybe remove the @%s annotation from the field?
Maybe do not reference planning entities inside Java records?
"""
.strip()
.formatted(f.getName(), declaringClass.getCanonicalName(),
f.getType().getCanonicalName(), DeepPlanningClone.class.getSimpleName()));
} else {
f.setAccessible(true);
}
})
.map(ShallowCloningFieldCloner::of)
.toArray(ShallowCloningFieldCloner[]::new);
}
return copiedFieldArray;
}
public DeepCloningFieldCloner[] getClonedFieldArray() {
if (clonedFieldArray == null) { // Lazy-loaded; some types (such as String) will never get here.
clonedFieldArray = Arrays.stream(declaringClass.getDeclaredFields())
.filter(f -> !Modifier.isStatic(f.getModifiers()))
.filter(field -> !DeepCloningUtils.isImmutable(field.getType()))
.peek(f -> f.setAccessible(true))
.map(DeepCloningFieldCloner::new)
.toArray(DeepCloningFieldCloner[]::new);
}
return clonedFieldArray;
}
}
private record Unprocessed(Object bean, Field field, Object originalValue) {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution/cloner/FieldCloningUtils.java | package ai.timefold.solver.core.impl.domain.solution.cloner;
import java.lang.reflect.Field;
final class FieldCloningUtils {
static void copyBoolean(Field field, Object original, Object clone) {
boolean originalValue = getBooleanFieldValue(original, field);
setFieldValue(clone, field, originalValue);
}
private static boolean getBooleanFieldValue(Object bean, Field field) {
try {
return field.getBoolean(bean);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnRead(bean, field, e);
}
}
private static void setFieldValue(Object bean, Field field, boolean value) {
try {
field.setBoolean(bean, value);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnWrite(bean, field, value, e);
}
}
static void copyByte(Field field, Object original, Object clone) {
byte originalValue = getByteFieldValue(original, field);
setFieldValue(clone, field, originalValue);
}
private static byte getByteFieldValue(Object bean, Field field) {
try {
return field.getByte(bean);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnRead(bean, field, e);
}
}
private static void setFieldValue(Object bean, Field field, byte value) {
try {
field.setByte(bean, value);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnWrite(bean, field, value, e);
}
}
static void copyChar(Field field, Object original, Object clone) {
char originalValue = getCharFieldValue(original, field);
setFieldValue(clone, field, originalValue);
}
private static char getCharFieldValue(Object bean, Field field) {
try {
return field.getChar(bean);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnRead(bean, field, e);
}
}
private static void setFieldValue(Object bean, Field field, char value) {
try {
field.setChar(bean, value);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnWrite(bean, field, value, e);
}
}
static void copyShort(Field field, Object original, Object clone) {
short originalValue = getShortFieldValue(original, field);
setFieldValue(clone, field, originalValue);
}
private static short getShortFieldValue(Object bean, Field field) {
try {
return field.getShort(bean);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnRead(bean, field, e);
}
}
private static void setFieldValue(Object bean, Field field, short value) {
try {
field.setShort(bean, value);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnWrite(bean, field, value, e);
}
}
static void copyInt(Field field, Object original, Object clone) {
int originalValue = getIntFieldValue(original, field);
setFieldValue(clone, field, originalValue);
}
private static int getIntFieldValue(Object bean, Field field) {
try {
return field.getInt(bean);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnRead(bean, field, e);
}
}
private static void setFieldValue(Object bean, Field field, int value) {
try {
field.setInt(bean, value);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnWrite(bean, field, value, e);
}
}
static void copyLong(Field field, Object original, Object clone) {
long originalValue = getLongFieldValue(original, field);
setFieldValue(clone, field, originalValue);
}
private static long getLongFieldValue(Object bean, Field field) {
try {
return field.getLong(bean);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnRead(bean, field, e);
}
}
private static void setFieldValue(Object bean, Field field, long value) {
try {
field.setLong(bean, value);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnWrite(bean, field, value, e);
}
}
static void copyFloat(Field field, Object original, Object clone) {
float originalValue = getFloatFieldValue(original, field);
setFieldValue(clone, field, originalValue);
}
private static float getFloatFieldValue(Object bean, Field field) {
try {
return field.getFloat(bean);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnRead(bean, field, e);
}
}
private static void setFieldValue(Object bean, Field field, float value) {
try {
field.setFloat(bean, value);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnWrite(bean, field, value, e);
}
}
static void copyDouble(Field field, Object original, Object clone) {
double originalValue = getDoubleFieldValue(original, field);
setFieldValue(clone, field, originalValue);
}
private static double getDoubleFieldValue(Object bean, Field field) {
try {
return field.getDouble(bean);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnRead(bean, field, e);
}
}
private static void setFieldValue(Object bean, Field field, double value) {
try {
field.setDouble(bean, value);
} catch (IllegalAccessException e) {
throw FieldCloningUtils.createExceptionOnWrite(bean, field, value, e);
}
}
static void copyObject(Field field, Object original, Object clone) {
Object originalValue = FieldCloningUtils.getObjectFieldValue(original, field);
FieldCloningUtils.setObjectFieldValue(clone, field, originalValue);
}
static Object getObjectFieldValue(Object bean, Field field) {
try {
return field.get(bean);
} catch (IllegalAccessException e) {
throw createExceptionOnRead(bean, field, e);
}
}
private static RuntimeException createExceptionOnRead(Object bean, Field field, Exception rootCause) {
return new IllegalStateException("The class (" + bean.getClass() + ") has a field (" + field
+ ") which cannot be read to create a planning clone.", rootCause);
}
static void setObjectFieldValue(Object bean, Field field, Object value) {
try {
field.set(bean, value);
} catch (IllegalAccessException e) {
throw createExceptionOnWrite(bean, field, value, e);
}
}
private static RuntimeException createExceptionOnWrite(Object bean, Field field, Object value, Exception rootCause) {
return new IllegalStateException("The class (" + bean.getClass() + ") has a field (" + field
+ ") which cannot be written with the value (" + value + ") to create a planning clone.", rootCause);
}
private FieldCloningUtils() {
// No external instances.
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution/cloner/ShallowCloningFieldCloner.java | package ai.timefold.solver.core.impl.domain.solution.cloner;
import java.lang.reflect.Field;
import java.util.Objects;
import ai.timefold.solver.core.api.function.TriConsumer;
final class ShallowCloningFieldCloner {
public static ShallowCloningFieldCloner of(Field field) {
Class<?> fieldType = field.getType();
if (fieldType == boolean.class) {
return new ShallowCloningFieldCloner(field, FieldCloningUtils::copyBoolean);
} else if (fieldType == byte.class) {
return new ShallowCloningFieldCloner(field, FieldCloningUtils::copyByte);
} else if (fieldType == char.class) {
return new ShallowCloningFieldCloner(field, FieldCloningUtils::copyChar);
} else if (fieldType == short.class) {
return new ShallowCloningFieldCloner(field, FieldCloningUtils::copyShort);
} else if (fieldType == int.class) {
return new ShallowCloningFieldCloner(field, FieldCloningUtils::copyInt);
} else if (fieldType == long.class) {
return new ShallowCloningFieldCloner(field, FieldCloningUtils::copyLong);
} else if (fieldType == float.class) {
return new ShallowCloningFieldCloner(field, FieldCloningUtils::copyFloat);
} else if (fieldType == double.class) {
return new ShallowCloningFieldCloner(field, FieldCloningUtils::copyDouble);
} else {
return new ShallowCloningFieldCloner(field, FieldCloningUtils::copyObject);
}
}
private final Field field;
private final TriConsumer<Field, Object, Object> copyOperation;
private ShallowCloningFieldCloner(Field field, TriConsumer<Field, Object, Object> copyOperation) {
this.field = Objects.requireNonNull(field);
this.copyOperation = Objects.requireNonNull(copyOperation);
}
public <C> void clone(C original, C clone) {
copyOperation.accept(field, original, clone);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution/cloner | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution/cloner/gizmo/GizmoCloningUtils.java | package ai.timefold.solver.core.impl.domain.solution.cloner.gizmo;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import ai.timefold.solver.core.impl.domain.solution.cloner.DeepCloningUtils;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
public final class GizmoCloningUtils {
public static Set<Class<?>> getDeepClonedClasses(SolutionDescriptor<?> solutionDescriptor,
Collection<Class<?>> entitySubclasses) {
Set<Class<?>> deepClonedClassSet = new HashSet<>();
Set<Class<?>> classesToProcess = new LinkedHashSet<>(solutionDescriptor.getEntityClassSet());
classesToProcess.add(solutionDescriptor.getSolutionClass());
classesToProcess.addAll(entitySubclasses);
for (Class<?> clazz : classesToProcess) {
deepClonedClassSet.add(clazz);
for (Field field : getAllFields(clazz)) {
deepClonedClassSet.addAll(getDeepClonedTypeArguments(solutionDescriptor, field.getGenericType()));
if (DeepCloningUtils.isFieldDeepCloned(solutionDescriptor, field, clazz)) {
deepClonedClassSet.add(field.getType());
}
}
}
return deepClonedClassSet;
}
/**
* @return never null
*/
private static Set<Class<?>> getDeepClonedTypeArguments(SolutionDescriptor<?> solutionDescriptor, Type genericType) {
// Check the generic type arguments of the field.
// It is possible for fields and methods, but not instances.
if (!(genericType instanceof ParameterizedType)) {
return Collections.emptySet();
}
Set<Class<?>> deepClonedTypeArguments = new HashSet<>();
ParameterizedType parameterizedType = (ParameterizedType) genericType;
for (Type actualTypeArgument : parameterizedType.getActualTypeArguments()) {
if (actualTypeArgument instanceof Class class1
&& DeepCloningUtils.isClassDeepCloned(solutionDescriptor, class1)) {
deepClonedTypeArguments.add(class1);
}
deepClonedTypeArguments.addAll(getDeepClonedTypeArguments(solutionDescriptor, actualTypeArgument));
}
return deepClonedTypeArguments;
}
private static List<Field> getAllFields(Class<?> baseClass) {
Class<?> clazz = baseClass;
Stream<Field> memberStream = Stream.empty();
while (clazz != null) {
Stream<Field> fieldStream = Stream.of(clazz.getDeclaredFields());
memberStream = Stream.concat(memberStream, fieldStream);
clazz = clazz.getSuperclass();
}
return memberStream.collect(Collectors.toList());
}
private GizmoCloningUtils() {
// No external instances.
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution/cloner | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution/cloner/gizmo/GizmoSolutionClonerImplementor.java | package ai.timefold.solver.core.impl.domain.solution.cloner.gizmo;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner;
import ai.timefold.solver.core.impl.domain.common.accessor.gizmo.GizmoClassLoader;
import ai.timefold.solver.core.impl.domain.common.accessor.gizmo.GizmoMemberDescriptor;
import ai.timefold.solver.core.impl.domain.solution.cloner.DeepCloningUtils;
import ai.timefold.solver.core.impl.domain.solution.cloner.FieldAccessingSolutionCloner;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.util.MutableReference;
import io.quarkus.gizmo.AssignableResultHandle;
import io.quarkus.gizmo.BranchResult;
import io.quarkus.gizmo.BytecodeCreator;
import io.quarkus.gizmo.ClassCreator;
import io.quarkus.gizmo.ClassOutput;
import io.quarkus.gizmo.FieldDescriptor;
import io.quarkus.gizmo.MethodCreator;
import io.quarkus.gizmo.MethodDescriptor;
import io.quarkus.gizmo.ResultHandle;
public class GizmoSolutionClonerImplementor {
private static final MethodDescriptor EQUALS_METHOD = MethodDescriptor.ofMethod(Object.class, "equals", boolean.class,
Object.class);
protected static final MethodDescriptor GET_METHOD = MethodDescriptor.ofMethod(Map.class, "get", Object.class,
Object.class);
private static final MethodDescriptor PUT_METHOD = MethodDescriptor.ofMethod(Map.class, "put", Object.class,
Object.class, Object.class);
private static final String FALLBACK_CLONER = "fallbackCloner";
public static final boolean DEBUG = false;
/**
* Return a comparator that sorts classes into instanceof check order.
* In particular, if x is a subclass of y, then x will appear earlier
* than y in the list.
*
* @param deepClonedClassSet The set of classes to generate a comparator for
* @return A comparator that sorts classes from deepClonedClassSet such that
* x < y if x is assignable from y.
*/
public static Comparator<Class<?>> getInstanceOfComparator(Set<Class<?>> deepClonedClassSet) {
Map<Class<?>, Integer> classToSubclassLevel = new HashMap<>();
deepClonedClassSet
.forEach(clazz -> {
if (deepClonedClassSet.stream()
.allMatch(
otherClazz -> clazz.isAssignableFrom(otherClazz) || !otherClazz.isAssignableFrom(clazz))) {
classToSubclassLevel.put(clazz, 0);
}
});
boolean isChanged = true;
while (isChanged) {
// Need to iterate over all classes
// since maxSubclassLevel can change
// (for instance, Tiger extends Cat (1) implements Animal (0))
isChanged = false;
for (Class<?> clazz : deepClonedClassSet) {
Optional<Integer> maxParentSubclassLevel = classToSubclassLevel.keySet().stream()
.filter(otherClazz -> otherClazz != clazz && otherClazz.isAssignableFrom(clazz))
.map(classToSubclassLevel::get)
.max(Integer::compare);
if (maxParentSubclassLevel.isPresent()) {
Integer oldVal = classToSubclassLevel.getOrDefault(clazz, -1);
Integer newVal = maxParentSubclassLevel.get() + 1;
if (newVal.compareTo(oldVal) > 0) {
isChanged = true;
classToSubclassLevel.put(clazz, newVal);
}
}
}
}
return Comparator.<Class<?>, Integer> comparing(classToSubclassLevel::get)
.thenComparing(Class::getName).reversed();
}
protected void createFields(ClassCreator classCreator) {
classCreator.getFieldCreator(FALLBACK_CLONER, FieldAccessingSolutionCloner.class)
.setModifiers(Modifier.PRIVATE | Modifier.STATIC);
}
/**
* Generates the constructor and implementations of SolutionCloner methods for the given SolutionDescriptor using the given
* ClassCreator
*/
public static void defineClonerFor(ClassCreator classCreator,
SolutionDescriptor<?> solutionDescriptor,
Set<Class<?>> solutionClassSet,
Map<Class<?>, GizmoSolutionOrEntityDescriptor> memoizedSolutionOrEntityDescriptorMap,
Set<Class<?>> deepClonedClassSet) {
defineClonerFor(GizmoSolutionClonerImplementor::new, classCreator, solutionDescriptor, solutionClassSet,
memoizedSolutionOrEntityDescriptorMap, deepClonedClassSet);
}
/**
* Generates the constructor and implementations of SolutionCloner
* methods for the given SolutionDescriptor using the given ClassCreator
*/
public static void defineClonerFor(Supplier<GizmoSolutionClonerImplementor> implementorSupplier,
ClassCreator classCreator,
SolutionDescriptor<?> solutionDescriptor,
Set<Class<?>> solutionClassSet,
Map<Class<?>, GizmoSolutionOrEntityDescriptor> memoizedSolutionOrEntityDescriptorMap,
Set<Class<?>> deepClonedClassSet) {
GizmoSolutionClonerImplementor implementor = implementorSupplier.get();
// Classes that are not instances of any other class in the collection
// have a subclass level of 0.
// Other classes subclass level is the maximum of the subclass level
// of the classes it is a subclass of + 1
Set<Class<?>> deepCloneClassesThatAreNotSolutionSet =
deepClonedClassSet.stream()
.filter(clazz -> !solutionClassSet.contains(clazz) && !clazz.isArray())
.filter(clazz -> !clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers()))
.collect(Collectors.toSet());
Comparator<Class<?>> instanceOfComparator = getInstanceOfComparator(deepClonedClassSet);
SortedSet<Class<?>> deepCloneClassesThatAreNotSolutionSortedSet = new TreeSet<>(instanceOfComparator);
deepCloneClassesThatAreNotSolutionSortedSet.addAll(deepCloneClassesThatAreNotSolutionSet);
implementor.createFields(classCreator);
implementor.createConstructor(classCreator);
implementor.createSetSolutionDescriptor(classCreator, solutionDescriptor);
implementor.createCloneSolution(classCreator, solutionDescriptor);
implementor.createCloneSolutionRun(classCreator, solutionDescriptor, solutionClassSet,
memoizedSolutionOrEntityDescriptorMap,
deepCloneClassesThatAreNotSolutionSortedSet, instanceOfComparator);
for (Class<?> deepClonedClass : deepCloneClassesThatAreNotSolutionSortedSet) {
implementor.createDeepCloneHelperMethod(classCreator, deepClonedClass, solutionDescriptor,
memoizedSolutionOrEntityDescriptorMap,
deepCloneClassesThatAreNotSolutionSortedSet);
}
Set<Class<?>> abstractDeepCloneClassSet =
deepClonedClassSet.stream()
.filter(clazz -> !solutionClassSet.contains(clazz) && !clazz.isArray())
.filter(clazz -> clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers()))
.collect(Collectors.toSet());
for (Class<?> abstractDeepClonedClass : abstractDeepCloneClassSet) {
implementor.createAbstractDeepCloneHelperMethod(classCreator, abstractDeepClonedClass, solutionDescriptor,
memoizedSolutionOrEntityDescriptorMap,
deepCloneClassesThatAreNotSolutionSortedSet);
}
}
public static ClassOutput createClassOutputWithDebuggingCapability(MutableReference<byte[]> classBytecodeHolder) {
return (path, byteCode) -> {
classBytecodeHolder.setValue(byteCode);
if (DEBUG) {
Path debugRoot = Paths.get("target/timefold-solver-generated-classes");
Path rest = Paths.get(path + ".class");
Path destination = debugRoot.resolve(rest);
try {
Files.createDirectories(destination.getParent());
Files.write(destination, byteCode);
} catch (IOException e) {
throw new IllegalStateException("Fail to write debug class file " + destination + ".", e);
}
}
};
}
static <T> SolutionCloner<T> createClonerFor(SolutionDescriptor<T> solutionDescriptor,
GizmoClassLoader gizmoClassLoader) {
GizmoSolutionClonerImplementor implementor = new GizmoSolutionClonerImplementor();
String className = GizmoSolutionClonerFactory.getGeneratedClassName(solutionDescriptor);
if (gizmoClassLoader.hasBytecodeFor(className)) {
return implementor.createInstance(className, gizmoClassLoader, solutionDescriptor);
}
MutableReference<byte[]> classBytecodeHolder = new MutableReference<>(null);
ClassCreator classCreator = ClassCreator.builder()
.className(className)
.interfaces(GizmoSolutionCloner.class)
.superClass(Object.class)
.classOutput(createClassOutputWithDebuggingCapability(classBytecodeHolder))
.setFinal(true)
.build();
Set<Class<?>> deepClonedClassSet = GizmoCloningUtils.getDeepClonedClasses(solutionDescriptor, Collections.emptyList());
defineClonerFor(() -> implementor, classCreator, solutionDescriptor,
Collections.singleton(solutionDescriptor.getSolutionClass()),
new HashMap<>(), deepClonedClassSet);
classCreator.close();
byte[] classBytecode = classBytecodeHolder.getValue();
gizmoClassLoader.storeBytecode(className, classBytecode);
return implementor.createInstance(className, gizmoClassLoader, solutionDescriptor);
}
private <T> SolutionCloner<T> createInstance(String className, ClassLoader gizmoClassLoader,
SolutionDescriptor<T> solutionDescriptor) {
try {
@SuppressWarnings("unchecked")
Class<? extends GizmoSolutionCloner<T>> outClass =
(Class<? extends GizmoSolutionCloner<T>>) gizmoClassLoader.loadClass(className);
GizmoSolutionCloner<T> out = outClass.getConstructor().newInstance();
out.setSolutionDescriptor(solutionDescriptor);
return out;
} catch (InvocationTargetException | InstantiationException | IllegalAccessException | ClassNotFoundException
| NoSuchMethodException e) {
throw new IllegalStateException(e);
}
}
private void createConstructor(ClassCreator classCreator) {
MethodCreator methodCreator = classCreator.getMethodCreator(
MethodDescriptor.ofConstructor(classCreator.getClassName()));
ResultHandle thisObj = methodCreator.getThis();
// Invoke Object's constructor
methodCreator.invokeSpecialMethod(MethodDescriptor.ofConstructor(Object.class), thisObj);
// Return this (it a constructor)
methodCreator.returnValue(thisObj);
}
protected void createSetSolutionDescriptor(ClassCreator classCreator, SolutionDescriptor<?> solutionDescriptor) {
MethodCreator methodCreator = classCreator.getMethodCreator(
MethodDescriptor.ofMethod(GizmoSolutionCloner.class, "setSolutionDescriptor", void.class,
SolutionDescriptor.class));
methodCreator.writeStaticField(FieldDescriptor.of(
GizmoSolutionClonerFactory.getGeneratedClassName(solutionDescriptor),
FALLBACK_CLONER, FieldAccessingSolutionCloner.class),
methodCreator.newInstance(
MethodDescriptor.ofConstructor(FieldAccessingSolutionCloner.class, SolutionDescriptor.class),
methodCreator.getMethodParam(0)));
methodCreator.returnValue(null);
}
private void createCloneSolution(ClassCreator classCreator, SolutionDescriptor<?> solutionDescriptor) {
Class<?> solutionClass = solutionDescriptor.getSolutionClass();
MethodCreator methodCreator =
classCreator.getMethodCreator(MethodDescriptor.ofMethod(SolutionCloner.class,
"cloneSolution",
Object.class,
Object.class));
ResultHandle thisObj = methodCreator.getMethodParam(0);
ResultHandle clone = methodCreator.invokeStaticMethod(
MethodDescriptor.ofMethod(
GizmoSolutionClonerFactory.getGeneratedClassName(solutionDescriptor),
"cloneSolutionRun", solutionClass, solutionClass, Map.class),
thisObj,
methodCreator.newInstance(MethodDescriptor.ofConstructor(IdentityHashMap.class)));
methodCreator.returnValue(clone);
}
private void createCloneSolutionRun(ClassCreator classCreator, SolutionDescriptor solutionDescriptor,
Set<Class<?>> solutionClassSet,
Map<Class<?>, GizmoSolutionOrEntityDescriptor> memoizedSolutionOrEntityDescriptorMap,
SortedSet<Class<?>> deepClonedClassesSortedSet, Comparator<Class<?>> instanceOfComparator) {
Class<?> solutionClass = solutionDescriptor.getSolutionClass();
MethodCreator methodCreator =
classCreator.getMethodCreator("cloneSolutionRun", solutionClass, solutionClass, Map.class);
methodCreator.setModifiers(Modifier.STATIC | Modifier.PRIVATE);
ResultHandle thisObj = methodCreator.getMethodParam(0);
BranchResult solutionNullBranchResult = methodCreator.ifNull(thisObj);
BytecodeCreator solutionIsNullBranch = solutionNullBranchResult.trueBranch();
solutionIsNullBranch.returnValue(thisObj); // thisObj is null
BytecodeCreator solutionIsNotNullBranch = solutionNullBranchResult.falseBranch();
ResultHandle createdCloneMap = methodCreator.getMethodParam(1);
ResultHandle maybeClone = solutionIsNotNullBranch.invokeInterfaceMethod(
GET_METHOD, createdCloneMap, thisObj);
BranchResult hasCloneBranchResult = solutionIsNotNullBranch.ifNotNull(maybeClone);
BytecodeCreator hasCloneBranch = hasCloneBranchResult.trueBranch();
hasCloneBranch.returnValue(maybeClone);
BytecodeCreator noCloneBranch = hasCloneBranchResult.falseBranch();
List<Class<?>> sortedSolutionClassList = new ArrayList<>(solutionClassSet);
sortedSolutionClassList.sort(instanceOfComparator);
BytecodeCreator currentBranch = noCloneBranch;
ResultHandle thisObjClass =
currentBranch.invokeVirtualMethod(MethodDescriptor.ofMethod(Object.class, "getClass", Class.class), thisObj);
for (Class<?> solutionSubclass : sortedSolutionClassList) {
ResultHandle solutionSubclassResultHandle = currentBranch.loadClass(solutionSubclass);
ResultHandle isSubclass =
currentBranch.invokeVirtualMethod(EQUALS_METHOD, solutionSubclassResultHandle, thisObjClass);
BranchResult isSubclassBranchResult = currentBranch.ifTrue(isSubclass);
BytecodeCreator isSubclassBranch = isSubclassBranchResult.trueBranch();
GizmoSolutionOrEntityDescriptor solutionSubclassDescriptor =
memoizedSolutionOrEntityDescriptorMap.computeIfAbsent(solutionSubclass,
(key) -> new GizmoSolutionOrEntityDescriptor(solutionDescriptor, solutionSubclass));
ResultHandle clone = isSubclassBranch.newInstance(MethodDescriptor.ofConstructor(solutionSubclass));
isSubclassBranch.invokeInterfaceMethod(
MethodDescriptor.ofMethod(Map.class, "put", Object.class, Object.class, Object.class),
createdCloneMap, thisObj, clone);
for (GizmoMemberDescriptor shallowlyClonedField : solutionSubclassDescriptor.getShallowClonedMemberDescriptors()) {
writeShallowCloneInstructions(solutionSubclassDescriptor, isSubclassBranch, shallowlyClonedField, thisObj,
clone, createdCloneMap, deepClonedClassesSortedSet);
}
for (Field deeplyClonedField : solutionSubclassDescriptor.getDeepClonedFields()) {
GizmoMemberDescriptor gizmoMemberDescriptor =
solutionSubclassDescriptor.getMemberDescriptorForField(deeplyClonedField);
ResultHandle fieldValue = gizmoMemberDescriptor.readMemberValue(isSubclassBranch, thisObj);
AssignableResultHandle cloneValue = isSubclassBranch.createVariable(deeplyClonedField.getType());
writeDeepCloneInstructions(isSubclassBranch, solutionSubclassDescriptor, deeplyClonedField,
gizmoMemberDescriptor, fieldValue, cloneValue, createdCloneMap, deepClonedClassesSortedSet);
if (!gizmoMemberDescriptor.writeMemberValue(isSubclassBranch, clone, cloneValue)) {
throw new IllegalStateException("The member (" + gizmoMemberDescriptor.getName() + ") of class (" +
gizmoMemberDescriptor.getDeclaringClassName() +
") does not have a setter.");
}
}
isSubclassBranch.returnValue(clone);
currentBranch = isSubclassBranchResult.falseBranch();
}
ResultHandle errorBuilder = currentBranch.newInstance(MethodDescriptor.ofConstructor(StringBuilder.class, String.class),
currentBranch.load("Failed to create clone: encountered ("));
final MethodDescriptor APPEND =
MethodDescriptor.ofMethod(StringBuilder.class, "append", StringBuilder.class, Object.class);
currentBranch.invokeVirtualMethod(APPEND, errorBuilder, thisObjClass);
currentBranch.invokeVirtualMethod(APPEND, errorBuilder, currentBranch.load(") which is not a known subclass of " +
"the solution class (" + solutionDescriptor.getSolutionClass() + "). The known subclasses are " +
solutionClassSet.stream().map(Class::getName).collect(Collectors.joining(", ", "[", "]")) + "." +
"\nMaybe use DomainAccessType.REFLECTION?"));
ResultHandle errorMsg = currentBranch
.invokeVirtualMethod(MethodDescriptor.ofMethod(Object.class, "toString", String.class), errorBuilder);
ResultHandle error = currentBranch
.newInstance(MethodDescriptor.ofConstructor(IllegalArgumentException.class, String.class), errorMsg);
currentBranch.throwException(error);
}
/**
* Writes the following code:
*
* <pre>
* // If getter a field
* clone.member = original.member
* // If getter a method (i.e. Quarkus)
* clone.setMember(original.getMember());
* </pre>
*
* @param methodCreator
* @param shallowlyClonedField
* @param thisObj
* @param clone
*/
private void writeShallowCloneInstructions(GizmoSolutionOrEntityDescriptor solutionInfo,
BytecodeCreator methodCreator, GizmoMemberDescriptor shallowlyClonedField,
ResultHandle thisObj, ResultHandle clone, ResultHandle createdCloneMap,
SortedSet<Class<?>> deepClonedClassesSortedSet) {
try {
boolean isArray = shallowlyClonedField.getTypeName().endsWith("[]");
Class<?> type = null;
if (shallowlyClonedField.getType() instanceof Class) {
type = (Class<?>) shallowlyClonedField.getType();
}
List<Class<?>> entitySubclasses = Collections.emptyList();
if (type == null && !isArray) {
type = Class.forName(shallowlyClonedField.getTypeName().replace('/', '.'), false,
Thread.currentThread().getContextClassLoader());
}
if (type != null && !isArray) {
entitySubclasses =
deepClonedClassesSortedSet.stream().filter(type::isAssignableFrom).collect(Collectors.toList());
}
ResultHandle fieldValue = shallowlyClonedField.readMemberValue(methodCreator, thisObj);
if (!entitySubclasses.isEmpty()) {
AssignableResultHandle cloneResultHolder = methodCreator.createVariable(type);
writeDeepCloneEntityOrFactInstructions(methodCreator, solutionInfo, type,
fieldValue, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet,
UnhandledCloneType.SHALLOW);
fieldValue = cloneResultHolder;
}
if (!shallowlyClonedField.writeMemberValue(methodCreator, clone, fieldValue)) {
throw new IllegalStateException("Field (" + shallowlyClonedField.getName() + ") of class (" +
shallowlyClonedField.getDeclaringClassName() +
") does not have a setter.");
}
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Error creating Gizmo Solution Cloner", e);
}
}
/**
* @see #writeDeepCloneInstructions(BytecodeCreator, GizmoSolutionOrEntityDescriptor, Class, Type, ResultHandle,
* AssignableResultHandle, ResultHandle, SortedSet)
*/
private void writeDeepCloneInstructions(BytecodeCreator bytecodeCreator,
GizmoSolutionOrEntityDescriptor solutionDescriptor, Field deeplyClonedField,
GizmoMemberDescriptor gizmoMemberDescriptor, ResultHandle toClone, AssignableResultHandle cloneResultHolder,
ResultHandle createdCloneMap, SortedSet<Class<?>> deepClonedClassesSortedSet) {
BranchResult isNull = bytecodeCreator.ifNull(toClone);
BytecodeCreator isNullBranch = isNull.trueBranch();
isNullBranch.assign(cloneResultHolder, isNullBranch.loadNull());
BytecodeCreator isNotNullBranch = isNull.falseBranch();
Class<?> deeplyClonedFieldClass = deeplyClonedField.getType();
Type type = gizmoMemberDescriptor.getType();
if (solutionDescriptor.getSolutionDescriptor().getSolutionClass().isAssignableFrom(deeplyClonedFieldClass)) {
writeDeepCloneSolutionInstructions(bytecodeCreator, solutionDescriptor, toClone, cloneResultHolder,
createdCloneMap);
} else if (Collection.class.isAssignableFrom(deeplyClonedFieldClass)) {
writeDeepCloneCollectionInstructions(isNotNullBranch, solutionDescriptor, deeplyClonedFieldClass, type,
toClone, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet);
} else if (Map.class.isAssignableFrom(deeplyClonedFieldClass)) {
writeDeepCloneMapInstructions(isNotNullBranch, solutionDescriptor, deeplyClonedFieldClass, type,
toClone, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet);
} else if (deeplyClonedFieldClass.isArray()) {
writeDeepCloneArrayInstructions(isNotNullBranch, solutionDescriptor, deeplyClonedFieldClass,
toClone, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet);
} else {
UnhandledCloneType unknownClassCloneType =
(DeepCloningUtils.isFieldDeepCloned(solutionDescriptor.solutionDescriptor,
deeplyClonedField, deeplyClonedField.getDeclaringClass()))
? UnhandledCloneType.DEEP
: UnhandledCloneType.SHALLOW;
writeDeepCloneEntityOrFactInstructions(isNotNullBranch, solutionDescriptor, deeplyClonedFieldClass,
toClone, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet, unknownClassCloneType);
}
}
/**
* Writes the following code:
*
* <pre>
* // For a Collection
* Collection original = field;
* Collection clone = new ActualCollectionType();
* Iterator iterator = original.iterator();
* while (iterator.hasNext()) {
* Object nextClone = (result from recursion on iterator.next());
* clone.add(nextClone);
* }
*
* // For a Map
* Map original = field;
* Map clone = new ActualMapType();
* Iterator iterator = original.entrySet().iterator();
* while (iterator.hasNext()) {
* Entry next = iterator.next();
* nextClone = (result from recursion on next.getValue());
* clone.put(next.getKey(), nextClone);
* }
*
* // For an array
* Object[] original = field;
* Object[] clone = new Object[original.length];
*
* for (int i = 0; i < original.length; i++) {
* clone[i] = (result from recursion on original[i]);
* }
*
* // For an entity
* if (original instanceof SubclassOfEntity1) {
* SubclassOfEntity1 original = field;
* SubclassOfEntity1 clone = new SubclassOfEntity1();
*
* // shallowly clone fields using writeShallowCloneInstructions()
* // for any deeply cloned field, do recursion on it
* } else if (original instanceof SubclassOfEntity2) {
* // ...
* }
* </pre>
*
* @param bytecodeCreator
* @param solutionDescriptor
* @param deeplyClonedFieldClass
* @param type
* @param toClone
* @param cloneResultHolder
*/
private void writeDeepCloneInstructions(BytecodeCreator bytecodeCreator,
GizmoSolutionOrEntityDescriptor solutionDescriptor,
Class<?> deeplyClonedFieldClass, java.lang.reflect.Type type, ResultHandle toClone,
AssignableResultHandle cloneResultHolder, ResultHandle createdCloneMap,
SortedSet<Class<?>> deepClonedClassesSortedSet) {
BranchResult isNull = bytecodeCreator.ifNull(toClone);
BytecodeCreator isNullBranch = isNull.trueBranch();
isNullBranch.assign(cloneResultHolder, isNullBranch.loadNull());
BytecodeCreator isNotNullBranch = isNull.falseBranch();
if (solutionDescriptor.getSolutionDescriptor().getSolutionClass().isAssignableFrom(deeplyClonedFieldClass)) {
writeDeepCloneSolutionInstructions(bytecodeCreator, solutionDescriptor, toClone, cloneResultHolder,
createdCloneMap);
} else if (Collection.class.isAssignableFrom(deeplyClonedFieldClass)) {
// Clone collection
writeDeepCloneCollectionInstructions(isNotNullBranch, solutionDescriptor, deeplyClonedFieldClass, type,
toClone, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet);
} else if (Map.class.isAssignableFrom(deeplyClonedFieldClass)) {
// Clone map
writeDeepCloneMapInstructions(isNotNullBranch, solutionDescriptor, deeplyClonedFieldClass, type,
toClone, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet);
} else if (deeplyClonedFieldClass.isArray()) {
// Clone array
writeDeepCloneArrayInstructions(isNotNullBranch, solutionDescriptor, deeplyClonedFieldClass,
toClone, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet);
} else {
// Clone entity
UnhandledCloneType unknownClassCloneType =
(DeepCloningUtils.isClassDeepCloned(solutionDescriptor.solutionDescriptor, deeplyClonedFieldClass))
? UnhandledCloneType.DEEP
: UnhandledCloneType.SHALLOW;
writeDeepCloneEntityOrFactInstructions(isNotNullBranch, solutionDescriptor, deeplyClonedFieldClass,
toClone, cloneResultHolder, createdCloneMap, deepClonedClassesSortedSet, unknownClassCloneType);
}
}
private void writeDeepCloneSolutionInstructions(BytecodeCreator bytecodeCreator,
GizmoSolutionOrEntityDescriptor solutionDescriptor, ResultHandle toClone, AssignableResultHandle cloneResultHolder,
ResultHandle createdCloneMap) {
BranchResult isNull = bytecodeCreator.ifNull(toClone);
BytecodeCreator isNullBranch = isNull.trueBranch();
isNullBranch.assign(cloneResultHolder, isNullBranch.loadNull());
BytecodeCreator isNotNullBranch = isNull.falseBranch();
ResultHandle clone = isNotNullBranch.invokeStaticMethod(
MethodDescriptor.ofMethod(
GizmoSolutionClonerFactory.getGeneratedClassName(solutionDescriptor.getSolutionDescriptor()),
"cloneSolutionRun", solutionDescriptor.getSolutionDescriptor().getSolutionClass(),
solutionDescriptor.getSolutionDescriptor().getSolutionClass(), Map.class),
toClone,
createdCloneMap);
isNotNullBranch.assign(cloneResultHolder, clone);
}
/**
* Writes the following code:
*
* <pre>
* // For a Collection
* Collection clone = new ActualCollectionType();
* Iterator iterator = toClone.iterator();
* while (iterator.hasNext()) {
* Object toCloneElement = iterator.next();
* Object nextClone = (result from recursion on toCloneElement);
* clone.add(nextClone);
* }
* cloneResultHolder = clone;
* </pre>
**/
private void writeDeepCloneCollectionInstructions(BytecodeCreator bytecodeCreator,
GizmoSolutionOrEntityDescriptor solutionDescriptor,
Class<?> deeplyClonedFieldClass, java.lang.reflect.Type type, ResultHandle toClone,
AssignableResultHandle cloneResultHolder, ResultHandle createdCloneMap,
SortedSet<Class<?>> deepClonedClassesSortedSet) {
// Clone collection
AssignableResultHandle cloneCollection = bytecodeCreator.createVariable(deeplyClonedFieldClass);
ResultHandle size = bytecodeCreator
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Collection.class, "size", int.class), toClone);
if (List.class.isAssignableFrom(deeplyClonedFieldClass)) {
bytecodeCreator.assign(cloneCollection,
bytecodeCreator.newInstance(MethodDescriptor.ofConstructor(ArrayList.class, int.class), size));
} else if (Set.class.isAssignableFrom(deeplyClonedFieldClass)) {
ResultHandle isSortedSet = bytecodeCreator.instanceOf(toClone, SortedSet.class);
BranchResult isSortedSetBranchResult = bytecodeCreator.ifTrue(isSortedSet);
BytecodeCreator isSortedSetBranch = isSortedSetBranchResult.trueBranch();
ResultHandle setComparator = isSortedSetBranch
.invokeInterfaceMethod(MethodDescriptor.ofMethod(SortedSet.class,
"comparator", Comparator.class), toClone);
isSortedSetBranch.assign(cloneCollection,
isSortedSetBranch.newInstance(MethodDescriptor.ofConstructor(TreeSet.class, Comparator.class),
setComparator));
BytecodeCreator isNotSortedSetBranch = isSortedSetBranchResult.falseBranch();
isNotSortedSetBranch.assign(cloneCollection,
isNotSortedSetBranch.newInstance(MethodDescriptor.ofConstructor(LinkedHashSet.class, int.class), size));
} else {
// field is probably of type collection
ResultHandle isSet = bytecodeCreator.instanceOf(toClone, Set.class);
BranchResult isSetBranchResult = bytecodeCreator.ifTrue(isSet);
BytecodeCreator isSetBranch = isSetBranchResult.trueBranch();
ResultHandle isSortedSet = isSetBranch.instanceOf(toClone, SortedSet.class);
BranchResult isSortedSetBranchResult = isSetBranch.ifTrue(isSortedSet);
BytecodeCreator isSortedSetBranch = isSortedSetBranchResult.trueBranch();
ResultHandle setComparator = isSortedSetBranch
.invokeInterfaceMethod(MethodDescriptor.ofMethod(SortedSet.class,
"comparator", Comparator.class), toClone);
isSortedSetBranch.assign(cloneCollection,
isSortedSetBranch.newInstance(MethodDescriptor.ofConstructor(TreeSet.class, Comparator.class),
setComparator));
BytecodeCreator isNotSortedSetBranch = isSortedSetBranchResult.falseBranch();
isNotSortedSetBranch.assign(cloneCollection,
isNotSortedSetBranch.newInstance(MethodDescriptor.ofConstructor(LinkedHashSet.class, int.class), size));
// Default to ArrayList
BytecodeCreator isNotSetBranch = isSetBranchResult.falseBranch();
isNotSetBranch.assign(cloneCollection,
isNotSetBranch.newInstance(MethodDescriptor.ofConstructor(ArrayList.class, int.class), size));
}
ResultHandle iterator = bytecodeCreator
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Iterable.class, "iterator", Iterator.class), toClone);
BytecodeCreator whileLoopBlock = bytecodeCreator.whileLoop(conditionBytecode -> {
ResultHandle hasNext = conditionBytecode
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Iterator.class, "hasNext", boolean.class), iterator);
return conditionBytecode.ifTrue(hasNext);
}).block();
Class<?> elementClass;
java.lang.reflect.Type elementClassType;
if (type instanceof ParameterizedType parameterizedType) {
// Assume Collection follow Collection<T> convention of first type argument = element class
elementClassType = parameterizedType.getActualTypeArguments()[0];
if (elementClassType instanceof Class class1) {
elementClass = class1;
} else if (elementClassType instanceof ParameterizedType parameterizedElementClassType) {
elementClass = (Class<?>) parameterizedElementClassType.getRawType();
} else {
throw new IllegalStateException("Unhandled type " + elementClassType + ".");
}
} else {
throw new IllegalStateException("Cannot infer element type for Collection type (" + type + ").");
}
// Odd case of member get and set being on different classes; will work as we only
// use get on the original and set on the clone.
ResultHandle next =
whileLoopBlock.invokeInterfaceMethod(MethodDescriptor.ofMethod(Iterator.class, "next", Object.class), iterator);
final AssignableResultHandle clonedElement = whileLoopBlock.createVariable(elementClass);
writeDeepCloneInstructions(whileLoopBlock, solutionDescriptor,
elementClass, elementClassType, next, clonedElement, createdCloneMap, deepClonedClassesSortedSet);
whileLoopBlock.invokeInterfaceMethod(MethodDescriptor.ofMethod(Collection.class, "add", boolean.class, Object.class),
cloneCollection,
clonedElement);
bytecodeCreator.assign(cloneResultHolder, cloneCollection);
}
/**
* Writes the following code:
*
* <pre>
* // For a Map
* Map clone = new ActualMapType();
* Iterator iterator = toClone.entrySet().iterator();
* while (iterator.hasNext()) {
* Entry next = iterator.next();
* Object toCloneValue = next.getValue();
* nextClone = (result from recursion on toCloneValue);
* clone.put(next.getKey(), nextClone);
* }
* cloneResultHolder = clone;
* </pre>
**/
private void writeDeepCloneMapInstructions(BytecodeCreator bytecodeCreator,
GizmoSolutionOrEntityDescriptor solutionDescriptor,
Class<?> deeplyClonedFieldClass, java.lang.reflect.Type type, ResultHandle toClone,
AssignableResultHandle cloneResultHolder, ResultHandle createdCloneMap,
SortedSet<Class<?>> deepClonedClassesSortedSet) {
Class<?> holderClass = deeplyClonedFieldClass;
try {
holderClass.getConstructor();
} catch (NoSuchMethodException e) {
if (LinkedHashMap.class.isAssignableFrom(holderClass)) {
holderClass = LinkedHashMap.class;
} else if (ConcurrentHashMap.class.isAssignableFrom(holderClass)) {
holderClass = ConcurrentHashMap.class;
} else {
// Default to LinkedHashMap
holderClass = LinkedHashMap.class;
}
}
ResultHandle cloneMap;
ResultHandle size =
bytecodeCreator.invokeInterfaceMethod(MethodDescriptor.ofMethod(Map.class, "size", int.class), toClone);
ResultHandle entrySet = bytecodeCreator
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Map.class, "entrySet", Set.class), toClone);
ResultHandle iterator = bytecodeCreator
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Iterable.class, "iterator", Iterator.class), entrySet);
try {
holderClass.getConstructor(int.class);
cloneMap = bytecodeCreator.newInstance(MethodDescriptor.ofConstructor(holderClass, int.class), size);
} catch (NoSuchMethodException e) {
cloneMap = bytecodeCreator.newInstance(MethodDescriptor.ofConstructor(holderClass));
}
BytecodeCreator whileLoopBlock = bytecodeCreator.whileLoop(conditionBytecode -> {
ResultHandle hasNext = conditionBytecode
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Iterator.class, "hasNext", boolean.class), iterator);
return conditionBytecode.ifTrue(hasNext);
}).block();
Class<?> keyClass;
Class<?> elementClass;
java.lang.reflect.Type keyType;
java.lang.reflect.Type elementClassType;
if (type instanceof ParameterizedType parameterizedType) {
// Assume Map follow Map<K,V> convention of second type argument = value class
keyType = parameterizedType.getActualTypeArguments()[0];
elementClassType = parameterizedType.getActualTypeArguments()[1];
if (elementClassType instanceof Class class1) {
elementClass = class1;
} else if (elementClassType instanceof ParameterizedType parameterizedElementClassType) {
elementClass = (Class<?>) parameterizedElementClassType.getRawType();
} else {
throw new IllegalStateException("Unhandled type " + elementClassType + ".");
}
if (keyType instanceof Class class1) {
keyClass = class1;
} else if (keyType instanceof ParameterizedType parameterizedElementClassType) {
keyClass = (Class<?>) parameterizedElementClassType.getRawType();
} else {
throw new IllegalStateException("Unhandled type " + keyType + ".");
}
} else {
throw new IllegalStateException("Cannot infer element type for Map type (" + type + ").");
}
List<Class<?>> entitySubclasses = deepClonedClassesSortedSet.stream()
.filter(keyClass::isAssignableFrom).collect(Collectors.toList());
ResultHandle entry = whileLoopBlock
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Iterator.class, "next", Object.class), iterator);
ResultHandle toCloneValue = whileLoopBlock
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Map.Entry.class, "getValue", Object.class), entry);
final AssignableResultHandle clonedElement = whileLoopBlock.createVariable(elementClass);
writeDeepCloneInstructions(whileLoopBlock, solutionDescriptor,
elementClass, elementClassType, toCloneValue, clonedElement, createdCloneMap, deepClonedClassesSortedSet);
ResultHandle key = whileLoopBlock
.invokeInterfaceMethod(MethodDescriptor.ofMethod(Map.Entry.class, "getKey", Object.class), entry);
if (!entitySubclasses.isEmpty()) {
AssignableResultHandle keyCloneResultHolder = whileLoopBlock.createVariable(keyClass);
writeDeepCloneEntityOrFactInstructions(whileLoopBlock, solutionDescriptor, keyClass,
key, keyCloneResultHolder, createdCloneMap, deepClonedClassesSortedSet, UnhandledCloneType.DEEP);
whileLoopBlock.invokeInterfaceMethod(
PUT_METHOD,
cloneMap, keyCloneResultHolder, clonedElement);
} else {
whileLoopBlock.invokeInterfaceMethod(
PUT_METHOD,
cloneMap, key, clonedElement);
}
bytecodeCreator.assign(cloneResultHolder, cloneMap);
}
/**
* Writes the following code:
*
* <pre>
* // For an array
* Object[] clone = new Object[toClone.length];
*
* for (int i = 0; i < original.length; i++) {
* clone[i] = (result from recursion on toClone[i]);
* }
* cloneResultHolder = clone;
* </pre>
**/
private void writeDeepCloneArrayInstructions(BytecodeCreator bytecodeCreator,
GizmoSolutionOrEntityDescriptor solutionDescriptor,
Class<?> deeplyClonedFieldClass, ResultHandle toClone, AssignableResultHandle cloneResultHolder,
ResultHandle createdCloneMap, SortedSet<Class<?>> deepClonedClassesSortedSet) {
// Clone array
Class<?> arrayComponent = deeplyClonedFieldClass.getComponentType();
ResultHandle arrayLength = bytecodeCreator.arrayLength(toClone);
ResultHandle arrayClone = bytecodeCreator.newArray(arrayComponent, arrayLength);
AssignableResultHandle iterations = bytecodeCreator.createVariable(int.class);
bytecodeCreator.assign(iterations, bytecodeCreator.load(0));
BytecodeCreator whileLoopBlock = bytecodeCreator
.whileLoop(conditionBytecode -> conditionBytecode.ifIntegerLessThan(iterations, arrayLength))
.block();
ResultHandle toCloneElement = whileLoopBlock.readArrayValue(toClone, iterations);
AssignableResultHandle clonedElement = whileLoopBlock.createVariable(arrayComponent);
writeDeepCloneInstructions(whileLoopBlock, solutionDescriptor, arrayComponent,
arrayComponent, toCloneElement, clonedElement, createdCloneMap, deepClonedClassesSortedSet);
whileLoopBlock.writeArrayValue(arrayClone, iterations, clonedElement);
whileLoopBlock.assign(iterations, whileLoopBlock.increment(iterations));
bytecodeCreator.assign(cloneResultHolder, arrayClone);
}
/**
* Writes the following code:
*
* <pre>
* // For an entity
* if (toClone instanceof SubclassOfEntity1) {
* SubclassOfEntity1 clone = new SubclassOfEntity1();
*
* // shallowly clone fields using writeShallowCloneInstructions()
* // for any deeply cloned field, do recursion on it
* cloneResultHolder = clone;
* } else if (toClone instanceof SubclassOfEntity2) {
* // ...
* }
* // ...
* else if (toClone instanceof SubclassOfEntityN) {
* // ...
* } else {
* // shallow or deep clone based on whether deep cloning is forced
* }
* </pre>
**/
private void writeDeepCloneEntityOrFactInstructions(BytecodeCreator bytecodeCreator,
GizmoSolutionOrEntityDescriptor solutionDescriptor, Class<?> deeplyClonedFieldClass, ResultHandle toClone,
AssignableResultHandle cloneResultHolder, ResultHandle createdCloneMap,
SortedSet<Class<?>> deepClonedClassesSortedSet, UnhandledCloneType unhandledCloneType) {
List<Class<?>> deepClonedSubclasses = deepClonedClassesSortedSet.stream()
.filter(deeplyClonedFieldClass::isAssignableFrom)
.filter(type -> DeepCloningUtils.isClassDeepCloned(solutionDescriptor.getSolutionDescriptor(), type))
.toList();
BytecodeCreator currentBranch = bytecodeCreator;
// If the field holds an instance of one of the field's declared type's subtypes, clone the subtype instead.
for (Class<?> deepClonedSubclass : deepClonedSubclasses) {
ResultHandle isInstance = currentBranch.instanceOf(toClone, deepClonedSubclass);
BranchResult isInstanceBranchResult = currentBranch.ifTrue(isInstance);
BytecodeCreator isInstanceBranch = isInstanceBranchResult.trueBranch();
ResultHandle cloneObj = isInstanceBranch.invokeStaticMethod(
MethodDescriptor.ofMethod(
GizmoSolutionClonerFactory.getGeneratedClassName(solutionDescriptor.getSolutionDescriptor()),
getEntityHelperMethodName(deepClonedSubclass), deepClonedSubclass, deepClonedSubclass, Map.class),
toClone, createdCloneMap);
isInstanceBranch.assign(cloneResultHolder, cloneObj);
currentBranch = isInstanceBranchResult.falseBranch();
}
// We are certain that the instance is of the same type as the declared field type.
// (Or is an undeclared subclass of the planning entity)
switch (unhandledCloneType) {
case SHALLOW -> {
currentBranch.assign(cloneResultHolder, toClone);
}
case DEEP -> {
ResultHandle cloneObj = currentBranch.invokeStaticMethod(
MethodDescriptor.ofMethod(
GizmoSolutionClonerFactory.getGeneratedClassName(solutionDescriptor.getSolutionDescriptor()),
getEntityHelperMethodName(deeplyClonedFieldClass), deeplyClonedFieldClass,
deeplyClonedFieldClass, Map.class),
toClone, createdCloneMap);
currentBranch.assign(cloneResultHolder, cloneObj);
}
}
}
protected String getEntityHelperMethodName(Class<?> entityClass) {
return "$clone" + entityClass.getName().replace('.', '_');
}
/**
* Writes the following code:
* <p>
* In Quarkus: (nothing)
* <p>
* Outside Quarkus:
*
* <pre>
* if (toClone.getClass() != entityClass) {
* Cloner.fallbackCloner.gizmoFallbackDeepClone(toClone, cloneMap);
* } else {
* ...
* }
* </pre>
*
* @return The else branch {@link BytecodeCreator} outside of Quarkus, the original bytecodeCreator otherwise.
*/
protected BytecodeCreator createUnknownClassHandler(BytecodeCreator bytecodeCreator,
SolutionDescriptor<?> solutionDescriptor,
Class<?> entityClass,
ResultHandle toClone,
ResultHandle cloneMap) {
ResultHandle actualClass =
bytecodeCreator.invokeVirtualMethod(MethodDescriptor.ofMethod(Object.class, "getClass", Class.class),
toClone);
BranchResult branchResult = bytecodeCreator.ifReferencesNotEqual(actualClass,
bytecodeCreator.loadClass(entityClass));
BytecodeCreator currentBranch = branchResult.trueBranch();
ResultHandle fallbackCloner =
currentBranch.readStaticField(FieldDescriptor.of(
GizmoSolutionClonerFactory.getGeneratedClassName(solutionDescriptor),
FALLBACK_CLONER, FieldAccessingSolutionCloner.class));
ResultHandle cloneObj =
currentBranch.invokeVirtualMethod(MethodDescriptor.ofMethod(FieldAccessingSolutionCloner.class,
"gizmoFallbackDeepClone", Object.class, Object.class, Map.class),
fallbackCloner, toClone, cloneMap);
currentBranch.returnValue(cloneObj);
return branchResult.falseBranch();
}
// To prevent stack overflow on chained models
private void createDeepCloneHelperMethod(ClassCreator classCreator,
Class<?> entityClass,
SolutionDescriptor<?> solutionDescriptor,
Map<Class<?>, GizmoSolutionOrEntityDescriptor> memoizedSolutionOrEntityDescriptorMap,
SortedSet<Class<?>> deepClonedClassesSortedSet) {
MethodCreator methodCreator =
classCreator.getMethodCreator(getEntityHelperMethodName(entityClass), entityClass, entityClass, Map.class);
methodCreator.setModifiers(Modifier.STATIC | Modifier.PRIVATE);
GizmoSolutionOrEntityDescriptor entityDescriptor = memoizedSolutionOrEntityDescriptorMap.computeIfAbsent(entityClass,
(key) -> new GizmoSolutionOrEntityDescriptor(solutionDescriptor, entityClass));
ResultHandle toClone = methodCreator.getMethodParam(0);
ResultHandle cloneMap = methodCreator.getMethodParam(1);
ResultHandle maybeClone = methodCreator.invokeInterfaceMethod(
GET_METHOD, cloneMap, toClone);
BranchResult hasCloneBranchResult = methodCreator.ifNotNull(maybeClone);
BytecodeCreator hasCloneBranch = hasCloneBranchResult.trueBranch();
hasCloneBranch.returnValue(maybeClone);
BytecodeCreator noCloneBranch = hasCloneBranchResult.falseBranch();
noCloneBranch = createUnknownClassHandler(noCloneBranch,
solutionDescriptor,
entityClass,
toClone,
cloneMap);
ResultHandle cloneObj = noCloneBranch.newInstance(MethodDescriptor.ofConstructor(entityClass));
noCloneBranch.invokeInterfaceMethod(
MethodDescriptor.ofMethod(Map.class, "put", Object.class, Object.class, Object.class),
cloneMap, toClone, cloneObj);
for (GizmoMemberDescriptor shallowlyClonedField : entityDescriptor.getShallowClonedMemberDescriptors()) {
writeShallowCloneInstructions(entityDescriptor, noCloneBranch, shallowlyClonedField, toClone, cloneObj, cloneMap,
deepClonedClassesSortedSet);
}
for (Field deeplyClonedField : entityDescriptor.getDeepClonedFields()) {
GizmoMemberDescriptor gizmoMemberDescriptor =
entityDescriptor.getMemberDescriptorForField(deeplyClonedField);
ResultHandle subfieldValue = gizmoMemberDescriptor.readMemberValue(noCloneBranch, toClone);
AssignableResultHandle cloneValue = noCloneBranch.createVariable(deeplyClonedField.getType());
writeDeepCloneInstructions(noCloneBranch, entityDescriptor, deeplyClonedField, gizmoMemberDescriptor, subfieldValue,
cloneValue, cloneMap, deepClonedClassesSortedSet);
if (!gizmoMemberDescriptor.writeMemberValue(noCloneBranch, cloneObj, cloneValue)) {
throw new IllegalStateException("The member (" + gizmoMemberDescriptor.getName() + ") of class (" +
gizmoMemberDescriptor.getDeclaringClassName() + ") does not have a setter.");
}
}
noCloneBranch.returnValue(cloneObj);
}
protected void createAbstractDeepCloneHelperMethod(ClassCreator classCreator,
Class<?> entityClass,
SolutionDescriptor<?> solutionDescriptor,
Map<Class<?>, GizmoSolutionOrEntityDescriptor> memoizedSolutionOrEntityDescriptorMap,
SortedSet<Class<?>> deepClonedClassesSortedSet) {
MethodCreator methodCreator =
classCreator.getMethodCreator(getEntityHelperMethodName(entityClass), entityClass, entityClass, Map.class);
methodCreator.setModifiers(Modifier.STATIC | Modifier.PRIVATE);
ResultHandle toClone = methodCreator.getMethodParam(0);
ResultHandle cloneMap = methodCreator.getMethodParam(1);
ResultHandle maybeClone = methodCreator.invokeInterfaceMethod(
GET_METHOD, cloneMap, toClone);
BranchResult hasCloneBranchResult = methodCreator.ifNotNull(maybeClone);
BytecodeCreator hasCloneBranch = hasCloneBranchResult.trueBranch();
hasCloneBranch.returnValue(maybeClone);
BytecodeCreator noCloneBranch = hasCloneBranchResult.falseBranch();
ResultHandle fallbackCloner =
noCloneBranch.readStaticField(FieldDescriptor.of(
GizmoSolutionClonerFactory.getGeneratedClassName(solutionDescriptor),
FALLBACK_CLONER, FieldAccessingSolutionCloner.class));
ResultHandle cloneObj =
noCloneBranch.invokeVirtualMethod(MethodDescriptor.ofMethod(FieldAccessingSolutionCloner.class,
"gizmoFallbackDeepClone", Object.class, Object.class, Map.class),
fallbackCloner, toClone, cloneMap);
noCloneBranch.returnValue(cloneObj);
}
private enum UnhandledCloneType {
SHALLOW,
DEEP
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution/descriptor/ProblemScaleTracker.java | package ai.timefold.solver.core.impl.domain.solution.descriptor;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Set;
import ai.timefold.solver.core.impl.util.MathUtils;
public class ProblemScaleTracker {
private final long logBase;
private final Set<Object> visitedAnchorSet = Collections.newSetFromMap(new IdentityHashMap<>());
private long basicProblemScaleLog = 0L;
private int listPinnedValueCount = 0;
private int listTotalEntityCount = 0;
private int listMovableEntityCount = 0;
private int listTotalValueCount = 0;
public ProblemScaleTracker(long logBase) {
this.logBase = logBase;
}
// Simple getters
public long getBasicProblemScaleLog() {
return basicProblemScaleLog;
}
public int getListPinnedValueCount() {
return listPinnedValueCount;
}
public int getListTotalEntityCount() {
return listTotalEntityCount;
}
public int getListMovableEntityCount() {
return listMovableEntityCount;
}
public int getListTotalValueCount() {
return listTotalValueCount;
}
public void setListTotalValueCount(int listTotalValueCount) {
this.listTotalValueCount = listTotalValueCount;
}
// Complex methods
public boolean isAnchorVisited(Object anchor) {
if (visitedAnchorSet.contains(anchor)) {
return true;
}
visitedAnchorSet.add(anchor);
return false;
}
public void addListValueCount(int count) {
listTotalValueCount += count;
}
public void addPinnedListValueCount(int count) {
listPinnedValueCount += count;
}
public void incrementListEntityCount(boolean isMovable) {
listTotalEntityCount++;
if (isMovable) {
listMovableEntityCount++;
}
}
public void addBasicProblemScale(long count) {
basicProblemScaleLog += MathUtils.getScaledApproximateLog(MathUtils.LOG_PRECISION, logBase, count);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/solution/descriptor/SolutionDescriptor.java | package ai.timefold.solver.core.impl.domain.solution.descriptor;
import static ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory.MemberAccessorType.FIELD_OR_GETTER_METHOD;
import static ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory.MemberAccessorType.FIELD_OR_READ_METHOD;
import static java.util.stream.Stream.concat;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import ai.timefold.solver.core.api.domain.autodiscover.AutoDiscoverMemberType;
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.domain.constraintweight.ConstraintConfiguration;
import ai.timefold.solver.core.api.domain.constraintweight.ConstraintConfigurationProvider;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty;
import ai.timefold.solver.core.api.domain.solution.PlanningEntityProperty;
import ai.timefold.solver.core.api.domain.solution.PlanningScore;
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.solution.ProblemFactProperty;
import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.api.score.IBendableScore;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.score.constraint.ConstraintRef;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.api.solver.ProblemSizeStatistics;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.common.ReflectionHelper;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory;
import ai.timefold.solver.core.impl.domain.common.accessor.ReflectionFieldMemberAccessor;
import ai.timefold.solver.core.impl.domain.constraintweight.descriptor.ConstraintConfigurationDescriptor;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.lookup.ClassAndPlanningIdComparator;
import ai.timefold.solver.core.impl.domain.lookup.LookUpStrategyResolver;
import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy;
import ai.timefold.solver.core.impl.domain.score.descriptor.ScoreDescriptor;
import ai.timefold.solver.core.impl.domain.solution.cloner.FieldAccessingSolutionCloner;
import ai.timefold.solver.core.impl.domain.solution.cloner.gizmo.GizmoSolutionCloner;
import ai.timefold.solver.core.impl.domain.solution.cloner.gizmo.GizmoSolutionClonerFactory;
import ai.timefold.solver.core.impl.domain.valuerange.descriptor.EntityIndependentValueRangeDescriptor;
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.ShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.score.definition.AbstractBendableScoreDefinition;
import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
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 ai.timefold.solver.core.impl.util.MutablePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class SolutionDescriptor<Solution_> {
private static final Logger LOGGER = LoggerFactory.getLogger(SolutionDescriptor.class);
private static final EntityDescriptor<?> NULL_ENTITY_DESCRIPTOR = new EntityDescriptor<>(-1, null, PlanningEntity.class);
public static <Solution_> SolutionDescriptor<Solution_> buildSolutionDescriptor(Class<Solution_> solutionClass,
Class<?>... entityClasses) {
return buildSolutionDescriptor(solutionClass, Arrays.asList(entityClasses));
}
public static <Solution_> SolutionDescriptor<Solution_> buildSolutionDescriptor(Class<Solution_> solutionClass,
List<Class<?>> entityClassList) {
return buildSolutionDescriptor(DomainAccessType.REFLECTION, solutionClass, null, null, entityClassList);
}
public static <Solution_> SolutionDescriptor<Solution_> buildSolutionDescriptor(DomainAccessType domainAccessType,
Class<Solution_> solutionClass, Map<String, MemberAccessor> memberAccessorMap,
Map<String, SolutionCloner> solutionClonerMap, List<Class<?>> entityClassList) {
assertMutable(solutionClass, "solutionClass");
solutionClonerMap = Objects.requireNonNullElse(solutionClonerMap, Collections.emptyMap());
var solutionDescriptor = new SolutionDescriptor<>(solutionClass, memberAccessorMap);
var descriptorPolicy = new DescriptorPolicy();
descriptorPolicy.setDomainAccessType(domainAccessType);
descriptorPolicy.setGeneratedSolutionClonerMap(solutionClonerMap);
descriptorPolicy.setMemberAccessorFactory(solutionDescriptor.getMemberAccessorFactory());
solutionDescriptor.processAnnotations(descriptorPolicy, entityClassList);
int ordinal = 0;
for (var entityClass : sortEntityClassList(entityClassList)) {
var entityDescriptor = new EntityDescriptor<>(ordinal++, solutionDescriptor, entityClass);
solutionDescriptor.addEntityDescriptor(entityDescriptor);
entityDescriptor.processAnnotations(descriptorPolicy);
}
solutionDescriptor.afterAnnotationsProcessed(descriptorPolicy);
return solutionDescriptor;
}
public static void assertMutable(Class<?> clz, String classType) {
if (clz.isRecord()) {
throw new IllegalArgumentException("""
The %s (%s) cannot be a record as it needs to be mutable.
Use a regular class instead."""
.formatted(classType, clz.getCanonicalName()));
} else if (clz.isEnum()) {
throw new IllegalArgumentException("""
The %s (%s) cannot be an enum as it needs to be mutable.
Use a regular class instead."""
.formatted(classType, clz.getCanonicalName()));
}
}
private static List<Class<?>> sortEntityClassList(List<Class<?>> entityClassList) {
List<Class<?>> sortedEntityClassList = new ArrayList<>(entityClassList.size());
for (Class<?> entityClass : entityClassList) {
boolean added = false;
for (int i = 0; i < sortedEntityClassList.size(); i++) {
Class<?> sortedEntityClass = sortedEntityClassList.get(i);
if (entityClass.isAssignableFrom(sortedEntityClass)) {
sortedEntityClassList.add(i, entityClass);
added = true;
break;
}
}
if (!added) {
sortedEntityClassList.add(entityClass);
}
}
return sortedEntityClassList;
}
// ************************************************************************
// Non-static members
// ************************************************************************
private final Class<Solution_> solutionClass;
private final MemberAccessorFactory memberAccessorFactory;
private DomainAccessType domainAccessType;
private AutoDiscoverMemberType autoDiscoverMemberType;
private LookUpStrategyResolver lookUpStrategyResolver;
private MemberAccessor constraintConfigurationMemberAccessor;
private final Map<String, MemberAccessor> problemFactMemberAccessorMap = new LinkedHashMap<>();
private final Map<String, MemberAccessor> problemFactCollectionMemberAccessorMap = new LinkedHashMap<>();
private final Map<String, MemberAccessor> entityMemberAccessorMap = new LinkedHashMap<>();
private final Map<String, MemberAccessor> entityCollectionMemberAccessorMap = new LinkedHashMap<>();
private Set<Class<?>> problemFactOrEntityClassSet;
private List<ListVariableDescriptor<Solution_>> listVariableDescriptorList;
private ScoreDescriptor scoreDescriptor;
private ConstraintConfigurationDescriptor<Solution_> constraintConfigurationDescriptor;
private final Map<Class<?>, EntityDescriptor<Solution_>> entityDescriptorMap = new LinkedHashMap<>();
private final List<Class<?>> reversedEntityClassList = new ArrayList<>();
private final ConcurrentMap<Class<?>, EntityDescriptor<Solution_>> lowestEntityDescriptorMap = new ConcurrentHashMap<>();
private final ConcurrentMap<Class<?>, MemberAccessor> planningIdMemberAccessorMap = new ConcurrentHashMap<>();
private SolutionCloner<Solution_> solutionCloner;
private boolean assertModelForCloning = false;
private Comparator<Object> classAndPlanningIdComparator;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
private SolutionDescriptor(Class<Solution_> solutionClass, Map<String, MemberAccessor> memberAccessorMap) {
this.solutionClass = solutionClass;
if (solutionClass.getPackage() == null) {
LOGGER.warn("The solutionClass ({}) should be in a proper java package.", solutionClass);
}
this.memberAccessorFactory = new MemberAccessorFactory(memberAccessorMap);
}
public void addEntityDescriptor(EntityDescriptor<Solution_> entityDescriptor) {
Class<?> entityClass = entityDescriptor.getEntityClass();
for (Class<?> otherEntityClass : entityDescriptorMap.keySet()) {
if (entityClass.isAssignableFrom(otherEntityClass)) {
throw new IllegalArgumentException("An earlier entityClass (" + otherEntityClass
+ ") should not be a subclass of a later entityClass (" + entityClass
+ "). Switch their declaration so superclasses are defined earlier.");
}
}
entityDescriptorMap.put(entityClass, entityDescriptor);
reversedEntityClassList.add(0, entityClass);
lowestEntityDescriptorMap.put(entityClass, entityDescriptor);
}
public void processAnnotations(DescriptorPolicy descriptorPolicy,
List<Class<?>> entityClassList) {
domainAccessType = descriptorPolicy.getDomainAccessType();
classAndPlanningIdComparator = new ClassAndPlanningIdComparator(memberAccessorFactory, domainAccessType, false);
processSolutionAnnotations(descriptorPolicy);
ArrayList<Method> potentiallyOverwritingMethodList = new ArrayList<>();
// Iterate inherited members too (unlike for EntityDescriptor where each one is declared)
// to make sure each one is registered
for (Class<?> lineageClass : ConfigUtils.getAllAnnotatedLineageClasses(solutionClass, PlanningSolution.class)) {
List<Member> memberList = ConfigUtils.getDeclaredMembers(lineageClass);
for (Member member : memberList) {
if (member instanceof Method method && potentiallyOverwritingMethodList.stream().anyMatch(
m -> member.getName().equals(m.getName()) // Shortcut to discard negatives faster
&& ReflectionHelper.isMethodOverwritten(method, m.getDeclaringClass()))) {
// Ignore member because it is an overwritten method
continue;
}
processValueRangeProviderAnnotation(descriptorPolicy, member);
processFactEntityOrScoreAnnotation(descriptorPolicy, member, entityClassList);
}
potentiallyOverwritingMethodList.ensureCapacity(potentiallyOverwritingMethodList.size() + memberList.size());
memberList.stream().filter(member -> member instanceof Method)
.forEach(member -> potentiallyOverwritingMethodList.add((Method) member));
}
if (entityCollectionMemberAccessorMap.isEmpty() && entityMemberAccessorMap.isEmpty()) {
throw new IllegalStateException("The solutionClass (" + solutionClass
+ ") must have at least 1 member with a "
+ PlanningEntityCollectionProperty.class.getSimpleName() + " annotation or a "
+ PlanningEntityProperty.class.getSimpleName() + " annotation.");
}
// Do not check if problemFactCollectionMemberAccessorMap and problemFactMemberAccessorMap are empty
// because they are only required for ConstraintStreams.
if (scoreDescriptor == null) {
throw new IllegalStateException("The solutionClass (" + solutionClass
+ ") must have 1 member with a @" + PlanningScore.class.getSimpleName() + " annotation.\n"
+ "Maybe add a getScore() method with a @" + PlanningScore.class.getSimpleName() + " annotation.");
}
if (constraintConfigurationMemberAccessor != null) {
// The scoreDescriptor is definitely initialized at this point.
constraintConfigurationDescriptor.processAnnotations(descriptorPolicy, scoreDescriptor.getScoreDefinition());
}
}
private void processSolutionAnnotations(DescriptorPolicy descriptorPolicy) {
PlanningSolution solutionAnnotation = solutionClass.getAnnotation(PlanningSolution.class);
if (solutionAnnotation == null) {
throw new IllegalStateException("The solutionClass (" + solutionClass
+ ") has been specified as a solution in the configuration," +
" but does not have a @" + PlanningSolution.class.getSimpleName() + " annotation.");
}
autoDiscoverMemberType = solutionAnnotation.autoDiscoverMemberType();
Class<? extends SolutionCloner> solutionClonerClass = solutionAnnotation.solutionCloner();
if (solutionClonerClass != PlanningSolution.NullSolutionCloner.class) {
solutionCloner = ConfigUtils.newInstance(this::toString, "solutionClonerClass", solutionClonerClass);
}
lookUpStrategyResolver =
new LookUpStrategyResolver(descriptorPolicy, solutionAnnotation.lookUpStrategyType());
}
private void processValueRangeProviderAnnotation(DescriptorPolicy descriptorPolicy, Member member) {
if (((AnnotatedElement) member).isAnnotationPresent(ValueRangeProvider.class)) {
MemberAccessor memberAccessor = descriptorPolicy.getMemberAccessorFactory().buildAndCacheMemberAccessor(member,
FIELD_OR_READ_METHOD, ValueRangeProvider.class, descriptorPolicy.getDomainAccessType());
descriptorPolicy.addFromSolutionValueRangeProvider(memberAccessor);
}
}
private void processFactEntityOrScoreAnnotation(DescriptorPolicy descriptorPolicy,
Member member,
List<Class<?>> entityClassList) {
Class<? extends Annotation> annotationClass = extractFactEntityOrScoreAnnotationClassOrAutoDiscover(
member, entityClassList);
if (annotationClass == null) {
return;
} else if (annotationClass.equals(ConstraintConfigurationProvider.class)) {
processConstraintConfigurationProviderAnnotation(descriptorPolicy, member, annotationClass);
} else if (annotationClass.equals(ProblemFactProperty.class)
|| annotationClass.equals(ProblemFactCollectionProperty.class)) {
processProblemFactPropertyAnnotation(descriptorPolicy, member, annotationClass);
} else if (annotationClass.equals(PlanningEntityProperty.class)
|| annotationClass.equals(PlanningEntityCollectionProperty.class)) {
processPlanningEntityPropertyAnnotation(descriptorPolicy, member, annotationClass);
} else if (annotationClass.equals(PlanningScore.class)) {
if (scoreDescriptor == null) {
// Bottom class wins. Bottom classes are parsed first due to ConfigUtil.getAllAnnotatedLineageClasses().
scoreDescriptor = ScoreDescriptor.buildScoreDescriptor(descriptorPolicy, member, solutionClass);
} else {
scoreDescriptor.failFastOnDuplicateMember(descriptorPolicy, member, solutionClass);
}
}
}
private Class<? extends Annotation> extractFactEntityOrScoreAnnotationClassOrAutoDiscover(
Member member, List<Class<?>> entityClassList) {
Class<? extends Annotation> annotationClass = ConfigUtils.extractAnnotationClass(member,
ConstraintConfigurationProvider.class,
ProblemFactProperty.class,
ProblemFactCollectionProperty.class,
PlanningEntityProperty.class, PlanningEntityCollectionProperty.class,
PlanningScore.class);
if (annotationClass == null) {
Class<?> type;
if (autoDiscoverMemberType == AutoDiscoverMemberType.FIELD
&& member instanceof Field field) {
type = field.getType();
} else if (autoDiscoverMemberType == AutoDiscoverMemberType.GETTER
&& (member instanceof Method method) && ReflectionHelper.isGetterMethod(method)) {
type = method.getReturnType();
} else {
type = null;
}
if (type != null) {
if (Score.class.isAssignableFrom(type)) {
annotationClass = PlanningScore.class;
} else if (Collection.class.isAssignableFrom(type) || type.isArray()) {
Class<?> elementType;
if (Collection.class.isAssignableFrom(type)) {
Type genericType = (member instanceof Field f) ? f.getGenericType()
: ((Method) member).getGenericReturnType();
String memberName = member.getName();
if (!(genericType instanceof ParameterizedType)) {
throw new IllegalArgumentException("The solutionClass (" + solutionClass + ") has a "
+ "auto discovered member (" + memberName + ") with a member type (" + type
+ ") that returns a " + Collection.class.getSimpleName()
+ " which has no generic parameters.\n"
+ "Maybe the member (" + memberName + ") should return a typed "
+ Collection.class.getSimpleName() + ".");
}
elementType = ConfigUtils.extractCollectionGenericTypeParameterLeniently(
"solutionClass", solutionClass,
type, genericType,
null, member.getName()).orElse(Object.class);
} else {
elementType = type.getComponentType();
}
if (entityClassList.stream().anyMatch(entityClass -> entityClass.isAssignableFrom(elementType))) {
annotationClass = PlanningEntityCollectionProperty.class;
} else if (elementType.isAnnotationPresent(ConstraintConfiguration.class)) {
throw new IllegalStateException("The autoDiscoverMemberType (" + autoDiscoverMemberType
+ ") cannot accept a member (" + member
+ ") of type (" + type
+ ") with an elementType (" + elementType
+ ") that has a @" + ConstraintConfiguration.class.getSimpleName() + " annotation.\n"
+ "Maybe use a member of the type (" + elementType + ") directly instead of a "
+ Collection.class.getSimpleName() + " or array of that type.");
} else {
annotationClass = ProblemFactCollectionProperty.class;
}
} else if (Map.class.isAssignableFrom(type)) {
throw new IllegalStateException("The autoDiscoverMemberType (" + autoDiscoverMemberType
+ ") does not yet support the member (" + member
+ ") of type (" + type
+ ") which is an implementation of " + Map.class.getSimpleName() + ".");
} else if (entityClassList.stream().anyMatch(entityClass -> entityClass.isAssignableFrom(type))) {
annotationClass = PlanningEntityProperty.class;
} else if (type.isAnnotationPresent(ConstraintConfiguration.class)) {
annotationClass = ConstraintConfigurationProvider.class;
} else {
annotationClass = ProblemFactProperty.class;
}
}
}
return annotationClass;
}
private void processConstraintConfigurationProviderAnnotation(
DescriptorPolicy descriptorPolicy, Member member,
Class<? extends Annotation> annotationClass) {
MemberAccessor memberAccessor = descriptorPolicy.getMemberAccessorFactory().buildAndCacheMemberAccessor(member,
FIELD_OR_READ_METHOD, annotationClass, descriptorPolicy.getDomainAccessType());
if (constraintConfigurationMemberAccessor != null) {
if (!constraintConfigurationMemberAccessor.getName().equals(memberAccessor.getName())
|| !constraintConfigurationMemberAccessor.getClass().equals(memberAccessor.getClass())) {
throw new IllegalStateException("The solutionClass (" + solutionClass
+ ") has a @" + ConstraintConfigurationProvider.class.getSimpleName()
+ " annotated member (" + memberAccessor
+ ") that is duplicated by another member (" + constraintConfigurationMemberAccessor + ").\n"
+ "Maybe the annotation is defined on both the field and its getter.");
}
// Bottom class wins. Bottom classes are parsed first due to ConfigUtil.getAllAnnotatedLineageClasses()
return;
}
assertNoFieldAndGetterDuplicationOrConflict(memberAccessor, annotationClass);
constraintConfigurationMemberAccessor = memberAccessor;
// Every ConstraintConfiguration is also a problem fact
problemFactMemberAccessorMap.put(memberAccessor.getName(), memberAccessor);
Class<?> constraintConfigurationClass = constraintConfigurationMemberAccessor.getType();
if (!constraintConfigurationClass.isAnnotationPresent(ConstraintConfiguration.class)) {
throw new IllegalStateException("The solutionClass (" + solutionClass
+ ") has a @" + ConstraintConfigurationProvider.class.getSimpleName()
+ " annotated member (" + member + ") that does not return a class ("
+ constraintConfigurationClass + ") that has a "
+ ConstraintConfiguration.class.getSimpleName() + " annotation.");
}
constraintConfigurationDescriptor = new ConstraintConfigurationDescriptor<>(this, constraintConfigurationClass);
}
private void processProblemFactPropertyAnnotation(DescriptorPolicy descriptorPolicy,
Member member,
Class<? extends Annotation> annotationClass) {
MemberAccessor memberAccessor = descriptorPolicy.getMemberAccessorFactory().buildAndCacheMemberAccessor(member,
FIELD_OR_READ_METHOD, annotationClass, descriptorPolicy.getDomainAccessType());
assertNoFieldAndGetterDuplicationOrConflict(memberAccessor, annotationClass);
if (annotationClass == ProblemFactProperty.class) {
problemFactMemberAccessorMap.put(memberAccessor.getName(), memberAccessor);
} else if (annotationClass == ProblemFactCollectionProperty.class) {
Class<?> type = memberAccessor.getType();
if (!(Collection.class.isAssignableFrom(type) || type.isArray())) {
throw new IllegalStateException("The solutionClass (" + solutionClass
+ ") has a @" + ProblemFactCollectionProperty.class.getSimpleName()
+ " annotated member (" + member + ") that does not return a "
+ Collection.class.getSimpleName() + " or an array.");
}
problemFactCollectionMemberAccessorMap.put(memberAccessor.getName(), memberAccessor);
} else {
throw new IllegalStateException("Impossible situation with annotationClass (" + annotationClass + ").");
}
}
private void processPlanningEntityPropertyAnnotation(DescriptorPolicy descriptorPolicy,
Member member,
Class<? extends Annotation> annotationClass) {
MemberAccessor memberAccessor = descriptorPolicy.getMemberAccessorFactory().buildAndCacheMemberAccessor(member,
FIELD_OR_GETTER_METHOD, annotationClass, descriptorPolicy.getDomainAccessType());
assertNoFieldAndGetterDuplicationOrConflict(memberAccessor, annotationClass);
if (annotationClass == PlanningEntityProperty.class) {
entityMemberAccessorMap.put(memberAccessor.getName(), memberAccessor);
} else if (annotationClass == PlanningEntityCollectionProperty.class) {
Class<?> type = memberAccessor.getType();
if (!(Collection.class.isAssignableFrom(type) || type.isArray())) {
throw new IllegalStateException("The solutionClass (" + solutionClass
+ ") has a @" + PlanningEntityCollectionProperty.class.getSimpleName()
+ " annotated member (" + member + ") that does not return a "
+ Collection.class.getSimpleName() + " or an array.");
}
entityCollectionMemberAccessorMap.put(memberAccessor.getName(), memberAccessor);
} else {
throw new IllegalStateException("Impossible situation with annotationClass (" + annotationClass + ").");
}
}
private void assertNoFieldAndGetterDuplicationOrConflict(
MemberAccessor memberAccessor, Class<? extends Annotation> annotationClass) {
MemberAccessor duplicate;
Class<? extends Annotation> otherAnnotationClass;
String memberName = memberAccessor.getName();
if (constraintConfigurationMemberAccessor != null
&& constraintConfigurationMemberAccessor.getName().equals(memberName)) {
duplicate = constraintConfigurationMemberAccessor;
otherAnnotationClass = ConstraintConfigurationProvider.class;
} else if (problemFactMemberAccessorMap.containsKey(memberName)) {
duplicate = problemFactMemberAccessorMap.get(memberName);
otherAnnotationClass = ProblemFactProperty.class;
} else if (problemFactCollectionMemberAccessorMap.containsKey(memberName)) {
duplicate = problemFactCollectionMemberAccessorMap.get(memberName);
otherAnnotationClass = ProblemFactCollectionProperty.class;
} else if (entityMemberAccessorMap.containsKey(memberName)) {
duplicate = entityMemberAccessorMap.get(memberName);
otherAnnotationClass = PlanningEntityProperty.class;
} else if (entityCollectionMemberAccessorMap.containsKey(memberName)) {
duplicate = entityCollectionMemberAccessorMap.get(memberName);
otherAnnotationClass = PlanningEntityCollectionProperty.class;
} else {
return;
}
throw new IllegalStateException("The solutionClass (" + solutionClass
+ ") has a @" + annotationClass.getSimpleName()
+ " annotated member (" + memberAccessor
+ ") that is duplicated by a @" + otherAnnotationClass.getSimpleName()
+ " annotated member (" + duplicate + ").\n"
+ (annotationClass.equals(otherAnnotationClass)
? "Maybe the annotation is defined on both the field and its getter."
: "Maybe 2 mutually exclusive annotations are configured."));
}
private void afterAnnotationsProcessed(DescriptorPolicy descriptorPolicy) {
for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptorMap.values()) {
entityDescriptor.linkEntityDescriptors(descriptorPolicy);
}
for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptorMap.values()) {
entityDescriptor.linkVariableDescriptors(descriptorPolicy);
}
determineGlobalShadowOrder();
problemFactOrEntityClassSet = collectEntityAndProblemFactClasses();
listVariableDescriptorList = findListVariableDescriptors();
validateListVariableDescriptors();
// And finally log the successful completion of processing.
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(" Model annotations parsed for solution {}:", solutionClass.getSimpleName());
for (Map.Entry<Class<?>, EntityDescriptor<Solution_>> entry : entityDescriptorMap.entrySet()) {
EntityDescriptor<Solution_> entityDescriptor = entry.getValue();
LOGGER.trace(" Entity {}:", entityDescriptor.getEntityClass().getSimpleName());
for (VariableDescriptor<Solution_> variableDescriptor : entityDescriptor.getDeclaredVariableDescriptors()) {
LOGGER.trace(" {} variable {} ({})",
variableDescriptor instanceof GenuineVariableDescriptor ? "Genuine" : "Shadow",
variableDescriptor.getVariableName(),
variableDescriptor.getMemberAccessorSpeedNote());
}
}
}
initSolutionCloner(descriptorPolicy);
}
private void determineGlobalShadowOrder() {
// Topological sorting with Kahn's algorithm
var pairList = new ArrayList<MutablePair<ShadowVariableDescriptor<Solution_>, Integer>>();
var shadowToPairMap =
new HashMap<ShadowVariableDescriptor<Solution_>, MutablePair<ShadowVariableDescriptor<Solution_>, Integer>>();
for (var entityDescriptor : entityDescriptorMap.values()) {
for (var shadow : entityDescriptor.getDeclaredShadowVariableDescriptors()) {
var sourceSize = shadow.getSourceVariableDescriptorList().size();
var pair = MutablePair.of(shadow, sourceSize);
pairList.add(pair);
shadowToPairMap.put(shadow, pair);
}
}
for (var entityDescriptor : entityDescriptorMap.values()) {
for (var genuine : entityDescriptor.getDeclaredGenuineVariableDescriptors()) {
for (var sink : genuine.getSinkVariableDescriptorList()) {
var sinkPair = shadowToPairMap.get(sink);
sinkPair.setValue(sinkPair.getValue() - 1);
}
}
}
int globalShadowOrder = 0;
while (!pairList.isEmpty()) {
pairList.sort(Comparator.comparingInt(MutablePair::getValue));
var pair = pairList.remove(0);
var shadow = pair.getKey();
if (pair.getValue() != 0) {
if (pair.getValue() < 0) {
throw new IllegalStateException("Impossible state because the shadowVariable ("
+ shadow.getSimpleEntityAndVariableName()
+ ") cannot be used more as a sink than it has sources.");
}
throw new IllegalStateException("There is a cyclic shadow variable path"
+ " that involves the shadowVariable (" + shadow.getSimpleEntityAndVariableName()
+ ") because it must be later than its sources (" + shadow.getSourceVariableDescriptorList()
+ ") and also earlier than its sinks (" + shadow.getSinkVariableDescriptorList() + ").");
}
for (var sink : shadow.getSinkVariableDescriptorList()) {
var sinkPair = shadowToPairMap.get(sink);
sinkPair.setValue(sinkPair.getValue() - 1);
}
shadow.setGlobalShadowOrder(globalShadowOrder);
globalShadowOrder++;
}
}
private void validateListVariableDescriptors() {
if (listVariableDescriptorList.isEmpty()) {
return;
}
if (listVariableDescriptorList.size() > 1) {
throw new UnsupportedOperationException(
"Defining multiple list variables (%s) across the model is currently not supported."
.formatted(listVariableDescriptorList));
}
var listVariableDescriptor = listVariableDescriptorList.get(0);
var listVariableEntityDescriptor = listVariableDescriptor.getEntityDescriptor();
if (listVariableEntityDescriptor.getGenuineVariableDescriptorList().size() > 1) {
var basicVariableDescriptorList = new ArrayList<>(listVariableEntityDescriptor.getGenuineVariableDescriptorList());
basicVariableDescriptorList.remove(listVariableDescriptor);
throw new UnsupportedOperationException(
"Combining basic variables (%s) with list variables (%s) on a single planning entity (%s) is not supported."
.formatted(basicVariableDescriptorList, listVariableDescriptor,
listVariableDescriptor.getEntityDescriptor().getEntityClass().getCanonicalName()));
}
}
private Set<Class<?>> collectEntityAndProblemFactClasses() {
// Figure out all problem fact or entity types that are used within this solution,
// using the knowledge we've already gained by processing all the annotations.
Stream<Class<?>> entityClassStream = entityDescriptorMap.keySet()
.stream();
Stream<Class<?>> factClassStream = problemFactMemberAccessorMap
.values()
.stream()
.map(MemberAccessor::getType);
Stream<Class<?>> problemFactOrEntityClassStream = concat(entityClassStream, factClassStream);
Stream<Class<?>> factCollectionClassStream = problemFactCollectionMemberAccessorMap.values()
.stream()
.map(accessor -> ConfigUtils.extractCollectionGenericTypeParameterLeniently(
"solutionClass", getSolutionClass(),
accessor.getType(), accessor.getGenericType(), ProblemFactCollectionProperty.class,
accessor.getName()).orElse(Object.class));
problemFactOrEntityClassStream = concat(problemFactOrEntityClassStream, factCollectionClassStream);
// Add constraint configuration, if configured.
if (constraintConfigurationDescriptor != null) {
problemFactOrEntityClassStream = concat(problemFactOrEntityClassStream,
Stream.of(constraintConfigurationDescriptor.getConstraintConfigurationClass()));
}
return problemFactOrEntityClassStream.collect(Collectors.toSet());
}
private List<ListVariableDescriptor<Solution_>> findListVariableDescriptors() {
return getGenuineEntityDescriptors().stream()
.map(EntityDescriptor::getGenuineVariableDescriptorList)
.flatMap(Collection::stream)
.filter(VariableDescriptor::isListVariable)
.map(variableDescriptor -> ((ListVariableDescriptor<Solution_>) variableDescriptor))
.collect(Collectors.toList());
}
private void initSolutionCloner(DescriptorPolicy descriptorPolicy) {
solutionCloner = solutionCloner == null ? descriptorPolicy.getGeneratedSolutionClonerMap()
.get(GizmoSolutionClonerFactory.getGeneratedClassName(this))
: solutionCloner;
if (solutionCloner instanceof GizmoSolutionCloner<Solution_> gizmoSolutionCloner) {
gizmoSolutionCloner.setSolutionDescriptor(this);
}
if (solutionCloner == null) {
switch (descriptorPolicy.getDomainAccessType()) {
case GIZMO:
solutionCloner = GizmoSolutionClonerFactory.build(this, memberAccessorFactory.getGizmoClassLoader());
break;
case REFLECTION:
solutionCloner = new FieldAccessingSolutionCloner<>(this);
break;
default:
throw new IllegalStateException("The domainAccessType (" + domainAccessType
+ ") is not implemented.");
}
}
if (assertModelForCloning) {
// TODO https://issues.redhat.com/browse/PLANNER-2395
}
}
public Class<Solution_> getSolutionClass() {
return solutionClass;
}
public MemberAccessorFactory getMemberAccessorFactory() {
return memberAccessorFactory;
}
public DomainAccessType getDomainAccessType() {
return domainAccessType;
}
public ScoreDefinition getScoreDefinition() {
return scoreDescriptor.getScoreDefinition();
}
public Map<String, MemberAccessor> getProblemFactMemberAccessorMap() {
return problemFactMemberAccessorMap;
}
public Map<String, MemberAccessor> getProblemFactCollectionMemberAccessorMap() {
return problemFactCollectionMemberAccessorMap;
}
public Map<String, MemberAccessor> getEntityMemberAccessorMap() {
return entityMemberAccessorMap;
}
public Map<String, MemberAccessor> getEntityCollectionMemberAccessorMap() {
return entityCollectionMemberAccessorMap;
}
public Set<Class<?>> getProblemFactOrEntityClassSet() {
return problemFactOrEntityClassSet;
}
public ListVariableDescriptor<Solution_> getListVariableDescriptor() {
return listVariableDescriptorList.isEmpty() ? null : listVariableDescriptorList.get(0);
}
public SolutionCloner<Solution_> getSolutionCloner() {
return solutionCloner;
}
public Comparator<Object> getClassAndPlanningIdComparator() {
return classAndPlanningIdComparator;
}
public void setAssertModelForCloning(boolean assertModelForCloning) {
this.assertModelForCloning = assertModelForCloning;
}
// ************************************************************************
// Model methods
// ************************************************************************
public MemberAccessor getConstraintConfigurationMemberAccessor() {
return constraintConfigurationMemberAccessor;
}
/**
* @return sometimes null
*/
public ConstraintConfigurationDescriptor<Solution_> getConstraintConfigurationDescriptor() {
return constraintConfigurationDescriptor;
}
public Set<Class<?>> getEntityClassSet() {
return entityDescriptorMap.keySet();
}
public Collection<EntityDescriptor<Solution_>> getEntityDescriptors() {
return entityDescriptorMap.values();
}
public Collection<EntityDescriptor<Solution_>> getGenuineEntityDescriptors() {
List<EntityDescriptor<Solution_>> genuineEntityDescriptorList = new ArrayList<>(entityDescriptorMap.size());
for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptorMap.values()) {
if (entityDescriptor.hasAnyDeclaredGenuineVariableDescriptor()) {
genuineEntityDescriptorList.add(entityDescriptor);
}
}
return genuineEntityDescriptorList;
}
public EntityDescriptor<Solution_> getEntityDescriptorStrict(Class<?> entityClass) {
return entityDescriptorMap.get(entityClass);
}
public boolean hasEntityDescriptor(Class<?> entitySubclass) {
EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptor(entitySubclass);
return entityDescriptor != null;
}
public EntityDescriptor<Solution_> findEntityDescriptorOrFail(Class<?> entitySubclass) {
EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptor(entitySubclass);
if (entityDescriptor == null) {
throw new IllegalArgumentException("A planning entity is an instance of a class (" + entitySubclass
+ ") that is not configured as a planning entity class (" + getEntityClassSet() + ").\n" +
"If that class (" + entitySubclass.getSimpleName()
+ ") (or superclass thereof) is not a @" + PlanningEntity.class.getSimpleName()
+ " annotated class, maybe your @" + PlanningSolution.class.getSimpleName()
+ " annotated class has an incorrect @" + PlanningEntityCollectionProperty.class.getSimpleName()
+ " or @" + PlanningEntityProperty.class.getSimpleName() + " annotated member.\n"
+ "Otherwise, if you're not using the Quarkus extension or Spring Boot starter,"
+ " maybe that entity class (" + entitySubclass.getSimpleName()
+ ") is missing from your solver configuration.");
}
return entityDescriptor;
}
public EntityDescriptor<Solution_> findEntityDescriptor(Class<?> entitySubclass) {
/*
* A slightly optimized variant of map.computeIfAbsent(...).
* computeIfAbsent(...) would require the creation of a capturing lambda every time this method is called,
* which is created, executed once, and immediately thrown away.
* This is a micro-optimization, but it is valuable on the hot path.
*/
EntityDescriptor<Solution_> cachedEntityDescriptor = lowestEntityDescriptorMap.get(entitySubclass);
if (cachedEntityDescriptor == NULL_ENTITY_DESCRIPTOR) { // Cache hit, no descriptor found.
return null;
} else if (cachedEntityDescriptor != null) { // Cache hit, descriptor found.
return cachedEntityDescriptor;
}
// Cache miss, look for the descriptor.
EntityDescriptor<Solution_> newEntityDescriptor = innerFindEntityDescriptor(entitySubclass);
if (newEntityDescriptor == null) {
// Dummy entity descriptor value, as ConcurrentMap does not allow null values.
lowestEntityDescriptorMap.put(entitySubclass, (EntityDescriptor<Solution_>) NULL_ENTITY_DESCRIPTOR);
return null;
} else {
lowestEntityDescriptorMap.put(entitySubclass, newEntityDescriptor);
return newEntityDescriptor;
}
}
private EntityDescriptor<Solution_> innerFindEntityDescriptor(Class<?> entitySubclass) {
// Reverse order to find the nearest ancestor
for (Class<?> entityClass : reversedEntityClassList) {
if (entityClass.isAssignableFrom(entitySubclass)) {
return entityDescriptorMap.get(entityClass);
}
}
return null;
}
public VariableDescriptor<Solution_> findVariableDescriptorOrFail(Object entity, String variableName) {
EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass());
VariableDescriptor<Solution_> variableDescriptor = entityDescriptor.getVariableDescriptor(variableName);
if (variableDescriptor == null) {
throw new IllegalArgumentException(entityDescriptor.buildInvalidVariableNameExceptionMessage(variableName));
}
return variableDescriptor;
}
// ************************************************************************
// Look up methods
// ************************************************************************
public LookUpStrategyResolver getLookUpStrategyResolver() {
return lookUpStrategyResolver;
}
public void validateConstraintWeight(ConstraintRef constraintRef, Score<?> constraintWeight) {
if (constraintWeight == null) {
throw new IllegalArgumentException("The constraintWeight (" + constraintWeight
+ ") for constraint (" + constraintRef + ") must not be null.\n"
+ (constraintConfigurationDescriptor == null ? "Maybe check your constraint implementation."
: "Maybe validate the data input of your constraintConfigurationClass ("
+ constraintConfigurationDescriptor.getConstraintConfigurationClass()
+ ") for that constraint."));
}
if (!scoreDescriptor.getScoreClass().isAssignableFrom(constraintWeight.getClass())) {
throw new IllegalArgumentException("The constraintWeight (" + constraintWeight
+ ") of class (" + constraintWeight.getClass() + ") for constraint (" + constraintRef
+ ") must be of the scoreClass (" + scoreDescriptor.getScoreClass() + ").\n"
+ (constraintConfigurationDescriptor == null ? "Maybe check your constraint implementation."
: "Maybe validate the data input of your constraintConfigurationClass ("
+ constraintConfigurationDescriptor.getConstraintConfigurationClass()
+ ") for that constraint."));
}
if (constraintWeight.initScore() != 0) {
throw new IllegalArgumentException("The constraintWeight (" + constraintWeight + ") for constraint ("
+ constraintRef + ") must have an initScore (" + constraintWeight.initScore() + ") equal to 0.\n"
+ (constraintConfigurationDescriptor == null ? "Maybe check your constraint implementation."
: "Maybe validate the data input of your constraintConfigurationClass ("
+ constraintConfigurationDescriptor.getConstraintConfigurationClass()
+ ") for that constraint."));
}
if (!((ScoreDefinition) scoreDescriptor.getScoreDefinition()).isPositiveOrZero(constraintWeight)) {
throw new IllegalArgumentException("The constraintWeight (" + constraintWeight + ") for constraint ("
+ constraintRef + ") must have a positive or zero constraintWeight (" + constraintWeight + ").\n"
+ (constraintConfigurationDescriptor == null ? "Maybe check your constraint implementation."
: "Maybe validate the data input of your constraintConfigurationClass ("
+ constraintConfigurationDescriptor.getConstraintConfigurationClass()
+ ")."));
}
if (constraintWeight instanceof IBendableScore bendableConstraintWeight) {
AbstractBendableScoreDefinition bendableScoreDefinition =
(AbstractBendableScoreDefinition) scoreDescriptor.getScoreDefinition();
if (bendableConstraintWeight.hardLevelsSize() != bendableScoreDefinition.getHardLevelsSize()
|| bendableConstraintWeight.softLevelsSize() != bendableScoreDefinition.getSoftLevelsSize()) {
throw new IllegalArgumentException("The bendable constraintWeight (" + constraintWeight
+ ") for constraint (" + constraintRef + ") has a hardLevelsSize ("
+ bendableConstraintWeight.hardLevelsSize() + ") or a softLevelsSize ("
+ bendableConstraintWeight.softLevelsSize()
+ ") that doesn't match the score definition's hardLevelsSize ("
+ bendableScoreDefinition.getHardLevelsSize()
+ ") or softLevelsSize (" + bendableScoreDefinition.getSoftLevelsSize() + ").\n"
+ (constraintConfigurationDescriptor == null ? "Maybe check your constraint implementation."
: "Maybe validate the data input of your constraintConfigurationClass ("
+ constraintConfigurationDescriptor.getConstraintConfigurationClass()
+ ")."));
}
}
}
// ************************************************************************
// Extraction methods
// ************************************************************************
public Collection<Object> getAllEntitiesAndProblemFacts(Solution_ solution) {
List<Object> facts = new ArrayList<>();
visitAll(solution, facts::add);
return facts;
}
/**
* @param solution never null
* @return {@code >= 0}
*/
public int getGenuineEntityCount(Solution_ solution) {
MutableInt entityCount = new MutableInt();
// Need to go over every element in every entity collection, as some of the entities may not be genuine.
visitAllEntities(solution, fact -> {
var entityDescriptor = findEntityDescriptorOrFail(fact.getClass());
if (entityDescriptor.isGenuine()) {
entityCount.increment();
}
});
return entityCount.intValue();
}
/**
* Return accessor for a given member of a given class, if present,
* and cache it for future use.
*
* @param factClass never null
* @return null if no such member exists
*/
public MemberAccessor getPlanningIdAccessor(Class<?> factClass) {
MemberAccessor memberAccessor = planningIdMemberAccessorMap.get(factClass);
if (memberAccessor == null) {
memberAccessor =
ConfigUtils.findPlanningIdMemberAccessor(factClass, getMemberAccessorFactory(), getDomainAccessType());
MemberAccessor nonNullMemberAccessor = Objects.requireNonNullElse(memberAccessor, DummyMemberAccessor.INSTANCE);
planningIdMemberAccessorMap.put(factClass, nonNullMemberAccessor);
return memberAccessor;
} else if (memberAccessor == DummyMemberAccessor.INSTANCE) {
return null;
} else {
return memberAccessor;
}
}
public void visitAllEntities(Solution_ solution, Consumer<Object> visitor) {
visitAllEntities(solution, visitor, collection -> collection.forEach(visitor));
}
private void visitAllEntities(Solution_ solution, Consumer<Object> visitor,
Consumer<Collection<Object>> collectionVisitor) {
for (MemberAccessor entityMemberAccessor : entityMemberAccessorMap.values()) {
Object entity = extractMemberObject(entityMemberAccessor, solution);
if (entity != null) {
visitor.accept(entity);
}
}
for (MemberAccessor entityCollectionMemberAccessor : entityCollectionMemberAccessorMap.values()) {
Collection<Object> entityCollection = extractMemberCollectionOrArray(entityCollectionMemberAccessor, solution,
false);
collectionVisitor.accept(entityCollection);
}
}
/**
*
* @param solution solution to extract the entities from
* @param entityClass class of the entity to be visited, including subclasses
* @param visitor never null; applied to every entity, iteration stops if it returns true
*/
public void visitEntitiesByEntityClass(Solution_ solution, Class<?> entityClass, Predicate<Object> visitor) {
for (MemberAccessor entityMemberAccessor : entityMemberAccessorMap.values()) {
Object entity = extractMemberObject(entityMemberAccessor, solution);
if (entityClass.isInstance(entity)) {
if (visitor.test(entity)) {
return;
}
}
}
for (MemberAccessor entityCollectionMemberAccessor : entityCollectionMemberAccessorMap.values()) {
Optional<Class<?>> optionalTypeParameter = ConfigUtils.extractCollectionGenericTypeParameterLeniently(
"solutionClass", entityCollectionMemberAccessor.getDeclaringClass(),
entityCollectionMemberAccessor.getType(),
entityCollectionMemberAccessor.getGenericType(),
null,
entityCollectionMemberAccessor.getName());
boolean collectionGuaranteedToContainOnlyGivenEntityType = optionalTypeParameter
.map(entityClass::isAssignableFrom)
.orElse(false);
if (collectionGuaranteedToContainOnlyGivenEntityType) {
/*
* In a typical case typeParameter is specified and it is the expected entity or its superclass.
* Therefore we can simply apply the visitor on each element.
*/
Collection<Object> entityCollection =
extractMemberCollectionOrArray(entityCollectionMemberAccessor, solution, false);
for (Object o : entityCollection) {
if (visitor.test(o)) {
return;
}
}
continue;
}
// The collection now is either raw, or it is not of an entity type, such as perhaps a parent interface.
boolean collectionCouldPossiblyContainGivenEntityType = optionalTypeParameter
.map(e -> e.isAssignableFrom(entityClass))
.orElse(true);
if (!collectionCouldPossiblyContainGivenEntityType) {
// There is no way how this collection could possibly contain entities of the given type.
continue;
}
// We need to go over every collection member and check if it is an entity of the given type.
Collection<Object> entityCollection =
extractMemberCollectionOrArray(entityCollectionMemberAccessor, solution, false);
for (Object entity : entityCollection) {
if (entityClass.isInstance(entity)) {
if (visitor.test(entity)) {
return;
}
}
}
}
}
public void visitAllProblemFacts(Solution_ solution, Consumer<Object> visitor) {
// Visits facts.
for (MemberAccessor accessor : problemFactMemberAccessorMap.values()) {
Object object = extractMemberObject(accessor, solution);
if (object != null) {
visitor.accept(object);
}
}
// Visits problem facts from problem fact collections.
for (MemberAccessor accessor : problemFactCollectionMemberAccessorMap.values()) {
Collection<Object> objects = extractMemberCollectionOrArray(accessor, solution, true);
for (Object object : objects) {
visitor.accept(object);
}
}
}
public void visitAll(Solution_ solution, Consumer<Object> visitor) {
visitAllProblemFacts(solution, visitor);
visitAllEntities(solution, visitor);
}
/**
* @param scoreDirector never null
* @return {@code >= 0}
*/
public boolean hasMovableEntities(ScoreDirector<Solution_> scoreDirector) {
return extractAllEntitiesStream(scoreDirector.getWorkingSolution())
.anyMatch(entity -> findEntityDescriptorOrFail(entity.getClass()).isMovable(scoreDirector, entity));
}
/**
* @param solution never null
* @return {@code >= 0}
*/
public long getGenuineVariableCount(Solution_ solution) {
MutableLong result = new MutableLong();
visitAllEntities(solution, entity -> {
var entityDescriptor = findEntityDescriptorOrFail(entity.getClass());
if (entityDescriptor.isGenuine()) {
result.add(entityDescriptor.getGenuineVariableCount());
}
});
return result.longValue();
}
/**
* @param solution never null
* @return {@code >= 0}
*/
public long getApproximateValueCount(Solution_ solution) {
var genuineVariableDescriptorSet =
Collections.newSetFromMap(new IdentityHashMap<GenuineVariableDescriptor<Solution_>, Boolean>());
visitAllEntities(solution, entity -> {
var entityDescriptor = findEntityDescriptorOrFail(entity.getClass());
if (entityDescriptor.isGenuine()) {
genuineVariableDescriptorSet.addAll(entityDescriptor.getGenuineVariableDescriptorList());
}
});
MutableLong out = new MutableLong();
for (var variableDescriptor : genuineVariableDescriptorSet) {
var valueRangeDescriptor = variableDescriptor.getValueRangeDescriptor();
if (valueRangeDescriptor.isEntityIndependent()) {
var entityIndependentVariableDescriptor =
(EntityIndependentValueRangeDescriptor<Solution_>) valueRangeDescriptor;
out.add(entityIndependentVariableDescriptor.extractValueRangeSize(solution));
} else {
visitEntitiesByEntityClass(solution,
variableDescriptor.getEntityDescriptor().getEntityClass(),
entity -> {
out.add(valueRangeDescriptor.extractValueRangeSize(solution, entity));
return false;
});
}
}
return out.longValue();
}
public long getMaximumValueRangeSize(Solution_ solution) {
return extractAllEntitiesStream(solution)
.mapToLong(entity -> {
var entityDescriptor = findEntityDescriptorOrFail(entity.getClass());
return entityDescriptor.isGenuine() ? entityDescriptor.getMaximumValueCount(solution, entity) : 0L;
})
.max()
.orElse(0L);
}
/**
* Calculates an indication on how big this problem instance is.
* This is approximately the base 10 log of the search space size.
*
* @param solution never null
* @return {@code >= 0}
*/
public double getProblemScale(ScoreDirector<Solution_> scoreDirector, Solution_ solution) {
long logBase = getMaximumValueRangeSize(solution);
ProblemScaleTracker problemScaleTracker = new ProblemScaleTracker(logBase);
visitAllEntities(solution, entity -> {
var entityDescriptor = findEntityDescriptorOrFail(entity.getClass());
if (entityDescriptor.isGenuine()) {
entityDescriptor.processProblemScale(scoreDirector, solution, entity, problemScaleTracker);
}
});
long result = problemScaleTracker.getBasicProblemScaleLog();
if (problemScaleTracker.getListTotalEntityCount() != 0L) {
// List variables do not support from entity value ranges
int totalListValueCount = problemScaleTracker.getListTotalValueCount();
int totalListMovableValueCount = totalListValueCount - problemScaleTracker.getListPinnedValueCount();
int possibleTargetsForListValue = problemScaleTracker.getListMovableEntityCount();
var listVariableDescriptor = 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);
}
return (result / (double) MathUtils.LOG_PRECISION) / MathUtils.getLogInBase(logBase, 10d);
}
public ProblemSizeStatistics getProblemSizeStatistics(ScoreDirector<Solution_> scoreDirector, Solution_ solution) {
return new ProblemSizeStatistics(
getGenuineEntityCount(solution),
getGenuineVariableCount(solution),
getApproximateValueCount(solution),
getProblemScale(scoreDirector, solution));
}
public SolutionInitializationStatistics computeInitializationStatistics(Solution_ solution) {
return computeInitializationStatistics(solution, null);
}
public SolutionInitializationStatistics computeInitializationStatistics(Solution_ solution, 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 genuineEntityCount = new MutableInt();
var shadowEntityCount = new MutableInt();
for (var listVariableDescriptor : listVariableDescriptorList) {
if (listVariableDescriptor.allowsUnassignedValues()) { // Unassigned elements count as assigned.
continue;
}
// We count every possibly unassigned element in every list variable.
// And later we subtract the assigned elements.
unassignedValueCount.add((int) listVariableDescriptor.getValueRangeSize(solution, null));
}
visitAllEntities(solution, entity -> {
var entityDescriptor = 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;
}
for (var listVariableDescriptor : listVariableDescriptorList) {
if (listVariableDescriptor.allowsUnassignedValues()) { // Unassigned elements count as assigned.
continue;
}
var listVariableEntityDescriptor = listVariableDescriptor.getEntityDescriptor();
if (listVariableEntityDescriptor.matchesEntity(entity)) {
unassignedValueCount.subtract(listVariableDescriptor.getListSize(entity));
}
// 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());
}
public record SolutionInitializationStatistics(int genuineEntityCount, int shadowEntityCount,
int uninitializedEntityCount, int uninitializedVariableCount, int unassignedValueCount) {
}
private Stream<Object> extractAllEntitiesStream(Solution_ solution) {
Stream<Object> stream = Stream.empty();
for (MemberAccessor memberAccessor : entityMemberAccessorMap.values()) {
Object entity = extractMemberObject(memberAccessor, solution);
if (entity != null) {
stream = concat(stream, Stream.of(entity));
}
}
for (MemberAccessor memberAccessor : entityCollectionMemberAccessorMap.values()) {
Collection<Object> entityCollection = extractMemberCollectionOrArray(memberAccessor, solution, false);
stream = concat(stream, entityCollection.stream());
}
return stream;
}
private Object extractMemberObject(MemberAccessor memberAccessor, Solution_ solution) {
return memberAccessor.executeGetter(solution);
}
private Collection<Object> extractMemberCollectionOrArray(MemberAccessor memberAccessor, Solution_ solution,
boolean isFact) {
Collection<Object> collection;
if (memberAccessor.getType().isArray()) {
Object arrayObject = memberAccessor.executeGetter(solution);
collection = ReflectionHelper.transformArrayToList(arrayObject);
} else {
collection = (Collection<Object>) memberAccessor.executeGetter(solution);
}
if (collection == null) {
throw new IllegalArgumentException("The solutionClass (" + solutionClass
+ ")'s " + (isFact ? "factCollectionProperty" : "entityCollectionProperty") + " ("
+ memberAccessor + ") should never return null.\n"
+ (memberAccessor instanceof ReflectionFieldMemberAccessor ? ""
: "Maybe the getter/method always returns null instead of the actual data.\n")
+ "Maybe that property (" + memberAccessor.getName()
+ ") was set with null instead of an empty collection/array when the class ("
+ solutionClass.getSimpleName() + ") instance was created.");
}
return collection;
}
/**
* @param solution never null
* @return sometimes null, if the {@link Score} hasn't been calculated yet
*/
public Score getScore(Solution_ solution) {
return scoreDescriptor.getScore(solution);
}
/**
* Called when the {@link Score} has been calculated or predicted.
*
* @param solution never null
* @param score sometimes null, in rare occasions to indicate that the old {@link Score} is stale,
* but no new ones has been calculated
*/
public void setScore(Solution_ solution, Score score) {
scoreDescriptor.setScore(solution, score);
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + solutionClass.getName() + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/AbstractCountableValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeFactory;
/**
* Abstract superclass for {@link CountableValueRange} (and therefore {@link ValueRange}).
*
* @see CountableValueRange
* @see ValueRange
* @see ValueRangeFactory
*/
public abstract class AbstractCountableValueRange<T> implements CountableValueRange<T> {
@Override
public boolean isEmpty() {
return getSize() == 0L;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/bigdecimal/BigDecimalValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.bigdecimal;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
public class BigDecimalValueRange extends AbstractCountableValueRange<BigDecimal> {
private final BigDecimal from;
private final BigDecimal to;
private final BigDecimal incrementUnit;
/**
* All parameters must have the same {@link BigDecimal#scale()}.
*
* @param from never null, inclusive minimum
* @param to never null, exclusive maximum, {@code >= from}
*/
public BigDecimalValueRange(BigDecimal from, BigDecimal to) {
this(from, to, BigDecimal.valueOf(1L, from.scale()));
}
/**
* All parameters must have the same {@link BigDecimal#scale()}.
*
* @param from never null, inclusive minimum
* @param to never null, exclusive maximum, {@code >= from}
* @param incrementUnit never null, {@code > 0}
*/
public BigDecimalValueRange(BigDecimal from, BigDecimal to, BigDecimal incrementUnit) {
this.from = from;
this.to = to;
this.incrementUnit = incrementUnit;
int scale = from.scale();
if (scale != to.scale()) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a to (" + to + ") scale (" + to.scale()
+ ") which is different than its from (" + from + ") scale (" + scale + ").");
}
if (scale != incrementUnit.scale()) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a from (" + incrementUnit + ") scale (" + incrementUnit.scale()
+ ") which is different than its from (" + from + ") scale (" + scale + ").");
}
if (to.compareTo(from) < 0) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a from (" + from + ") which is strictly higher than its to (" + to + ").");
}
if (incrementUnit.compareTo(BigDecimal.ZERO) <= 0) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " must have strictly positive incrementUnit (" + incrementUnit + ").");
}
if (!to.unscaledValue().subtract(from.unscaledValue()).remainder(incrementUnit.unscaledValue())
.equals(BigInteger.ZERO)) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ "'s incrementUnit (" + incrementUnit
+ ") must fit an integer number of times between from (" + from + ") and to (" + to + ").");
}
}
@Override
public long getSize() {
return to.unscaledValue().subtract(from.unscaledValue()).divide(incrementUnit.unscaledValue()).longValue();
}
@Override
public BigDecimal get(long index) {
if (index < 0L || index >= getSize()) {
throw new IndexOutOfBoundsException("The index (" + index + ") must be >= 0 and < size ("
+ getSize() + ").");
}
return incrementUnit.multiply(BigDecimal.valueOf(index)).add(from);
}
@Override
public boolean contains(BigDecimal value) {
if (value == null || value.compareTo(from) < 0 || value.compareTo(to) >= 0) {
return false;
}
return value.subtract(from).remainder(incrementUnit).compareTo(BigDecimal.ZERO) == 0;
}
@Override
public Iterator<BigDecimal> createOriginalIterator() {
return new OriginalBigDecimalValueRangeIterator();
}
private class OriginalBigDecimalValueRangeIterator extends ValueRangeIterator<BigDecimal> {
private BigDecimal upcoming = from;
@Override
public boolean hasNext() {
return upcoming.compareTo(to) < 0;
}
@Override
public BigDecimal next() {
if (upcoming.compareTo(to) >= 0) {
throw new NoSuchElementException();
}
BigDecimal next = upcoming;
upcoming = upcoming.add(incrementUnit);
return next;
}
}
@Override
public Iterator<BigDecimal> createRandomIterator(Random workingRandom) {
return new RandomBigDecimalValueRangeIterator(workingRandom);
}
private class RandomBigDecimalValueRangeIterator extends ValueRangeIterator<BigDecimal> {
private final Random workingRandom;
private final long size = getSize();
public RandomBigDecimalValueRangeIterator(Random workingRandom) {
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return size > 0L;
}
@Override
public BigDecimal next() {
if (size <= 0L) {
throw new NoSuchElementException();
}
long index = RandomUtils.nextLong(workingRandom, size);
return incrementUnit.multiply(BigDecimal.valueOf(index)).add(from);
}
}
@Override
public String toString() {
return "[" + from + "-" + to + ")"; // Formatting: interval (mathematics) ISO 31-11
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/biginteger/BigIntegerValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.biginteger;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
public class BigIntegerValueRange extends AbstractCountableValueRange<BigInteger> {
private final BigInteger from;
private final BigInteger to;
private final BigInteger incrementUnit;
/**
* @param from never null, inclusive minimum
* @param to never null, exclusive maximum, {@code >= from}
*/
public BigIntegerValueRange(BigInteger from, BigInteger to) {
this(from, to, BigInteger.valueOf(1L));
}
/**
* @param from never null, inclusive minimum
* @param to never null, exclusive maximum, {@code >= from}
* @param incrementUnit never null, {@code > 0}
*/
public BigIntegerValueRange(BigInteger from, BigInteger to, BigInteger incrementUnit) {
this.from = from;
this.to = to;
this.incrementUnit = incrementUnit;
if (to.compareTo(from) < 0) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a from (" + from + ") which is strictly higher than its to (" + to + ").");
}
if (incrementUnit.compareTo(BigInteger.ZERO) <= 0) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " must have strictly positive incrementUnit (" + incrementUnit + ").");
}
if (!to.subtract(from).remainder(incrementUnit).equals(BigInteger.ZERO)) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ "'s incrementUnit (" + incrementUnit
+ ") must fit an integer number of times between from (" + from + ") and to (" + to + ").");
}
}
@Override
public long getSize() {
return to.subtract(from).divide(incrementUnit).longValue();
}
@Override
public BigInteger get(long index) {
if (index < 0L || index >= getSize()) {
throw new IndexOutOfBoundsException("The index (" + index + ") must be >= 0 and < size ("
+ getSize() + ").");
}
return incrementUnit.multiply(BigInteger.valueOf(index)).add(from);
}
@Override
public boolean contains(BigInteger value) {
if (value == null || value.compareTo(from) < 0 || value.compareTo(to) >= 0) {
return false;
}
return value.subtract(from).remainder(incrementUnit).compareTo(BigInteger.ZERO) == 0;
}
@Override
public Iterator<BigInteger> createOriginalIterator() {
return new OriginalBigIntegerValueRangeIterator();
}
private class OriginalBigIntegerValueRangeIterator extends ValueRangeIterator<BigInteger> {
private BigInteger upcoming = from;
@Override
public boolean hasNext() {
return upcoming.compareTo(to) < 0;
}
@Override
public BigInteger next() {
if (upcoming.compareTo(to) >= 0) {
throw new NoSuchElementException();
}
BigInteger next = upcoming;
upcoming = upcoming.add(incrementUnit);
return next;
}
}
@Override
public Iterator<BigInteger> createRandomIterator(Random workingRandom) {
return new RandomBigIntegerValueRangeIterator(workingRandom);
}
private class RandomBigIntegerValueRangeIterator extends ValueRangeIterator<BigInteger> {
private final Random workingRandom;
private final long size = getSize();
public RandomBigIntegerValueRangeIterator(Random workingRandom) {
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return size > 0L;
}
@Override
public BigInteger next() {
if (size <= 0L) {
throw new NoSuchElementException();
}
long index = RandomUtils.nextLong(workingRandom, size);
return incrementUnit.multiply(BigInteger.valueOf(index)).add(from);
}
}
@Override
public String toString() {
return "[" + from + "-" + to + ")"; // Formatting: interval (mathematics) ISO 31-11
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/collection/ListValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.collection;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.CachedListRandomIterator;
public class ListValueRange<T> extends AbstractCountableValueRange<T> {
private final List<T> list;
public ListValueRange(List<T> list) {
this.list = list;
}
@Override
public long getSize() {
return list.size();
}
@Override
public T get(long index) {
if (index > Integer.MAX_VALUE) {
throw new IndexOutOfBoundsException("The index (" + index + ") must fit in an int.");
}
return list.get((int) index);
}
@Override
public boolean contains(T value) {
return list.contains(value);
}
@Override
public Iterator<T> createOriginalIterator() {
return list.iterator();
}
@Override
public Iterator<T> createRandomIterator(Random workingRandom) {
return new CachedListRandomIterator<>(list, workingRandom);
}
@Override
public String toString() {
// Formatting: interval (mathematics) ISO 31-11
return list.isEmpty() ? "[]" : "[" + list.get(0) + "-" + list.get(list.size() - 1) + "]";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/composite/CompositeCountableValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.composite;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
public class CompositeCountableValueRange<T> extends AbstractCountableValueRange<T> {
private final List<? extends CountableValueRange<T>> childValueRangeList;
private final long size;
public CompositeCountableValueRange(List<? extends CountableValueRange<T>> childValueRangeList) {
this.childValueRangeList = childValueRangeList;
long size = 0L;
for (CountableValueRange<T> childValueRange : childValueRangeList) {
size += childValueRange.getSize();
}
this.size = size;
}
public List<? extends ValueRange<T>> getChildValueRangeList() {
return childValueRangeList;
}
@Override
public long getSize() {
return size;
}
@Override
public T get(long index) {
long remainingIndex = index;
for (CountableValueRange<T> childValueRange : childValueRangeList) {
long childSize = childValueRange.getSize();
if (remainingIndex < childSize) {
return childValueRange.get(remainingIndex);
}
remainingIndex -= childSize;
}
throw new IndexOutOfBoundsException("The index (" + index + ") must be less than the size (" + size + ").");
}
@Override
public boolean contains(T value) {
for (CountableValueRange<T> childValueRange : childValueRangeList) {
if (childValueRange.contains(value)) {
return true;
}
}
return false;
}
@Override
public Iterator<T> createOriginalIterator() {
Stream<T> stream = Stream.empty();
for (CountableValueRange<T> childValueRange : childValueRangeList) {
stream = Stream.concat(stream, originalIteratorToStream(childValueRange));
}
return stream.iterator();
}
private static <T> Stream<T> originalIteratorToStream(CountableValueRange<T> valueRange) {
return StreamSupport.stream(
Spliterators.spliterator(valueRange.createOriginalIterator(), valueRange.getSize(), Spliterator.ORDERED),
false);
}
@Override
public Iterator<T> createRandomIterator(Random workingRandom) {
return new RandomCompositeValueRangeIterator(workingRandom);
}
private class RandomCompositeValueRangeIterator extends ValueRangeIterator<T> {
private final Random workingRandom;
public RandomCompositeValueRangeIterator(Random workingRandom) {
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return true;
}
@Override
public T next() {
long index = RandomUtils.nextLong(workingRandom, size);
long remainingIndex = index;
for (CountableValueRange<T> childValueRange : childValueRangeList) {
long childSize = childValueRange.getSize();
if (remainingIndex < childSize) {
return childValueRange.get(remainingIndex);
}
remainingIndex -= childSize;
}
throw new IllegalStateException("Impossible state because index (" + index
+ ") is always less than the size (" + size + ").");
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/composite/EmptyValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.composite;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
public class EmptyValueRange<T> extends AbstractCountableValueRange<T> {
public EmptyValueRange() {
}
@Override
public long getSize() {
return 0L;
}
@Override
public T get(long index) {
throw new IndexOutOfBoundsException("The index (" + index + ") must be >= 0 and < size ("
+ getSize() + ").");
}
@Override
public boolean contains(T value) {
return false;
}
@Override
public Iterator<T> createOriginalIterator() {
return new EmptyValueRangeIterator();
}
@Override
public Iterator<T> createRandomIterator(Random workingRandom) {
return new EmptyValueRangeIterator();
}
private class EmptyValueRangeIterator extends ValueRangeIterator<T> {
@Override
public boolean hasNext() {
return false;
}
@Override
public T next() {
throw new NoSuchElementException();
}
}
@Override
public String toString() {
return "[]"; // Formatting: interval (mathematics) ISO 31-11
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/composite/NullAllowingCountableValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.composite;
import java.util.Iterator;
import java.util.Random;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
public final class NullAllowingCountableValueRange<T> extends AbstractCountableValueRange<T> {
private final CountableValueRange<T> childValueRange;
private final long size;
public NullAllowingCountableValueRange(CountableValueRange<T> childValueRange) {
this.childValueRange = childValueRange;
size = childValueRange.getSize() + 1L;
}
public ValueRange<T> getChildValueRange() {
return childValueRange;
}
@Override
public long getSize() {
return size;
}
@Override
public T get(long index) {
if (index == 0) { // Consistent with the iterator.
return null;
} else {
return childValueRange.get(index - 1L);
}
}
@Override
public boolean contains(T value) {
if (value == null) {
return true;
}
return childValueRange.contains(value);
}
@Override
public Iterator<T> createOriginalIterator() {
return new OriginalNullValueRangeIterator(childValueRange.createOriginalIterator());
}
private class OriginalNullValueRangeIterator extends ValueRangeIterator<T> {
private boolean nullReturned = false;
private final Iterator<T> childIterator;
public OriginalNullValueRangeIterator(Iterator<T> childIterator) {
this.childIterator = childIterator;
}
@Override
public boolean hasNext() {
return !nullReturned || childIterator.hasNext();
}
@Override
public T next() {
if (!nullReturned) {
nullReturned = true;
return null;
} else {
return childIterator.next();
}
}
}
@Override
public Iterator<T> createRandomIterator(Random workingRandom) {
return new RandomNullValueRangeIterator(workingRandom);
}
private class RandomNullValueRangeIterator extends ValueRangeIterator<T> {
private final Random workingRandom;
public RandomNullValueRangeIterator(Random workingRandom) {
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return true;
}
@Override
public T next() {
long index = RandomUtils.nextLong(workingRandom, size);
return get(index);
}
}
@Override
public String toString() {
return "[null]∪" + childValueRange; // Formatting: interval (mathematics) ISO 31-11
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/primboolean/BooleanValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.primboolean;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
public class BooleanValueRange extends AbstractCountableValueRange<Boolean> {
public BooleanValueRange() {
}
@Override
public long getSize() {
return 2L;
}
@Override
public boolean contains(Boolean value) {
if (value == null) {
return false;
}
return true;
}
@Override
public Boolean get(long index) {
if (index < 0L || index >= 2L) {
throw new IndexOutOfBoundsException("The index (" + index + ") must be >= 0 and < 2.");
}
return index == 0L ? Boolean.FALSE : Boolean.TRUE;
}
@Override
public Iterator<Boolean> createOriginalIterator() {
return new OriginalBooleanValueRangeIterator();
}
private static final class OriginalBooleanValueRangeIterator extends ValueRangeIterator<Boolean> {
private boolean hasNext = true;
private Boolean upcoming = Boolean.FALSE;
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public Boolean next() {
if (!hasNext) {
throw new NoSuchElementException();
}
Boolean next = upcoming;
if (upcoming) {
hasNext = false;
} else {
upcoming = Boolean.TRUE;
}
return next;
}
}
@Override
public Iterator<Boolean> createRandomIterator(Random workingRandom) {
return new RandomBooleanValueRangeIterator(workingRandom);
}
private static final class RandomBooleanValueRangeIterator extends ValueRangeIterator<Boolean> {
private final Random workingRandom;
public RandomBooleanValueRangeIterator(Random workingRandom) {
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return true;
}
@Override
public Boolean next() {
return Boolean.valueOf(workingRandom.nextBoolean());
}
}
@Override
public String toString() {
return "[false, true]"; // Formatting: interval (mathematics) ISO 31-11
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/primdouble/DoubleValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.primdouble;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractUncountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.buildin.bigdecimal.BigDecimalValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
/**
* Note: Floating point numbers (float, double) cannot represent a decimal number correctly.
* If floating point numbers leak into the scoring function, they are likely to cause score corruptions.
* To avoid that, use either {@link java.math.BigDecimal} or fixed-point arithmetic.
*
* @deprecated Prefer {@link BigDecimalValueRange}.
*/
@Deprecated(forRemoval = true, since = "1.1.0")
public class DoubleValueRange extends AbstractUncountableValueRange<Double> {
private final double from;
private final double to;
/**
* @param from inclusive minimum
* @param to exclusive maximum, {@code >= from}
*/
public DoubleValueRange(double from, double to) {
this.from = from;
this.to = to;
if (to < from) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a from (" + from + ") which is strictly higher than its to (" + to + ").");
}
}
@Override
public boolean isEmpty() {
return from == to;
}
@Override
public boolean contains(Double value) {
if (value == null) {
return false;
}
return value >= from && value < to;
}
// In theory, we can implement createOriginalIterator() by using Math.nextAfter().
// But in practice, no one could use it.
@Override
public Iterator<Double> createRandomIterator(Random workingRandom) {
return new RandomDoubleValueRangeIterator(workingRandom);
}
private class RandomDoubleValueRangeIterator extends ValueRangeIterator<Double> {
private final Random workingRandom;
public RandomDoubleValueRangeIterator(Random workingRandom) {
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return to != from;
}
@Override
public Double next() {
if (to == from) {
throw new NoSuchElementException();
}
double diff = to - from;
double next = from + diff * workingRandom.nextDouble();
if (next >= to) {
// Rounding error occurred
next = Math.nextAfter(next, Double.NEGATIVE_INFINITY);
}
return next;
}
}
@Override
public String toString() {
return "[" + from + "-" + to + ")"; // Formatting: interval (mathematics) ISO 31-11
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/primint/IntValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.primint;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
public class IntValueRange extends AbstractCountableValueRange<Integer> {
private final int from;
private final int to;
private final int incrementUnit;
/**
* @param from inclusive minimum
* @param to exclusive maximum, {@code >= from}
*/
public IntValueRange(int from, int to) {
this(from, to, 1);
}
/**
* @param from inclusive minimum
* @param to exclusive maximum, {@code >= from}
* @param incrementUnit {@code > 0}
*/
public IntValueRange(int from, int to, int incrementUnit) {
this.from = from;
this.to = to;
this.incrementUnit = incrementUnit;
if (to < from) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a from (" + from + ") which is strictly higher than its to (" + to + ").");
}
if (incrementUnit <= 0) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " must have strictly positive incrementUnit (" + incrementUnit + ").");
}
if ((to - (long) from) % incrementUnit != 0L) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ "'s incrementUnit (" + incrementUnit
+ ") must fit an integer number of times between from (" + from + ") and to (" + to + ").");
}
}
@Override
public long getSize() {
return (to - (long) from) / incrementUnit;
}
@Override
public boolean contains(Integer value) {
if (value == null || value < from || value >= to) {
return false;
}
if (incrementUnit == 1) {
return true;
}
return ((long) value - from) % incrementUnit == 0;
}
@Override
public Integer get(long index) {
if (index < 0L || index >= getSize()) {
throw new IndexOutOfBoundsException("The index (" + index + ") must be >= 0 and < size ("
+ getSize() + ").");
}
return (int) (index * incrementUnit + from);
}
@Override
public Iterator<Integer> createOriginalIterator() {
return new OriginalIntValueRangeIterator();
}
private class OriginalIntValueRangeIterator extends ValueRangeIterator<Integer> {
private int upcoming = from;
@Override
public boolean hasNext() {
return upcoming < to;
}
@Override
public Integer next() {
if (upcoming >= to) {
throw new NoSuchElementException();
}
int next = upcoming;
upcoming += incrementUnit;
return next;
}
}
@Override
public Iterator<Integer> createRandomIterator(Random workingRandom) {
return new RandomIntValueRangeIterator(workingRandom);
}
private class RandomIntValueRangeIterator extends ValueRangeIterator<Integer> {
private final Random workingRandom;
private final long size = getSize();
public RandomIntValueRangeIterator(Random workingRandom) {
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return size > 0L;
}
@Override
public Integer next() {
if (size <= 0L) {
throw new NoSuchElementException();
}
long index = RandomUtils.nextLong(workingRandom, size);
return (int) (index * incrementUnit + from);
}
}
@Override
public String toString() {
return "[" + from + "-" + to + ")"; // Formatting: interval (mathematics) ISO 31-11
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/primlong/LongValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.primlong;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
public class LongValueRange extends AbstractCountableValueRange<Long> {
private final long from;
private final long to;
private final long incrementUnit;
/**
* @param from inclusive minimum
* @param to exclusive maximum, {@code >= from}
*/
public LongValueRange(long from, long to) {
this(from, to, 1);
}
/**
* @param from inclusive minimum
* @param to exclusive maximum, {@code >= from}
* @param incrementUnit {@code > 0}
*/
public LongValueRange(long from, long to, long incrementUnit) {
this.from = from;
this.to = to;
this.incrementUnit = incrementUnit;
if (to < from) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a from (" + from + ") which is strictly higher than its to (" + to + ").");
}
if (incrementUnit <= 0L) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " must have strictly positive incrementUnit (" + incrementUnit + ").");
}
if ((to - from) < 0L) { // Overflow way to detect if ((to - from) > Long.MAX_VALUE)
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a from (" + from + ") and to (" + to
+ ") with a gap greater than Long.MAX_VALUE (" + Long.MAX_VALUE + ").");
}
if ((to - from) % incrementUnit != 0L) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ "'s incrementUnit (" + incrementUnit
+ ") must fit an integer number of times between from (" + from + ") and to (" + to + ").");
}
}
@Override
public long getSize() {
return (to - from) / incrementUnit;
}
@Override
public boolean contains(Long value) {
if (value == null || value < from || value >= to) {
return false;
}
if (incrementUnit == 1L) {
return true;
}
return (value - from) % incrementUnit == 0L;
}
@Override
public Long get(long index) {
if (index < 0L || index >= getSize()) {
throw new IndexOutOfBoundsException("The index (" + index + ") must be >= 0 and < size ("
+ getSize() + ").");
}
return index * incrementUnit + from;
}
@Override
public Iterator<Long> createOriginalIterator() {
return new OriginalLongValueRangeIterator();
}
private class OriginalLongValueRangeIterator extends ValueRangeIterator<Long> {
private long upcoming = from;
@Override
public boolean hasNext() {
return upcoming < to;
}
@Override
public Long next() {
if (upcoming >= to) {
throw new NoSuchElementException();
}
long next = upcoming;
upcoming += incrementUnit;
return next;
}
}
@Override
public Iterator<Long> createRandomIterator(Random workingRandom) {
return new RandomLongValueRangeIterator(workingRandom);
}
private class RandomLongValueRangeIterator extends ValueRangeIterator<Long> {
private final Random workingRandom;
private final long size = getSize();
public RandomLongValueRangeIterator(Random workingRandom) {
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return size > 0L;
}
@Override
public Long next() {
if (size <= 0L) {
throw new NoSuchElementException();
}
long index = RandomUtils.nextLong(workingRandom, size);
return index * incrementUnit + from;
}
}
@Override
public String toString() {
return "[" + from + "-" + to + ")"; // Formatting: interval (mathematics) ISO 31-11
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/buildin/temporal/TemporalValueRange.java | package ai.timefold.solver.core.impl.domain.valuerange.buildin.temporal;
import java.time.DateTimeException;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalUnit;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import ai.timefold.solver.core.impl.domain.valuerange.AbstractCountableValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.util.ValueRangeIterator;
import ai.timefold.solver.core.impl.solver.random.RandomUtils;
public class TemporalValueRange<Temporal_ extends Temporal & Comparable<? super Temporal_>>
extends AbstractCountableValueRange<Temporal_> {
private final Temporal_ from;
private final Temporal_ to;
/** We could not use a {@link TemporalAmount} as {@code incrementUnit} due to lack of calculus functions. */
private final long incrementUnitAmount;
private final TemporalUnit incrementUnitType;
private final long size;
/**
* @param from never null, inclusive minimum
* @param to never null, exclusive maximum, {@code >= from}
* @param incrementUnitAmount {@code > 0}
* @param incrementUnitType never null, must be {@link Temporal#isSupported(TemporalUnit) supported} by {@code from}
* and {@code to}
*/
public TemporalValueRange(Temporal_ from, Temporal_ to, long incrementUnitAmount, TemporalUnit incrementUnitType) {
this.from = from;
this.to = to;
this.incrementUnitAmount = incrementUnitAmount;
this.incrementUnitType = incrementUnitType;
if (from == null || to == null || incrementUnitType == null) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " must have a from (" + from + "), to (" + to + ") and incrementUnitType (" + incrementUnitType
+ ") that are not null.");
}
if (incrementUnitAmount <= 0) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " must have strictly positive incrementUnitAmount (" + incrementUnitAmount + ").");
}
if (!from.isSupported(incrementUnitType) || !to.isSupported(incrementUnitType)) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " must have an incrementUnitType (" + incrementUnitType
+ ") that is supported by its from (" + from + ") class (" + from.getClass().getSimpleName()
+ ") and to (" + to + ") class (" + to.getClass().getSimpleName() + ").");
}
// We cannot use Temporal.until() to check bounds due to rounding errors
if (from.compareTo(to) > 0) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ " cannot have a from (" + from + ") which is strictly higher than its to (" + to + ").");
}
long space = from.until(to, incrementUnitType);
Temporal expectedTo = from.plus(space, incrementUnitType);
if (!to.equals(expectedTo)) {
// Temporal.until() rounds down, but it needs to round up, to be consistent with Temporal.plus()
space++;
Temporal roundedExpectedTo;
try {
roundedExpectedTo = from.plus(space, incrementUnitType);
} catch (DateTimeException e) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ "'s incrementUnitType (" + incrementUnitType
+ ") must fit an integer number of times in the space (" + space
+ ") between from (" + from + ") and to (" + to + ").\n"
+ "The to (" + to + ") is not the expectedTo (" + expectedTo + ").", e);
}
// Fail fast if there's a remainder on type (to be consistent with other value ranges)
if (!to.equals(roundedExpectedTo)) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ "'s incrementUnitType (" + incrementUnitType
+ ") must fit an integer number of times in the space (" + space
+ ") between from (" + from + ") and to (" + to + ").\n"
+ "The to (" + to + ") is not the expectedTo (" + expectedTo
+ ") nor the roundedExpectedTo (" + roundedExpectedTo + ").");
}
}
// Fail fast if there's a remainder on amount (to be consistent with other value ranges)
if (space % incrementUnitAmount > 0) {
throw new IllegalArgumentException("The " + getClass().getSimpleName()
+ "'s incrementUnitAmount (" + incrementUnitAmount
+ ") must fit an integer number of times in the space (" + space
+ ") between from (" + from + ") and to (" + to + ").");
}
size = space / incrementUnitAmount;
}
@Override
public long getSize() {
return size;
}
@Override
public Temporal_ get(long index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException();
}
return (Temporal_) from.plus(index * incrementUnitAmount, incrementUnitType);
}
@Override
public boolean contains(Temporal_ value) {
if (value == null || !value.isSupported(incrementUnitType)) {
return false;
}
// We cannot use Temporal.until() to check bounds due to rounding errors
if (value.compareTo(from) < 0 || value.compareTo(to) >= 0) {
return false;
}
long fromSpace = from.until(value, incrementUnitType);
if (value.equals(from.plus(fromSpace + 1, incrementUnitType))) {
// Temporal.until() rounds down, but it needs to round up, to be consistent with Temporal.plus()
fromSpace++;
}
// Only checking the modulus is not enough: 1-MAR + 1 month doesn't include 7-MAR but the modulus is 0 anyway
return fromSpace % incrementUnitAmount == 0
&& value.equals(from.plus(fromSpace, incrementUnitType));
}
@Override
public Iterator<Temporal_> createOriginalIterator() {
return new OriginalTemporalValueRangeIterator();
}
private class OriginalTemporalValueRangeIterator extends ValueRangeIterator<Temporal_> {
private long index = 0L;
@Override
public boolean hasNext() {
return index < size;
}
@Override
public Temporal_ next() {
if (index >= size) {
throw new NoSuchElementException();
}
// Do not use upcoming += incrementUnitAmount because 31-JAN + 1 month + 1 month returns 28-MAR
Temporal_ next = get(index);
index++;
return next;
}
}
@Override
public Iterator<Temporal_> createRandomIterator(Random workingRandom) {
return new RandomTemporalValueRangeIterator(workingRandom);
}
private class RandomTemporalValueRangeIterator extends ValueRangeIterator<Temporal_> {
private final Random workingRandom;
public RandomTemporalValueRangeIterator(Random workingRandom) {
this.workingRandom = workingRandom;
}
@Override
public boolean hasNext() {
return size > 0L;
}
@Override
public Temporal_ next() {
long index = RandomUtils.nextLong(workingRandom, size);
return get(index);
}
}
@Override
public String toString() {
return "[" + from + "-" + to + ")"; // Formatting: interval (mathematics) ISO 31-11
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/descriptor/AbstractFromPropertyValueRangeDescriptor.java | package ai.timefold.solver.core.impl.domain.valuerange.descriptor;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.common.ReflectionHelper;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.valuerange.buildin.collection.ListValueRange;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class AbstractFromPropertyValueRangeDescriptor<Solution_>
extends AbstractValueRangeDescriptor<Solution_> {
protected final MemberAccessor memberAccessor;
protected boolean collectionWrapping;
protected boolean arrayWrapping;
protected boolean countable;
public AbstractFromPropertyValueRangeDescriptor(GenuineVariableDescriptor<Solution_> variableDescriptor,
boolean addNullInValueRange,
MemberAccessor memberAccessor) {
super(variableDescriptor, addNullInValueRange);
this.memberAccessor = memberAccessor;
ValueRangeProvider valueRangeProviderAnnotation = memberAccessor.getAnnotation(ValueRangeProvider.class);
if (valueRangeProviderAnnotation == null) {
throw new IllegalStateException("The member (" + memberAccessor
+ ") must have a valueRangeProviderAnnotation (" + valueRangeProviderAnnotation + ").");
}
processValueRangeProviderAnnotation(valueRangeProviderAnnotation);
if (addNullInValueRange && !countable) {
throw new IllegalStateException("""
The valueRangeDescriptor (%s) allows unassigned values, but not countable (%s).
Maybe the member (%s) should return %s."""
.formatted(this, countable, memberAccessor, CountableValueRange.class.getSimpleName()));
}
}
private void processValueRangeProviderAnnotation(ValueRangeProvider valueRangeProviderAnnotation) {
EntityDescriptor<Solution_> entityDescriptor = variableDescriptor.getEntityDescriptor();
Class<?> type = memberAccessor.getType();
collectionWrapping = Collection.class.isAssignableFrom(type);
arrayWrapping = type.isArray();
if (!collectionWrapping && !arrayWrapping && !ValueRange.class.isAssignableFrom(type)) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + PlanningVariable.class.getSimpleName()
+ " annotated property (" + variableDescriptor.getVariableName()
+ ") that refers to a @" + ValueRangeProvider.class.getSimpleName()
+ " annotated member (" + memberAccessor
+ ") that does not return a " + Collection.class.getSimpleName()
+ ", an array or a " + ValueRange.class.getSimpleName() + ".");
}
if (collectionWrapping) {
Class<?> collectionElementClass = ConfigUtils.extractCollectionGenericTypeParameterStrictly(
"solutionClass or entityClass", memberAccessor.getDeclaringClass(),
memberAccessor.getType(), memberAccessor.getGenericType(),
ValueRangeProvider.class, memberAccessor.getName());
if (!variableDescriptor.acceptsValueType(collectionElementClass)) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + PlanningVariable.class.getSimpleName()
+ " annotated property (" + variableDescriptor.getVariableName()
+ ") that refers to a @" + ValueRangeProvider.class.getSimpleName()
+ " annotated member (" + memberAccessor
+ ") that returns a " + Collection.class.getSimpleName()
+ " with elements of type (" + collectionElementClass
+ ") which cannot be assigned to the @" + PlanningVariable.class.getSimpleName()
+ "'s type (" + variableDescriptor.getVariablePropertyType() + ").");
}
} else if (arrayWrapping) {
Class<?> arrayElementClass = type.getComponentType();
if (!variableDescriptor.acceptsValueType(arrayElementClass)) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + PlanningVariable.class.getSimpleName()
+ " annotated property (" + variableDescriptor.getVariableName()
+ ") that refers to a @" + ValueRangeProvider.class.getSimpleName()
+ " annotated member (" + memberAccessor
+ ") that returns an array with elements of type (" + arrayElementClass
+ ") which cannot be assigned to the @" + PlanningVariable.class.getSimpleName()
+ "'s type (" + variableDescriptor.getVariablePropertyType() + ").");
}
}
countable = collectionWrapping || arrayWrapping || CountableValueRange.class.isAssignableFrom(type);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
return countable;
}
protected ValueRange<?> readValueRange(Object bean) {
Object valueRangeObject = memberAccessor.executeGetter(bean);
if (valueRangeObject == null) {
throw new IllegalStateException("The @" + ValueRangeProvider.class.getSimpleName()
+ " annotated member (" + memberAccessor
+ ") called on bean (" + bean
+ ") must not return a null valueRangeObject (" + valueRangeObject + ").");
}
ValueRange<Object> valueRange;
if (collectionWrapping || arrayWrapping) {
List<Object> list = collectionWrapping ? transformCollectionToList((Collection<Object>) valueRangeObject)
: ReflectionHelper.transformArrayToList(valueRangeObject);
// Don't check the entire list for performance reasons, but do check common pitfalls
if (!list.isEmpty() && (list.get(0) == null || list.get(list.size() - 1) == null)) {
throw new IllegalStateException(
"""
The @%s-annotated member (%s) called on bean (%s) must not return a %s (%s) with an element that is null.
Maybe remove that null element from the dataset.
Maybe use @%s(allowsUnassigned = true) instead."""
.formatted(ValueRangeProvider.class.getSimpleName(),
memberAccessor, bean,
collectionWrapping ? Collection.class.getSimpleName() : "array",
list,
PlanningVariable.class.getSimpleName()));
}
valueRange = new ListValueRange<>(list);
} else {
valueRange = (ValueRange<Object>) valueRangeObject;
}
valueRange = doNullInValueRangeWrapping(valueRange);
if (valueRange.isEmpty()) {
throw new IllegalStateException("The @" + ValueRangeProvider.class.getSimpleName()
+ " annotated member (" + memberAccessor
+ ") called on bean (" + bean
+ ") must not return an empty valueRange (" + valueRangeObject + ").\n"
+ "Maybe apply overconstrained planning as described in the documentation.");
}
return valueRange;
}
protected long readValueRangeSize(Object bean) {
Object valueRangeObject = memberAccessor.executeGetter(bean);
if (valueRangeObject == null) {
throw new IllegalStateException("The @" + ValueRangeProvider.class.getSimpleName()
+ " annotated member (" + memberAccessor
+ ") called on bean (" + bean
+ ") must not return a null valueRangeObject (" + valueRangeObject + ").");
}
long size = addNullInValueRange ? 1 : 0;
if (collectionWrapping) {
return size + ((Collection<Object>) valueRangeObject).size();
} else if (arrayWrapping) {
return size + Array.getLength(valueRangeObject);
}
ValueRange<Object> valueRange = (ValueRange<Object>) valueRangeObject;
if (valueRange.isEmpty()) {
throw new IllegalStateException("The @" + ValueRangeProvider.class.getSimpleName()
+ " annotated member (" + memberAccessor
+ ") called on bean (" + bean
+ ") must not return an empty valueRange (" + valueRangeObject + ").\n"
+ "Maybe apply overconstrained planning as described in the documentation.");
} else if (valueRange instanceof CountableValueRange<Object> countableValueRange) {
return size + countableValueRange.getSize();
} else {
throw new UnsupportedOperationException("The @" + ValueRangeProvider.class.getSimpleName()
+ " annotated member (" + memberAccessor
+ ") called on bean (" + bean
+ ") is not countable and therefore does not support getSize().");
}
}
private <T> List<T> transformCollectionToList(Collection<T> collection) {
if (collection instanceof List<T> list) {
if (collection instanceof LinkedList<T> linkedList) {
// ValueRange.createRandomIterator(Random) and ValueRange.get(int) wouldn't be efficient.
return new ArrayList<>(linkedList);
} else {
return list;
}
} else {
// TODO If only ValueRange.createOriginalIterator() is used, cloning a Set to a List is a waste of time.
return new ArrayList<>(collection);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/descriptor/AbstractValueRangeDescriptor.java | package ai.timefold.solver.core.impl.domain.valuerange.descriptor;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
import ai.timefold.solver.core.impl.domain.valuerange.buildin.composite.NullAllowingCountableValueRange;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public abstract class AbstractValueRangeDescriptor<Solution_> implements ValueRangeDescriptor<Solution_> {
protected final GenuineVariableDescriptor<Solution_> variableDescriptor;
protected final boolean addNullInValueRange;
public AbstractValueRangeDescriptor(GenuineVariableDescriptor<Solution_> variableDescriptor,
boolean addNullInValueRange) {
this.variableDescriptor = variableDescriptor;
this.addNullInValueRange = addNullInValueRange;
}
@Override
public GenuineVariableDescriptor<Solution_> getVariableDescriptor() {
return variableDescriptor;
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean mightContainEntity() {
SolutionDescriptor<Solution_> solutionDescriptor = variableDescriptor.getEntityDescriptor().getSolutionDescriptor();
Class<?> variablePropertyType = variableDescriptor.getVariablePropertyType();
for (Class<?> entityClass : solutionDescriptor.getEntityClassSet()) {
if (variablePropertyType.isAssignableFrom(entityClass)) {
return true;
}
}
return false;
}
protected <T> ValueRange<T> doNullInValueRangeWrapping(ValueRange<T> valueRange) {
if (addNullInValueRange) {
valueRange = new NullAllowingCountableValueRange<>((CountableValueRange) valueRange);
}
return valueRange;
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + variableDescriptor.getVariableName() + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/descriptor/CompositeValueRangeDescriptor.java | package ai.timefold.solver.core.impl.domain.valuerange.descriptor;
import java.util.ArrayList;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.impl.domain.valuerange.buildin.composite.CompositeCountableValueRange;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class CompositeValueRangeDescriptor<Solution_> extends AbstractValueRangeDescriptor<Solution_>
implements EntityIndependentValueRangeDescriptor<Solution_> {
protected final List<ValueRangeDescriptor<Solution_>> childValueRangeDescriptorList;
protected boolean entityIndependent;
public CompositeValueRangeDescriptor(
GenuineVariableDescriptor<Solution_> variableDescriptor, boolean addNullInValueRange,
List<ValueRangeDescriptor<Solution_>> childValueRangeDescriptorList) {
super(variableDescriptor, addNullInValueRange);
this.childValueRangeDescriptorList = childValueRangeDescriptorList;
entityIndependent = true;
for (ValueRangeDescriptor<Solution_> valueRangeDescriptor : childValueRangeDescriptorList) {
if (!valueRangeDescriptor.isCountable()) {
throw new IllegalStateException("The valueRangeDescriptor (" + this
+ ") has a childValueRangeDescriptor (" + valueRangeDescriptor
+ ") with countable (" + valueRangeDescriptor.isCountable() + ").");
}
if (!valueRangeDescriptor.isEntityIndependent()) {
entityIndependent = false;
}
}
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isCountable() {
return true;
}
@Override
public boolean isEntityIndependent() {
return entityIndependent;
}
@Override
public ValueRange<?> extractValueRange(Solution_ solution, Object entity) {
List<CountableValueRange<?>> childValueRangeList = new ArrayList<>(childValueRangeDescriptorList.size());
for (ValueRangeDescriptor<Solution_> valueRangeDescriptor : childValueRangeDescriptorList) {
childValueRangeList.add((CountableValueRange) valueRangeDescriptor.extractValueRange(solution, entity));
}
return doNullInValueRangeWrapping(new CompositeCountableValueRange(childValueRangeList));
}
@Override
public ValueRange<?> extractValueRange(Solution_ solution) {
List<CountableValueRange<?>> childValueRangeList = new ArrayList<>(childValueRangeDescriptorList.size());
for (ValueRangeDescriptor<Solution_> valueRangeDescriptor : childValueRangeDescriptorList) {
EntityIndependentValueRangeDescriptor<Solution_> entityIndependentValueRangeDescriptor =
(EntityIndependentValueRangeDescriptor) valueRangeDescriptor;
childValueRangeList.add((CountableValueRange) entityIndependentValueRangeDescriptor.extractValueRange(solution));
}
return doNullInValueRangeWrapping(new CompositeCountableValueRange(childValueRangeList));
}
@Override
public long extractValueRangeSize(Solution_ solution, Object entity) {
int size = addNullInValueRange ? 1 : 0;
for (ValueRangeDescriptor<Solution_> valueRangeDescriptor : childValueRangeDescriptorList) {
size += ((CountableValueRange) valueRangeDescriptor.extractValueRange(solution, entity)).getSize();
}
return size;
}
@Override
public long extractValueRangeSize(Solution_ solution) {
int size = addNullInValueRange ? 1 : 0;
for (ValueRangeDescriptor<Solution_> valueRangeDescriptor : childValueRangeDescriptorList) {
EntityIndependentValueRangeDescriptor<Solution_> entityIndependentValueRangeDescriptor =
(EntityIndependentValueRangeDescriptor) valueRangeDescriptor;
size += ((CountableValueRange) entityIndependentValueRangeDescriptor.extractValueRange(solution)).getSize();
}
return size;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/descriptor/EntityIndependentValueRangeDescriptor.java | package ai.timefold.solver.core.impl.domain.valuerange.descriptor;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public interface EntityIndependentValueRangeDescriptor<Solution_> extends ValueRangeDescriptor<Solution_> {
/**
* As specified by {@link ValueRangeDescriptor#extractValueRange}.
*
* @param solution never null
* @return never null
* @see ValueRangeDescriptor#extractValueRange
*/
ValueRange<?> extractValueRange(Solution_ solution);
/**
* As specified by {@link ValueRangeDescriptor#extractValueRangeSize}.
*
* @param solution never null
* @return never null
* @see ValueRangeDescriptor#extractValueRangeSize
*/
long extractValueRangeSize(Solution_ solution);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/descriptor/FromEntityPropertyValueRangeDescriptor.java | package ai.timefold.solver.core.impl.domain.valuerange.descriptor;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class FromEntityPropertyValueRangeDescriptor<Solution_>
extends AbstractFromPropertyValueRangeDescriptor<Solution_> {
public FromEntityPropertyValueRangeDescriptor(GenuineVariableDescriptor<Solution_> variableDescriptor,
boolean addNullInValueRange, MemberAccessor memberAccessor) {
super(variableDescriptor, addNullInValueRange, memberAccessor);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isEntityIndependent() {
return false;
}
@Override
public ValueRange<?> extractValueRange(Solution_ solution, Object entity) {
return readValueRange(entity);
}
@Override
public long extractValueRangeSize(Solution_ solution, Object entity) {
return readValueRangeSize(entity);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/descriptor/FromSolutionPropertyValueRangeDescriptor.java | package ai.timefold.solver.core.impl.domain.valuerange.descriptor;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class FromSolutionPropertyValueRangeDescriptor<Solution_>
extends AbstractFromPropertyValueRangeDescriptor<Solution_>
implements EntityIndependentValueRangeDescriptor<Solution_> {
public FromSolutionPropertyValueRangeDescriptor(
GenuineVariableDescriptor<Solution_> variableDescriptor, boolean addNullInValueRange,
MemberAccessor memberAccessor) {
super(variableDescriptor, addNullInValueRange, memberAccessor);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public boolean isEntityIndependent() {
return true;
}
@Override
public ValueRange<?> extractValueRange(Solution_ solution, Object entity) {
return readValueRange(solution);
}
@Override
public long extractValueRangeSize(Solution_ solution, Object entity) {
return readValueRangeSize(solution);
}
@Override
public ValueRange<?> extractValueRange(Solution_ solution) {
return readValueRange(solution);
}
@Override
public long extractValueRangeSize(Solution_ solution) {
return readValueRangeSize(solution);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/valuerange/descriptor/ValueRangeDescriptor.java | package ai.timefold.solver.core.impl.domain.valuerange.descriptor;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.valuerange.ValueRange;
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public interface ValueRangeDescriptor<Solution_> {
/**
* @return never null
*/
GenuineVariableDescriptor<Solution_> getVariableDescriptor();
/**
* @return true if the {@link ValueRange} is countable
* (for example a double value range between 1.2 and 1.4 is not countable)
*/
boolean isCountable();
/**
* If this method return true, this instance is safe to cast to {@link EntityIndependentValueRangeDescriptor},
* otherwise it requires an entity to determine the {@link ValueRange}.
*
* @return true if the {@link ValueRange} is the same for all entities of the same solution
*/
boolean isEntityIndependent();
/**
* @return true if the {@link ValueRange} might contain a planning entity instance
* (not necessarily of the same entity class as this entity class of this descriptor.
*/
boolean mightContainEntity();
/**
* @param solution never null
* @param entity never null. To avoid this parameter,
* use {@link EntityIndependentValueRangeDescriptor#extractValueRange} instead.
* @return never null
*/
ValueRange<?> extractValueRange(Solution_ solution, Object entity);
/**
* @param solution never null
* @param entity never null. To avoid this parameter,
* use {@link EntityIndependentValueRangeDescriptor#extractValueRangeSize} instead.
* @return never null
* @throws UnsupportedOperationException if {@link #isCountable()} returns false
*/
long extractValueRangeSize(Solution_ solution, Object entity);
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/ExternalizedListVariableStateSupply.java | package ai.timefold.solver.core.impl.domain.variable;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Objects;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.heuristic.selector.list.ElementLocation;
import ai.timefold.solver.core.impl.heuristic.selector.list.LocationInList;
final class ExternalizedListVariableStateSupply<Solution_>
implements ListVariableStateSupply<Solution_> {
private final ListVariableDescriptor<Solution_> sourceVariableDescriptor;
private Map<Object, LocationInList> elementLocationMap;
private int unassignedCount;
public ExternalizedListVariableStateSupply(ListVariableDescriptor<Solution_> sourceVariableDescriptor) {
this.sourceVariableDescriptor = sourceVariableDescriptor;
}
@Override
public void resetWorkingSolution(ScoreDirector<Solution_> scoreDirector) {
var workingSolution = scoreDirector.getWorkingSolution();
if (elementLocationMap == null) {
elementLocationMap = new IdentityHashMap<>((int) sourceVariableDescriptor.getValueRangeSize(workingSolution, null));
} else {
elementLocationMap.clear();
}
// Start with everything unassigned.
unassignedCount = (int) sourceVariableDescriptor.getValueRangeSize(workingSolution, null);
// Will run over all entities and unmark all present elements as unassigned.
sourceVariableDescriptor.getEntityDescriptor().visitAllEntities(workingSolution, this::insert);
}
private void insert(Object entity) {
var assignedElements = sourceVariableDescriptor.getValue(entity);
var index = 0;
for (var element : assignedElements) {
var oldLocation = elementLocationMap.put(element, new LocationInList(entity, index));
if (oldLocation != null) {
throw new IllegalStateException(
"The supply (%s) is corrupted, because the element (%s) at index (%d) already exists (%s)."
.formatted(this, element, index, oldLocation));
}
index++;
unassignedCount--;
}
}
@Override
public void close() {
elementLocationMap = null;
}
@Override
public void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Object o) {
// No need to do anything.
}
@Override
public void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Object o) {
insert(o);
}
@Override
public void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object o) {
// No need to do anything.
}
@Override
public void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object o) {
// When the entity is removed, its values become unassigned.
// An unassigned value has no inverse entity and no index.
retract(o);
}
private void retract(Object entity) {
var assignedElements = sourceVariableDescriptor.getValue(entity);
for (var index = 0; index < assignedElements.size(); index++) {
var element = assignedElements.get(index);
var oldElementLocation = elementLocationMap.remove(element);
if (oldElementLocation == null) {
throw new IllegalStateException(
"The supply (%s) is corrupted, because the element (%s) at index (%d) was already unassigned (%s)."
.formatted(this, element, index, oldElementLocation));
}
var oldIndex = oldElementLocation.index();
if (oldIndex != index) {
throw new IllegalStateException(
"The supply (%s) is corrupted, because the element (%s) at index (%d) had an old index (%d) which is not the current index (%d)."
.formatted(this, element, index, oldIndex, index));
}
unassignedCount++;
}
}
@Override
public void afterListVariableElementUnassigned(ScoreDirector<Solution_> scoreDirector, Object element) {
var oldLocation = elementLocationMap.remove(element);
if (oldLocation == null) {
throw new IllegalStateException(
"The supply (%s) is corrupted, because the element (%s) did not exist before unassigning."
.formatted(this, element));
}
unassignedCount++;
}
@Override
public void beforeListVariableChanged(ScoreDirector<Solution_> scoreDirector, Object o, int fromIndex, int toIndex) {
// No need to do anything.
}
@Override
public void afterListVariableChanged(ScoreDirector<Solution_> scoreDirector, Object o, int fromIndex, int toIndex) {
updateIndexes(o, fromIndex, toIndex);
}
private void updateIndexes(Object entity, int startIndex, int toIndex) {
var assignedElements = sourceVariableDescriptor.getValue(entity);
for (var index = startIndex; index < assignedElements.size(); index++) {
var element = assignedElements.get(index);
var newLocation = new LocationInList(entity, index);
var oldLocation = elementLocationMap.put(element, newLocation);
if (oldLocation == null) {
unassignedCount--;
} else if (index >= toIndex && newLocation.equals(oldLocation)) {
// Location is unchanged and we are past the part of the list that changed.
return;
} else {
// Continue to the next element.
}
}
}
@Override
public ElementLocation getLocationInList(Object planningValue) {
return Objects.requireNonNullElse(elementLocationMap.get(Objects.requireNonNull(planningValue)),
ElementLocation.unassigned());
}
@Override
public Integer getIndex(Object planningValue) {
var elementLocation = elementLocationMap.get(Objects.requireNonNull(planningValue));
if (elementLocation == null) {
return null;
}
return elementLocation.index();
}
@Override
public Object getInverseSingleton(Object planningValue) {
var elementLocation = elementLocationMap.get(Objects.requireNonNull(planningValue));
if (elementLocation == null) {
return null;
}
return elementLocation.entity();
}
@Override
public boolean isAssigned(Object element) {
return getLocationInList(element) instanceof LocationInList;
}
@Override
public int getUnassignedCount() {
return unassignedCount;
}
@Override
public ListVariableDescriptor<Solution_> getSourceVariableDescriptor() {
return sourceVariableDescriptor;
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + sourceVariableDescriptor.getVariableName() + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/ListVariableElementStateSupply.java | package ai.timefold.solver.core.impl.domain.variable;
import ai.timefold.solver.core.api.domain.variable.ListVariableListener;
import ai.timefold.solver.core.impl.domain.variable.listener.SourcedVariableListener;
import ai.timefold.solver.core.impl.heuristic.selector.list.ElementLocation;
public interface ListVariableElementStateSupply<Solution_> extends
SourcedVariableListener<Solution_>,
ListVariableListener<Solution_, Object, Object> {
/**
*
* @param element never null
* @return true if the element is contained in a list variable of any entity.
*/
boolean isAssigned(Object element);
/**
*
* @param value never null
* @return never null
*/
ElementLocation getLocationInList(Object value);
/**
* Consider colling this before {@link #isAssigned(Object)} to eliminate some map accesses.
* If unassigned count is 0, {@link #isAssigned(Object)} is guaranteed to return true.
*
* @return number of elements for which {@link #isAssigned(Object)} would return false.
*/
int getUnassignedCount();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/ListVariableStateSupply.java | package ai.timefold.solver.core.impl.domain.variable;
import ai.timefold.solver.core.api.domain.variable.ListVariableListener;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.index.IndexVariableSupply;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import ai.timefold.solver.core.impl.domain.variable.listener.SourcedVariableListener;
public interface ListVariableStateSupply<Solution_> extends
SourcedVariableListener<Solution_>,
ListVariableListener<Solution_, Object, Object>,
SingletonInverseVariableSupply,
IndexVariableSupply,
ListVariableElementStateSupply<Solution_> {
@Override
ListVariableDescriptor<Solution_> getSourceVariableDescriptor();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/anchor/AnchorShadowVariableDescriptor.java | package ai.timefold.solver.core.impl.domain.variable.anchor;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener;
import ai.timefold.solver.core.api.domain.variable.AnchorShadowVariable;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy;
import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableDemand;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import ai.timefold.solver.core.impl.domain.variable.listener.VariableListenerWithSources;
import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public final class AnchorShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> {
private VariableDescriptor<Solution_> sourceVariableDescriptor;
public AnchorShadowVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor,
MemberAccessor variableMemberAccessor) {
super(ordinal, entityDescriptor, variableMemberAccessor);
}
@Override
public void processAnnotations(DescriptorPolicy descriptorPolicy) {
// Do nothing
}
@Override
public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) {
linkShadowSources(descriptorPolicy);
}
private void linkShadowSources(DescriptorPolicy descriptorPolicy) {
AnchorShadowVariable shadowVariableAnnotation = variableMemberAccessor.getAnnotation(AnchorShadowVariable.class);
String sourceVariableName = shadowVariableAnnotation.sourceVariableName();
sourceVariableDescriptor = entityDescriptor.getVariableDescriptor(sourceVariableName);
if (sourceVariableDescriptor == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has an @" + AnchorShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with sourceVariableName (" + sourceVariableName
+ ") which is not a valid planning variable on entityClass ("
+ entityDescriptor.getEntityClass() + ").\n"
+ entityDescriptor.buildInvalidVariableNameExceptionMessage(sourceVariableName));
}
if (!(sourceVariableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor) ||
!basicVariableDescriptor.isChained()) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has an @" + AnchorShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with sourceVariableName (" + sourceVariableName
+ ") which is not chained.");
}
sourceVariableDescriptor.registerSinkVariableDescriptor(this);
}
@Override
public List<VariableDescriptor<Solution_>> getSourceVariableDescriptorList() {
return Collections.singletonList(sourceVariableDescriptor);
}
@Override
public Collection<Class<? extends AbstractVariableListener>> getVariableListenerClasses() {
return Collections.singleton(AnchorVariableListener.class);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public AnchorVariableDemand<Solution_> getProvidedDemand() {
return new AnchorVariableDemand<>(sourceVariableDescriptor);
}
@Override
public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) {
SingletonInverseVariableSupply inverseVariableSupply = supplyManager
.demand(new SingletonInverseVariableDemand<>(sourceVariableDescriptor));
return new VariableListenerWithSources<>(
new AnchorVariableListener<>(this, sourceVariableDescriptor, inverseVariableSupply),
sourceVariableDescriptor).toCollection();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/anchor/AnchorVariableListener.java | package ai.timefold.solver.core.impl.domain.variable.anchor;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.variable.VariableListener;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class AnchorVariableListener<Solution_> implements VariableListener<Solution_, Object>, AnchorVariableSupply {
protected final AnchorShadowVariableDescriptor<Solution_> anchorShadowVariableDescriptor;
protected final VariableDescriptor<Solution_> previousVariableDescriptor;
protected final SingletonInverseVariableSupply nextVariableSupply;
public AnchorVariableListener(AnchorShadowVariableDescriptor<Solution_> anchorShadowVariableDescriptor,
VariableDescriptor<Solution_> previousVariableDescriptor,
SingletonInverseVariableSupply nextVariableSupply) {
this.anchorShadowVariableDescriptor = anchorShadowVariableDescriptor;
this.previousVariableDescriptor = previousVariableDescriptor;
this.nextVariableSupply = nextVariableSupply;
}
@Override
public void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) {
// Do nothing
}
@Override
public void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) {
insert((InnerScoreDirector<Solution_, ?>) scoreDirector, entity);
}
@Override
public void beforeVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) {
// No need to retract() because the insert (which is guaranteed to be called later) affects the same trailing entities.
}
@Override
public void afterVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) {
insert((InnerScoreDirector<Solution_, ?>) scoreDirector, entity);
}
@Override
public void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) {
// No need to retract() because the trailing entities will be removed too or change their previousVariable
}
@Override
public void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) {
// Do nothing
}
protected void insert(InnerScoreDirector<Solution_, ?> scoreDirector, Object entity) {
Object previousEntity = previousVariableDescriptor.getValue(entity);
Object anchor;
if (previousEntity == null) {
anchor = null;
} else if (previousVariableDescriptor.isValuePotentialAnchor(previousEntity)) {
anchor = previousEntity;
} else {
anchor = anchorShadowVariableDescriptor.getValue(previousEntity);
}
Object nextEntity = entity;
while (nextEntity != null && anchorShadowVariableDescriptor.getValue(nextEntity) != anchor) {
scoreDirector.beforeVariableChanged(anchorShadowVariableDescriptor, nextEntity);
anchorShadowVariableDescriptor.setValue(nextEntity, anchor);
scoreDirector.afterVariableChanged(anchorShadowVariableDescriptor, nextEntity);
nextEntity = nextVariableSupply.getInverseSingleton(nextEntity);
}
}
@Override
public Object getAnchor(Object entity) {
return anchorShadowVariableDescriptor.getValue(entity);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/anchor/ExternalizedAnchorVariableSupply.java | package ai.timefold.solver.core.impl.domain.variable.anchor;
import java.util.IdentityHashMap;
import java.util.Map;
import ai.timefold.solver.core.api.domain.variable.VariableListener;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import ai.timefold.solver.core.impl.domain.variable.listener.SourcedVariableListener;
/**
* Alternative to {@link AnchorVariableListener}.
*/
public class ExternalizedAnchorVariableSupply<Solution_> implements
SourcedVariableListener<Solution_>,
VariableListener<Solution_, Object>,
AnchorVariableSupply {
protected final VariableDescriptor<Solution_> previousVariableDescriptor;
protected final SingletonInverseVariableSupply nextVariableSupply;
protected Map<Object, Object> anchorMap = null;
public ExternalizedAnchorVariableSupply(VariableDescriptor<Solution_> previousVariableDescriptor,
SingletonInverseVariableSupply nextVariableSupply) {
this.previousVariableDescriptor = previousVariableDescriptor;
this.nextVariableSupply = nextVariableSupply;
}
@Override
public VariableDescriptor<Solution_> getSourceVariableDescriptor() {
return previousVariableDescriptor;
}
@Override
public void resetWorkingSolution(ScoreDirector<Solution_> scoreDirector) {
anchorMap = new IdentityHashMap<>();
previousVariableDescriptor.getEntityDescriptor().visitAllEntities(scoreDirector.getWorkingSolution(), this::insert);
}
@Override
public void close() {
anchorMap = null;
}
@Override
public void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) {
// Do nothing
}
@Override
public void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) {
insert(entity);
}
@Override
public void beforeVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) {
// No need to retract() because the insert (which is guaranteed to be called later) affects the same trailing entities.
}
@Override
public void afterVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) {
insert(entity);
}
@Override
public void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) {
boolean removeSucceeded = anchorMap.remove(entity) != null;
if (!removeSucceeded) {
throw new IllegalStateException("The supply (" + this + ") is corrupted,"
+ " because the entity (" + entity
+ ") for sourceVariable (" + previousVariableDescriptor.getVariableName()
+ ") cannot be retracted: it was never inserted.");
}
// No need to retract the trailing entities because they will be removed too or change their previousVariable
}
@Override
public void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) {
// Do nothing
}
protected void insert(Object entity) {
Object previousEntity = previousVariableDescriptor.getValue(entity);
Object anchor;
if (previousEntity == null) {
anchor = null;
} else if (previousVariableDescriptor.isValuePotentialAnchor(previousEntity)) {
anchor = previousEntity;
} else {
anchor = anchorMap.get(previousEntity);
}
Object nextEntity = entity;
while (nextEntity != null && anchorMap.get(nextEntity) != anchor) {
anchorMap.put(nextEntity, anchor);
nextEntity = nextVariableSupply.getInverseSingleton(nextEntity);
}
}
@Override
public Object getAnchor(Object entity) {
return anchorMap.get(entity);
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + previousVariableDescriptor.getVariableName() + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/custom/CustomShadowVariableDescriptor.java | package ai.timefold.solver.core.impl.domain.variable.custom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener;
import ai.timefold.solver.core.api.domain.variable.ListVariableListener;
import ai.timefold.solver.core.api.domain.variable.ShadowVariable;
import ai.timefold.solver.core.api.domain.variable.VariableListener;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.listener.VariableListenerWithSources;
import ai.timefold.solver.core.impl.domain.variable.supply.Demand;
import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public final class CustomShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> {
private final Map<Class<? extends AbstractVariableListener>, List<VariableDescriptor<Solution_>>> listenerClassToSourceDescriptorListMap =
new HashMap<>();
public CustomShadowVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor,
MemberAccessor variableMemberAccessor) {
super(ordinal, entityDescriptor, variableMemberAccessor);
}
@Override
public void processAnnotations(DescriptorPolicy descriptorPolicy) {
// Do nothing
}
@Override
public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) {
for (ShadowVariable shadowVariable : variableMemberAccessor.getDeclaredAnnotationsByType(ShadowVariable.class)) {
linkSourceVariableDescriptorToListenerClass(shadowVariable);
}
}
private void linkSourceVariableDescriptorToListenerClass(ShadowVariable shadowVariable) {
EntityDescriptor<Solution_> sourceEntityDescriptor;
Class<?> sourceEntityClass = shadowVariable.sourceEntityClass();
if (sourceEntityClass.equals(ShadowVariable.NullEntityClass.class)) {
sourceEntityDescriptor = entityDescriptor;
} else {
sourceEntityDescriptor = entityDescriptor.getSolutionDescriptor().findEntityDescriptor(sourceEntityClass);
if (sourceEntityDescriptor == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + ShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with a sourceEntityClass (" + sourceEntityClass
+ ") which is not a valid planning entity."
+ "\nMaybe check the annotations of the class (" + sourceEntityClass + ")."
+ "\nMaybe add the class (" + sourceEntityClass
+ ") among planning entities in the solver configuration.");
}
}
String sourceVariableName = shadowVariable.sourceVariableName();
VariableDescriptor<Solution_> sourceVariableDescriptor =
sourceEntityDescriptor.getVariableDescriptor(sourceVariableName);
if (sourceVariableDescriptor == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + ShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with sourceVariableName (" + sourceVariableName
+ ") which is not a valid planning variable on entityClass ("
+ sourceEntityDescriptor.getEntityClass() + ").\n"
+ sourceEntityDescriptor.buildInvalidVariableNameExceptionMessage(sourceVariableName));
}
Class<? extends AbstractVariableListener> variableListenerClass = shadowVariable.variableListenerClass();
if (sourceVariableDescriptor.isListVariable()
&& !ListVariableListener.class.isAssignableFrom(variableListenerClass)) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + ShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with sourceVariable (" + sourceVariableDescriptor.getSimpleEntityAndVariableName()
+ ") which is a list variable but the variableListenerClass (" + variableListenerClass
+ ") is not a " + ListVariableListener.class.getSimpleName() + ".\n"
+ "Maybe make the variableListenerClass (" + variableListenerClass.getSimpleName()
+ ") implement " + ListVariableListener.class.getSimpleName() + ".");
}
if (!sourceVariableDescriptor.isListVariable()
&& !VariableListener.class.isAssignableFrom(variableListenerClass)) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + ShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with sourceVariable (" + sourceVariableDescriptor.getSimpleEntityAndVariableName()
+ ") which is a basic variable but the variableListenerClass (" + variableListenerClass
+ ") is not a " + VariableListener.class.getSimpleName() + ".\n"
+ "Maybe make the variableListenerClass (" + variableListenerClass.getSimpleName()
+ ") implement " + VariableListener.class.getSimpleName() + ".");
}
sourceVariableDescriptor.registerSinkVariableDescriptor(this);
listenerClassToSourceDescriptorListMap
.computeIfAbsent(variableListenerClass, k -> new ArrayList<>())
.add(sourceVariableDescriptor);
}
@Override
public List<VariableDescriptor<Solution_>> getSourceVariableDescriptorList() {
return listenerClassToSourceDescriptorListMap.values().stream()
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
}
@Override
public Collection<Class<? extends AbstractVariableListener>> getVariableListenerClasses() {
return listenerClassToSourceDescriptorListMap.keySet();
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Demand<?> getProvidedDemand() {
throw new UnsupportedOperationException("Custom shadow variable cannot be demanded.");
}
@Override
public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) {
return listenerClassToSourceDescriptorListMap.entrySet().stream().map(classListEntry -> {
AbstractVariableListener<Solution_, Object> variableListener =
ConfigUtils.newInstance(this::toString, "variableListenerClass", classListEntry.getKey());
return new VariableListenerWithSources<>(variableListener, classListEntry.getValue());
}).collect(Collectors.toList());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/custom/LegacyCustomShadowVariableDescriptor.java | package ai.timefold.solver.core.impl.domain.variable.custom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener;
import ai.timefold.solver.core.api.domain.variable.CustomShadowVariable;
import ai.timefold.solver.core.api.domain.variable.PlanningVariableReference;
import ai.timefold.solver.core.api.domain.variable.VariableListener;
import ai.timefold.solver.core.config.util.ConfigUtils;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.listener.VariableListenerWithSources;
import ai.timefold.solver.core.impl.domain.variable.supply.Demand;
import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public final class LegacyCustomShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> {
private LegacyCustomShadowVariableDescriptor<Solution_> refVariableDescriptor;
private Class<? extends VariableListener> variableListenerClass;
private List<VariableDescriptor<Solution_>> sourceVariableDescriptorList;
public LegacyCustomShadowVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor,
MemberAccessor variableMemberAccessor) {
super(ordinal, entityDescriptor, variableMemberAccessor);
}
@Override
public void processAnnotations(DescriptorPolicy descriptorPolicy) {
processPropertyAnnotations(descriptorPolicy);
}
private void processPropertyAnnotations(DescriptorPolicy descriptorPolicy) {
CustomShadowVariable shadowVariableAnnotation = variableMemberAccessor
.getAnnotation(CustomShadowVariable.class);
PlanningVariableReference variableListenerRef = shadowVariableAnnotation.variableListenerRef();
if (variableListenerRef.variableName().equals("")) {
variableListenerRef = null;
}
variableListenerClass = shadowVariableAnnotation.variableListenerClass();
if (variableListenerClass == CustomShadowVariable.NullVariableListener.class) {
variableListenerClass = null;
}
PlanningVariableReference[] sources = shadowVariableAnnotation.sources();
if (variableListenerRef != null) {
if (variableListenerClass != null || sources.length > 0) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with a non-null variableListenerRef (" + variableListenerRef
+ "), so it cannot have a variableListenerClass (" + variableListenerClass
+ ") nor any sources (" + Arrays.toString(sources) + ").");
}
} else {
if (variableListenerClass == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") which lacks a variableListenerClass (" + variableListenerClass + ").");
}
if (sources.length < 1) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with sources (" + Arrays.toString(sources)
+ ") which is empty.");
}
}
}
public boolean isRef() {
// refVariableDescriptor might not be initialized yet, but variableListenerClass will
return variableListenerClass == null;
}
@Override
public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) {
linkShadowSources(descriptorPolicy);
}
private void linkShadowSources(DescriptorPolicy descriptorPolicy) {
CustomShadowVariable shadowVariableAnnotation = variableMemberAccessor
.getAnnotation(CustomShadowVariable.class);
PlanningVariableReference variableListenerRef = shadowVariableAnnotation.variableListenerRef();
if (variableListenerRef.variableName().equals("")) {
variableListenerRef = null;
}
if (variableListenerRef != null) {
EntityDescriptor<Solution_> refEntityDescriptor;
Class<?> refEntityClass = variableListenerRef.entityClass();
if (refEntityClass.equals(PlanningVariableReference.NullEntityClass.class)) {
refEntityDescriptor = entityDescriptor;
} else {
refEntityDescriptor = entityDescriptor.getSolutionDescriptor().findEntityDescriptor(refEntityClass);
if (refEntityDescriptor == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with a refEntityClass (" + refEntityClass
+ ") which is not a valid planning entity."
+ "\nMaybe check the annotations of the class (" + refEntityClass + ")."
+ "\nMaybe add the class (" + refEntityClass
+ ") among planning entities in the solver configuration.");
}
}
String refVariableName = variableListenerRef.variableName();
VariableDescriptor<Solution_> uncastRefVariableDescriptor = refEntityDescriptor
.getVariableDescriptor(refVariableName);
if (uncastRefVariableDescriptor == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with refVariableName (" + refVariableName
+ ") which is not a valid planning variable on entityClass ("
+ refEntityDescriptor.getEntityClass() + ").\n"
+ refEntityDescriptor.buildInvalidVariableNameExceptionMessage(refVariableName));
}
if (!(uncastRefVariableDescriptor instanceof LegacyCustomShadowVariableDescriptor)) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with refVariable (" + uncastRefVariableDescriptor.getSimpleEntityAndVariableName()
+ ") that lacks a @" + CustomShadowVariable.class.getSimpleName() + " annotation.");
}
refVariableDescriptor = (LegacyCustomShadowVariableDescriptor<Solution_>) uncastRefVariableDescriptor;
if (refVariableDescriptor.isRef()) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with refVariable (" + refVariableDescriptor + ") that is a reference itself too.");
}
refVariableDescriptor.registerSinkVariableDescriptor(this);
} else {
PlanningVariableReference[] sources = shadowVariableAnnotation.sources();
sourceVariableDescriptorList = new ArrayList<>(sources.length);
for (PlanningVariableReference source : sources) {
EntityDescriptor<Solution_> sourceEntityDescriptor;
Class<?> sourceEntityClass = source.entityClass();
if (sourceEntityClass.equals(PlanningVariableReference.NullEntityClass.class)) {
sourceEntityDescriptor = entityDescriptor;
} else {
sourceEntityDescriptor = entityDescriptor.getSolutionDescriptor()
.findEntityDescriptor(sourceEntityClass);
if (sourceEntityDescriptor == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with a sourceEntityClass (" + sourceEntityClass
+ ") which is not a valid planning entity."
+ "\nMaybe check the annotations of the class (" + sourceEntityClass + ")."
+ "\nMaybe add the class (" + sourceEntityClass
+ ") among planning entities in the solver configuration.");
}
}
String sourceVariableName = source.variableName();
VariableDescriptor<Solution_> sourceVariableDescriptor = sourceEntityDescriptor.getVariableDescriptor(
sourceVariableName);
if (sourceVariableDescriptor == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with sourceVariableName (" + sourceVariableName
+ ") which is not a valid planning variable on entityClass ("
+ sourceEntityDescriptor.getEntityClass() + ").\n"
+ sourceEntityDescriptor.buildInvalidVariableNameExceptionMessage(sourceVariableName));
}
if (sourceVariableDescriptor.isListVariable()) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + CustomShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with sourceVariableName (" + sourceVariableName
+ ") which is a list variable.\n"
+ "Custom shadow variables sourced on list variables are not yet supported.");
}
sourceVariableDescriptor.registerSinkVariableDescriptor(this);
sourceVariableDescriptorList.add(sourceVariableDescriptor);
}
}
}
@Override
public List<VariableDescriptor<Solution_>> getSourceVariableDescriptorList() {
if (refVariableDescriptor != null) {
return Collections.singletonList(refVariableDescriptor);
}
return sourceVariableDescriptorList;
}
@Override
public Collection<Class<? extends AbstractVariableListener>> getVariableListenerClasses() {
if (isRef()) {
return refVariableDescriptor.getVariableListenerClasses();
}
return Collections.singleton(variableListenerClass);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Demand<?> getProvidedDemand() {
throw new UnsupportedOperationException("Custom shadow variable cannot be demanded.");
}
@Override
public boolean hasVariableListener() {
return refVariableDescriptor == null;
}
@Override
public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) {
if (refVariableDescriptor != null) {
throw new IllegalStateException("The shadowVariableDescriptor (" + this
+ ") references another shadowVariableDescriptor (" + refVariableDescriptor
+ ") so it cannot build a " + VariableListener.class.getSimpleName() + ".");
}
VariableListener<Solution_, Object> variableListener =
ConfigUtils.newInstance(this::toString, "variableListenerClass", variableListenerClass);
return new VariableListenerWithSources<>(variableListener, sourceVariableDescriptorList).toCollection();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable | java-sources/ai/timefold/solver/timefold-solver-core-impl/1.8.1/ai/timefold/solver/core/impl/domain/variable/custom/PiggybackShadowVariableDescriptor.java | package ai.timefold.solver.core.impl.domain.variable.custom;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener;
import ai.timefold.solver.core.api.domain.variable.PiggybackShadowVariable;
import ai.timefold.solver.core.api.domain.variable.ShadowVariable;
import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor;
import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.listener.VariableListenerWithSources;
import ai.timefold.solver.core.impl.domain.variable.supply.Demand;
import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public final class PiggybackShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> {
private CustomShadowVariableDescriptor<Solution_> shadowVariableDescriptor;
public PiggybackShadowVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor,
MemberAccessor variableMemberAccessor) {
super(ordinal, entityDescriptor, variableMemberAccessor);
}
@Override
public void processAnnotations(DescriptorPolicy descriptorPolicy) {
// Do nothing
}
@Override
public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) {
linkShadowSources(descriptorPolicy);
}
private void linkShadowSources(DescriptorPolicy descriptorPolicy) {
PiggybackShadowVariable piggybackShadowVariable = variableMemberAccessor.getAnnotation(PiggybackShadowVariable.class);
EntityDescriptor<Solution_> shadowEntityDescriptor;
Class<?> shadowEntityClass = piggybackShadowVariable.shadowEntityClass();
if (shadowEntityClass.equals(PiggybackShadowVariable.NullEntityClass.class)) {
shadowEntityDescriptor = entityDescriptor;
} else {
shadowEntityDescriptor = entityDescriptor.getSolutionDescriptor().findEntityDescriptor(shadowEntityClass);
if (shadowEntityDescriptor == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + PiggybackShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with a shadowEntityClass (" + shadowEntityClass
+ ") which is not a valid planning entity."
+ "\nMaybe check the annotations of the class (" + shadowEntityClass + ")."
+ "\nMaybe add the class (" + shadowEntityClass
+ ") among planning entities in the solver configuration.");
}
}
String shadowVariableName = piggybackShadowVariable.shadowVariableName();
VariableDescriptor<Solution_> uncastShadowVariableDescriptor =
shadowEntityDescriptor.getVariableDescriptor(shadowVariableName);
if (uncastShadowVariableDescriptor == null) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + PiggybackShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with shadowVariableName (" + shadowVariableName
+ ") which is not a valid planning variable on entityClass ("
+ shadowEntityDescriptor.getEntityClass() + ").\n"
+ shadowEntityDescriptor.buildInvalidVariableNameExceptionMessage(shadowVariableName));
}
if (!(uncastShadowVariableDescriptor instanceof CustomShadowVariableDescriptor)) {
throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass()
+ ") has a @" + PiggybackShadowVariable.class.getSimpleName()
+ " annotated property (" + variableMemberAccessor.getName()
+ ") with refVariable (" + uncastShadowVariableDescriptor.getSimpleEntityAndVariableName()
+ ") that lacks a @" + ShadowVariable.class.getSimpleName() + " annotation.");
}
shadowVariableDescriptor = (CustomShadowVariableDescriptor<Solution_>) uncastShadowVariableDescriptor;
shadowVariableDescriptor.registerSinkVariableDescriptor(this);
}
@Override
public List<VariableDescriptor<Solution_>> getSourceVariableDescriptorList() {
return Collections.singletonList(shadowVariableDescriptor);
}
@Override
public Collection<Class<? extends AbstractVariableListener>> getVariableListenerClasses() {
return shadowVariableDescriptor.getVariableListenerClasses();
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Demand<?> getProvidedDemand() {
throw new UnsupportedOperationException("Custom shadow variable cannot be demanded.");
}
@Override
public boolean hasVariableListener() {
return false;
}
@Override
public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) {
throw new UnsupportedOperationException("The piggybackShadowVariableDescriptor (" + this
+ ") cannot build a variable listener.");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.