index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config/SolverBenchmarkConfig.java
package ai.timefold.solver.benchmark.config; 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.solver.SolverConfig; import ai.timefold.solver.core.config.util.ConfigUtils; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; @XmlType(propOrder = { "name", "solverConfig", "problemBenchmarksConfig", "subSingleCount" }) public class SolverBenchmarkConfig extends AbstractConfig<SolverBenchmarkConfig> { private String name = null; @XmlElement(name = SolverConfig.XML_ELEMENT_NAME, namespace = SolverConfig.XML_NAMESPACE) private SolverConfig solverConfig = null; @XmlElement(name = "problemBenchmarks") private ProblemBenchmarksConfig problemBenchmarksConfig = null; private Integer subSingleCount = null; // ************************************************************************ // Constructors and simple getters/setters // ************************************************************************ public @Nullable String getName() { return name; } public void setName(@Nullable String name) { this.name = name; } public @Nullable SolverConfig getSolverConfig() { return solverConfig; } public void setSolverConfig(@Nullable SolverConfig solverConfig) { this.solverConfig = solverConfig; } public @Nullable ProblemBenchmarksConfig getProblemBenchmarksConfig() { return problemBenchmarksConfig; } public void setProblemBenchmarksConfig(@Nullable ProblemBenchmarksConfig problemBenchmarksConfig) { this.problemBenchmarksConfig = problemBenchmarksConfig; } public @Nullable Integer getSubSingleCount() { return subSingleCount; } public void setSubSingleCount(@Nullable Integer subSingleCount) { this.subSingleCount = subSingleCount; } // ************************************************************************ // With methods // ************************************************************************ public @NonNull SolverBenchmarkConfig withName(@NonNull String name) { this.setName(name); return this; } public @NonNull SolverBenchmarkConfig withSolverConfig(@NonNull SolverConfig solverConfig) { this.setSolverConfig(solverConfig); return this; } public @NonNull SolverBenchmarkConfig withProblemBenchmarksConfig(@NonNull ProblemBenchmarksConfig problemBenchmarksConfig) { this.setProblemBenchmarksConfig(problemBenchmarksConfig); return this; } public @NonNull SolverBenchmarkConfig withSubSingleCount(@NonNull Integer subSingleCount) { this.setSubSingleCount(subSingleCount); return this; } @Override public @NonNull SolverBenchmarkConfig inherit(@NonNull SolverBenchmarkConfig inheritedConfig) { solverConfig = ConfigUtils.inheritConfig(solverConfig, inheritedConfig.getSolverConfig()); problemBenchmarksConfig = ConfigUtils.inheritConfig(problemBenchmarksConfig, inheritedConfig.getProblemBenchmarksConfig()); subSingleCount = ConfigUtils.inheritOverwritableProperty(subSingleCount, inheritedConfig.getSubSingleCount()); return this; } @Override public @NonNull SolverBenchmarkConfig copyConfig() { return new SolverBenchmarkConfig().inherit(this); } @Override public void visitReferencedClasses(@NonNull Consumer<Class<?>> classVisitor) { if (solverConfig != null) { solverConfig.visitReferencedClasses(classVisitor); } if (problemBenchmarksConfig != null) { problemBenchmarksConfig.visitReferencedClasses(classVisitor); } } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config/package-info.java
/** * Classes which represent the XML Benchmark configuration of Timefold Benchmark. * <p> * The XML Benchmark configuration is backwards compatible for all elements, * except for elements that require the use of non-public API classes. */ @XmlSchema( namespace = PlannerBenchmarkConfig.XML_NAMESPACE, elementFormDefault = XmlNsForm.QUALIFIED, xmlns = { @XmlNs(namespaceURI = SolverConfig.XML_NAMESPACE, prefix = PlannerBenchmarkConfig.SOLVER_NAMESPACE_PREFIX) }) package ai.timefold.solver.benchmark.config; import jakarta.xml.bind.annotation.XmlNs; import jakarta.xml.bind.annotation.XmlNsForm; import jakarta.xml.bind.annotation.XmlSchema; import ai.timefold.solver.core.config.solver.SolverConfig;
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config/blueprint/SolverBenchmarkBluePrintConfig.java
package ai.timefold.solver.benchmark.config.blueprint; import java.util.List; import jakarta.xml.bind.annotation.XmlType; import ai.timefold.solver.benchmark.config.SolverBenchmarkConfig; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; @XmlType(propOrder = { "solverBenchmarkBluePrintType" }) public class SolverBenchmarkBluePrintConfig { protected SolverBenchmarkBluePrintType solverBenchmarkBluePrintType = null; public @Nullable SolverBenchmarkBluePrintType getSolverBenchmarkBluePrintType() { return solverBenchmarkBluePrintType; } public void setSolverBenchmarkBluePrintType(@Nullable SolverBenchmarkBluePrintType solverBenchmarkBluePrintType) { this.solverBenchmarkBluePrintType = solverBenchmarkBluePrintType; } // ************************************************************************ // Builder methods // ************************************************************************ public @NonNull List<SolverBenchmarkConfig> buildSolverBenchmarkConfigList() { validate(); return solverBenchmarkBluePrintType.buildSolverBenchmarkConfigList(); } protected void validate() { if (solverBenchmarkBluePrintType == null) { throw new IllegalArgumentException( "The solverBenchmarkBluePrint must have" + " a solverBenchmarkBluePrintType (" + solverBenchmarkBluePrintType + ")."); } } // ************************************************************************ // With methods // ************************************************************************ public @NonNull SolverBenchmarkBluePrintConfig withSolverBenchmarkBluePrintType( @NonNull SolverBenchmarkBluePrintType solverBenchmarkBluePrintType) { this.solverBenchmarkBluePrintType = solverBenchmarkBluePrintType; return this; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config/blueprint/SolverBenchmarkBluePrintType.java
package ai.timefold.solver.benchmark.config.blueprint; import java.util.ArrayList; import java.util.List; import jakarta.xml.bind.annotation.XmlEnum; import ai.timefold.solver.benchmark.config.SolverBenchmarkConfig; import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig; import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicType; import ai.timefold.solver.core.config.localsearch.LocalSearchPhaseConfig; import ai.timefold.solver.core.config.localsearch.LocalSearchType; import ai.timefold.solver.core.config.phase.PhaseConfig; import ai.timefold.solver.core.config.solver.SolverConfig; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; @XmlEnum public enum SolverBenchmarkBluePrintType { /* * Run the default {@link ConstructionHeuristicType} with and without the default {@link LocalSearchType}. */ CONSTRUCTION_HEURISTIC_WITH_AND_WITHOUT_LOCAL_SEARCH, /** * Run every {@link ConstructionHeuristicType}. */ EVERY_CONSTRUCTION_HEURISTIC_TYPE, /** * Run the default {@link ConstructionHeuristicType} with every {@link LocalSearchType}. */ EVERY_LOCAL_SEARCH_TYPE, /** * Run every {@link ConstructionHeuristicType} with every {@link LocalSearchType}. */ EVERY_CONSTRUCTION_HEURISTIC_TYPE_WITH_EVERY_LOCAL_SEARCH_TYPE; @NonNull List<SolverBenchmarkConfig> buildSolverBenchmarkConfigList() { return switch (this) { case CONSTRUCTION_HEURISTIC_WITH_AND_WITHOUT_LOCAL_SEARCH -> buildConstructionHeuristicWithAndWithoutLocalSearch(); case EVERY_CONSTRUCTION_HEURISTIC_TYPE -> buildEveryConstructionHeuristicType(); case EVERY_LOCAL_SEARCH_TYPE -> buildEveryLocalSearchType(); case EVERY_CONSTRUCTION_HEURISTIC_TYPE_WITH_EVERY_LOCAL_SEARCH_TYPE -> buildEveryConstructionHeuristicTypeWithEveryLocalSearchType(); }; } private List<SolverBenchmarkConfig> buildConstructionHeuristicWithAndWithoutLocalSearch() { List<SolverBenchmarkConfig> solverBenchmarkConfigList = new ArrayList<>(2); solverBenchmarkConfigList.add(buildSolverBenchmarkConfig(null, false, null)); solverBenchmarkConfigList.add(buildSolverBenchmarkConfig(null, true, null)); return solverBenchmarkConfigList; } private List<SolverBenchmarkConfig> buildEveryConstructionHeuristicType() { ConstructionHeuristicType[] chTypes = ConstructionHeuristicType.getBluePrintTypes(); List<SolverBenchmarkConfig> solverBenchmarkConfigList = new ArrayList<>(chTypes.length); for (ConstructionHeuristicType chType : chTypes) { solverBenchmarkConfigList.add(buildSolverBenchmarkConfig(chType, false, null)); } return solverBenchmarkConfigList; } private List<SolverBenchmarkConfig> buildEveryLocalSearchType() { return buildEveryLocalSearchType(null); } private List<SolverBenchmarkConfig> buildEveryLocalSearchType(ConstructionHeuristicType constructionHeuristicType) { LocalSearchType[] lsTypes = LocalSearchType.getBluePrintTypes(); List<SolverBenchmarkConfig> solverBenchmarkConfigList = new ArrayList<>(lsTypes.length); for (LocalSearchType lsType : lsTypes) { if (lsType == LocalSearchType.DIVERSIFIED_LATE_ACCEPTANCE) { // When the preview feature is removed, this will fail at compile time // and the code will have to be adjusted. // Most likely, the preview feature will be promoted to a regular feature, // and this if statement will be removed. continue; } solverBenchmarkConfigList.add(buildSolverBenchmarkConfig(constructionHeuristicType, true, lsType)); } return solverBenchmarkConfigList; } private List<SolverBenchmarkConfig> buildEveryConstructionHeuristicTypeWithEveryLocalSearchType() { ConstructionHeuristicType[] chTypes = ConstructionHeuristicType.getBluePrintTypes(); LocalSearchType[] lsTypes = LocalSearchType.getBluePrintTypes(); List<SolverBenchmarkConfig> solverBenchmarkConfigList = new ArrayList<>(chTypes.length * lsTypes.length); for (ConstructionHeuristicType chType : chTypes) { solverBenchmarkConfigList.addAll(buildEveryLocalSearchType(chType)); } return solverBenchmarkConfigList; } @NonNull private SolverBenchmarkConfig buildSolverBenchmarkConfig( @Nullable ConstructionHeuristicType constructionHeuristicType, boolean localSearchEnabled, @Nullable LocalSearchType localSearchType) { SolverBenchmarkConfig solverBenchmarkConfig = new SolverBenchmarkConfig(); String constructionHeuristicName = constructionHeuristicType == null ? "Construction Heuristic" : constructionHeuristicType.name(); String name; if (!localSearchEnabled) { name = constructionHeuristicName; } else { String localSearchName = localSearchType == null ? "Local Search" : localSearchType.name(); name = constructionHeuristicType == null ? localSearchName : constructionHeuristicName + " - " + localSearchName; } solverBenchmarkConfig.setName(name); SolverConfig solverConfig = new SolverConfig(); List<PhaseConfig> phaseConfigList = new ArrayList<>(2); ConstructionHeuristicPhaseConfig constructionHeuristicPhaseConfig = new ConstructionHeuristicPhaseConfig(); if (constructionHeuristicType != null) { constructionHeuristicPhaseConfig.setConstructionHeuristicType(constructionHeuristicType); } phaseConfigList.add(constructionHeuristicPhaseConfig); if (localSearchEnabled) { LocalSearchPhaseConfig localSearchPhaseConfig = new LocalSearchPhaseConfig(); if (localSearchType != null) { localSearchPhaseConfig.setLocalSearchType(localSearchType); } phaseConfigList.add(localSearchPhaseConfig); } solverConfig.setPhaseConfigList(phaseConfigList); solverBenchmarkConfig.setSolverConfig(solverConfig); return solverBenchmarkConfig; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config/blueprint/package-info.java
@XmlSchema( namespace = PlannerBenchmarkConfig.XML_NAMESPACE, elementFormDefault = XmlNsForm.QUALIFIED) package ai.timefold.solver.benchmark.config.blueprint; import jakarta.xml.bind.annotation.XmlNsForm; import jakarta.xml.bind.annotation.XmlSchema; import ai.timefold.solver.benchmark.config.PlannerBenchmarkConfig;
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config/ranking/SolverRankingType.java
package ai.timefold.solver.benchmark.config.ranking; import jakarta.xml.bind.annotation.XmlEnum; import ai.timefold.solver.benchmark.impl.ranking.TotalRankSolverRankingWeightFactory; import ai.timefold.solver.benchmark.impl.ranking.TotalScoreSolverRankingComparator; import ai.timefold.solver.benchmark.impl.ranking.WorstScoreSolverRankingComparator; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; @XmlEnum public enum SolverRankingType { /** * Maximize the overall score, so minimize the overall cost if all {@link PlanningSolution}s would be executed. * * @see TotalScoreSolverRankingComparator */ TOTAL_SCORE, /** * Minimize the worst case scenario. * * @see WorstScoreSolverRankingComparator */ WORST_SCORE, /** * Maximize the overall ranking. * * @see TotalRankSolverRankingWeightFactory */ TOTAL_RANKING; }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config/ranking/package-info.java
@XmlSchema( namespace = PlannerBenchmarkConfig.XML_NAMESPACE, elementFormDefault = XmlNsForm.QUALIFIED) package ai.timefold.solver.benchmark.config.ranking; import jakarta.xml.bind.annotation.XmlNsForm; import jakarta.xml.bind.annotation.XmlSchema; import ai.timefold.solver.benchmark.config.PlannerBenchmarkConfig;
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config/report/BenchmarkReportConfig.java
package ai.timefold.solver.benchmark.config.report; import java.util.Comparator; import java.util.Locale; import java.util.function.Consumer; import jakarta.xml.bind.annotation.XmlType; import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import ai.timefold.solver.benchmark.config.ranking.SolverRankingType; import ai.timefold.solver.benchmark.impl.ranking.SolverRankingWeightFactory; import ai.timefold.solver.benchmark.impl.result.SolverBenchmarkResult; import ai.timefold.solver.core.config.AbstractConfig; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.io.jaxb.adapter.JaxbLocaleAdapter; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; @XmlType(propOrder = { "locale", "solverRankingType", "solverRankingComparatorClass", "solverRankingWeightFactoryClass" }) public class BenchmarkReportConfig extends AbstractConfig<BenchmarkReportConfig> { @XmlJavaTypeAdapter(JaxbLocaleAdapter.class) private Locale locale = null; private SolverRankingType solverRankingType = null; private Class<? extends Comparator<SolverBenchmarkResult>> solverRankingComparatorClass = null; private Class<? extends SolverRankingWeightFactory> solverRankingWeightFactoryClass = null; public BenchmarkReportConfig() { } public BenchmarkReportConfig(@NonNull BenchmarkReportConfig inheritedConfig) { inherit(inheritedConfig); } public @Nullable Locale getLocale() { return locale; } public void setLocale(@Nullable Locale locale) { this.locale = locale; } public @Nullable SolverRankingType getSolverRankingType() { return solverRankingType; } public void setSolverRankingType(@Nullable SolverRankingType solverRankingType) { this.solverRankingType = solverRankingType; } public @Nullable Class<? extends Comparator<SolverBenchmarkResult>> getSolverRankingComparatorClass() { return solverRankingComparatorClass; } public void setSolverRankingComparatorClass( @Nullable Class<? extends Comparator<SolverBenchmarkResult>> solverRankingComparatorClass) { this.solverRankingComparatorClass = solverRankingComparatorClass; } public @Nullable Class<? extends SolverRankingWeightFactory> getSolverRankingWeightFactoryClass() { return solverRankingWeightFactoryClass; } public void setSolverRankingWeightFactoryClass( @Nullable Class<? extends SolverRankingWeightFactory> solverRankingWeightFactoryClass) { this.solverRankingWeightFactoryClass = solverRankingWeightFactoryClass; } public @Nullable Locale determineLocale() { return getLocale() == null ? Locale.getDefault() : getLocale(); } // ************************************************************************ // With methods // ************************************************************************ public @NonNull BenchmarkReportConfig withLocale(@NonNull Locale locale) { this.setLocale(locale); return this; } public @NonNull BenchmarkReportConfig withSolverRankingType(@NonNull SolverRankingType solverRankingType) { this.setSolverRankingType(solverRankingType); return this; } public @NonNull BenchmarkReportConfig withSolverRankingComparatorClass( @NonNull Class<? extends Comparator<SolverBenchmarkResult>> solverRankingComparatorClass) { this.setSolverRankingComparatorClass(solverRankingComparatorClass); return this; } public @NonNull BenchmarkReportConfig withSolverRankingWeightFactoryClass( @NonNull Class<? extends SolverRankingWeightFactory> solverRankingWeightFactoryClass) { this.setSolverRankingWeightFactoryClass(solverRankingWeightFactoryClass); return this; } @Override public @NonNull BenchmarkReportConfig inherit(@NonNull BenchmarkReportConfig inheritedConfig) { locale = ConfigUtils.inheritOverwritableProperty(locale, inheritedConfig.getLocale()); solverRankingType = ConfigUtils.inheritOverwritableProperty(solverRankingType, inheritedConfig.getSolverRankingType()); solverRankingComparatorClass = ConfigUtils.inheritOverwritableProperty(solverRankingComparatorClass, inheritedConfig.getSolverRankingComparatorClass()); solverRankingWeightFactoryClass = ConfigUtils.inheritOverwritableProperty(solverRankingWeightFactoryClass, inheritedConfig.getSolverRankingWeightFactoryClass()); return this; } @Override public @NonNull BenchmarkReportConfig copyConfig() { return new BenchmarkReportConfig().inherit(this); } @Override public void visitReferencedClasses(@NonNull Consumer<Class<?>> classVisitor) { classVisitor.accept(solverRankingComparatorClass); classVisitor.accept(solverRankingWeightFactoryClass); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config/report/package-info.java
@XmlSchema( namespace = PlannerBenchmarkConfig.XML_NAMESPACE, elementFormDefault = XmlNsForm.QUALIFIED) package ai.timefold.solver.benchmark.config.report; import jakarta.xml.bind.annotation.XmlNsForm; import jakarta.xml.bind.annotation.XmlSchema; import ai.timefold.solver.benchmark.config.PlannerBenchmarkConfig;
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config/statistic/ProblemStatisticType.java
package ai.timefold.solver.benchmark.config.statistic; import java.util.List; import jakarta.xml.bind.annotation.XmlEnum; import ai.timefold.solver.benchmark.impl.result.ProblemBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.StatisticType; import ai.timefold.solver.benchmark.impl.statistic.bestscore.BestScoreProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.bestsolutionmutation.BestSolutionMutationProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.memoryuse.MemoryUseProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.movecountperstep.MoveCountPerStepProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.movecountpertype.MoveCountPerTypeProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.moveevaluationspeed.MoveEvaluationSpeedProblemStatisticTime; import ai.timefold.solver.benchmark.impl.statistic.scorecalculationspeed.ScoreCalculationSpeedProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.stepscore.StepScoreProblemStatistic; import org.jspecify.annotations.NonNull; @XmlEnum public enum ProblemStatisticType implements StatisticType { BEST_SCORE, STEP_SCORE, SCORE_CALCULATION_SPEED, MOVE_EVALUATION_SPEED, BEST_SOLUTION_MUTATION, MOVE_COUNT_PER_STEP, MOVE_COUNT_PER_TYPE, MEMORY_USE; public @NonNull ProblemStatistic buildProblemStatistic(@NonNull ProblemBenchmarkResult problemBenchmarkResult) { switch (this) { case BEST_SCORE: return new BestScoreProblemStatistic(problemBenchmarkResult); case STEP_SCORE: return new StepScoreProblemStatistic(problemBenchmarkResult); case SCORE_CALCULATION_SPEED: return new ScoreCalculationSpeedProblemStatistic(problemBenchmarkResult); case MOVE_EVALUATION_SPEED: return new MoveEvaluationSpeedProblemStatisticTime(problemBenchmarkResult); case BEST_SOLUTION_MUTATION: return new BestSolutionMutationProblemStatistic(problemBenchmarkResult); case MOVE_COUNT_PER_STEP: return new MoveCountPerStepProblemStatistic(problemBenchmarkResult); case MOVE_COUNT_PER_TYPE: return new MoveCountPerTypeProblemStatistic(problemBenchmarkResult); case MEMORY_USE: return new MemoryUseProblemStatistic(problemBenchmarkResult); default: throw new IllegalStateException("The problemStatisticType (" + this + ") is not implemented."); } } public boolean hasScoreLevels() { return this == BEST_SCORE || this == STEP_SCORE; } public static @NonNull List<@NonNull ProblemStatisticType> defaultList() { return List.of(ProblemStatisticType.BEST_SCORE); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config/statistic/SingleStatisticType.java
package ai.timefold.solver.benchmark.config.statistic; import jakarta.xml.bind.annotation.XmlEnum; import ai.timefold.solver.benchmark.impl.report.ReportHelper; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.PureSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.StatisticType; import ai.timefold.solver.benchmark.impl.statistic.subsingle.constraintmatchtotalbestscore.ConstraintMatchTotalBestScoreSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.subsingle.constraintmatchtotalstepscore.ConstraintMatchTotalStepScoreSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.subsingle.pickedmovetypebestscore.PickedMoveTypeBestScoreDiffSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.subsingle.pickedmovetypestepscore.PickedMoveTypeStepScoreDiffSubSingleStatistic; import org.jspecify.annotations.NonNull; @XmlEnum public enum SingleStatisticType implements StatisticType { CONSTRAINT_MATCH_TOTAL_BEST_SCORE, CONSTRAINT_MATCH_TOTAL_STEP_SCORE, PICKED_MOVE_TYPE_BEST_SCORE_DIFF, PICKED_MOVE_TYPE_STEP_SCORE_DIFF; public @NonNull PureSubSingleStatistic buildPureSubSingleStatistic(@NonNull SubSingleBenchmarkResult subSingleBenchmarkResult) { switch (this) { case CONSTRAINT_MATCH_TOTAL_BEST_SCORE: return new ConstraintMatchTotalBestScoreSubSingleStatistic(subSingleBenchmarkResult); case CONSTRAINT_MATCH_TOTAL_STEP_SCORE: return new ConstraintMatchTotalStepScoreSubSingleStatistic(subSingleBenchmarkResult); case PICKED_MOVE_TYPE_BEST_SCORE_DIFF: return new PickedMoveTypeBestScoreDiffSubSingleStatistic(subSingleBenchmarkResult); case PICKED_MOVE_TYPE_STEP_SCORE_DIFF: return new PickedMoveTypeStepScoreDiffSubSingleStatistic(subSingleBenchmarkResult); default: throw new IllegalStateException("The singleStatisticType (" + this + ") is not implemented."); } } public @NonNull String getAnchorId() { return ReportHelper.escapeHtmlId(name()); } public boolean hasScoreLevels() { return this == CONSTRAINT_MATCH_TOTAL_BEST_SCORE || this == CONSTRAINT_MATCH_TOTAL_STEP_SCORE || this == PICKED_MOVE_TYPE_BEST_SCORE_DIFF || this == PICKED_MOVE_TYPE_STEP_SCORE_DIFF; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/config/statistic/package-info.java
@XmlSchema( namespace = PlannerBenchmarkConfig.XML_NAMESPACE, elementFormDefault = XmlNsForm.QUALIFIED) package ai.timefold.solver.benchmark.config.statistic; import jakarta.xml.bind.annotation.XmlNsForm; import jakarta.xml.bind.annotation.XmlSchema; import ai.timefold.solver.benchmark.config.PlannerBenchmarkConfig;
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/DefaultPlannerBenchmark.java
package ai.timefold.solver.benchmark.impl; import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.time.OffsetDateTime; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import ai.timefold.solver.benchmark.api.PlannerBenchmark; import ai.timefold.solver.benchmark.api.PlannerBenchmarkException; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.result.BenchmarkResultIO; import ai.timefold.solver.benchmark.impl.result.PlannerBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.ProblemBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SolverBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.PureSubSingleStatistic; import ai.timefold.solver.core.config.solver.termination.TerminationConfig; import ai.timefold.solver.core.config.util.ConfigUtils; import org.jspecify.annotations.NonNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DefaultPlannerBenchmark implements PlannerBenchmark { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultPlannerBenchmark.class); private static final Logger SINGLE_BENCHMARK_RUNNER_EXCEPTION_LOGGER = LoggerFactory.getLogger(DefaultPlannerBenchmark.class + ".singleBenchmarkRunnerException"); private final PlannerBenchmarkResult plannerBenchmarkResult; private final File benchmarkDirectory; private final ExecutorService warmUpExecutorService; private final ExecutorCompletionService<SubSingleBenchmarkRunner> warmUpExecutorCompletionService; private final ExecutorService executorService; private final BenchmarkResultIO benchmarkResultIO; private final BenchmarkReport benchmarkReport; private long startingSystemTimeMillis = -1L; private SubSingleBenchmarkRunner firstFailureSubSingleBenchmarkRunner = null; public DefaultPlannerBenchmark(PlannerBenchmarkResult plannerBenchmarkResult, File benchmarkDirectory, ExecutorService warmUpExecutorService, ExecutorService executorService, BenchmarkReport benchmarkReport) { this.plannerBenchmarkResult = plannerBenchmarkResult; this.benchmarkDirectory = benchmarkDirectory; this.warmUpExecutorService = warmUpExecutorService; warmUpExecutorCompletionService = new ExecutorCompletionService<>(warmUpExecutorService); this.executorService = executorService; this.benchmarkReport = benchmarkReport; benchmarkResultIO = new BenchmarkResultIO(); } public PlannerBenchmarkResult getPlannerBenchmarkResult() { return plannerBenchmarkResult; } public File getBenchmarkDirectory() { return benchmarkDirectory; } public BenchmarkReport getBenchmarkReport() { return benchmarkReport; } // ************************************************************************ // Benchmark methods // ************************************************************************ @Override public @NonNull File benchmark() { benchmarkingStarted(); warmUp(); runSingleBenchmarks(); benchmarkingEnded(); return getBenchmarkDirectory(); } public void benchmarkingStarted() { if (startingSystemTimeMillis >= 0L) { throw new IllegalStateException("This benchmark has already ran before."); } startingSystemTimeMillis = System.currentTimeMillis(); plannerBenchmarkResult.setStartingTimestamp(OffsetDateTime.now()); List<SolverBenchmarkResult> solverBenchmarkResultList = plannerBenchmarkResult.getSolverBenchmarkResultList(); if (ConfigUtils.isEmptyCollection(solverBenchmarkResultList)) { throw new IllegalArgumentException( "The solverBenchmarkResultList (" + solverBenchmarkResultList + ") cannot be empty."); } initBenchmarkDirectoryAndSubdirectories(); plannerBenchmarkResult.initSystemProperties(); LOGGER.info("Benchmarking started: parallelBenchmarkCount ({})" + " for problemCount ({}), solverCount ({}), totalSubSingleCount ({}).", plannerBenchmarkResult.getParallelBenchmarkCount(), plannerBenchmarkResult.getUnifiedProblemBenchmarkResultList().size(), solverBenchmarkResultList.size(), plannerBenchmarkResult.getTotalSubSingleCount()); } private void initBenchmarkDirectoryAndSubdirectories() { if (benchmarkDirectory == null) { throw new IllegalArgumentException("The benchmarkDirectory (" + benchmarkDirectory + ") must not be null."); } // benchmarkDirectory usually already exists benchmarkDirectory.mkdirs(); plannerBenchmarkResult.initBenchmarkReportDirectory(benchmarkDirectory); } private void warmUp() { if (plannerBenchmarkResult.getWarmUpTimeMillisSpentLimit() <= 0L) { return; } LOGGER.info("================================================================================"); LOGGER.info("Warm up started"); LOGGER.info("================================================================================"); long timeLeftTotal = plannerBenchmarkResult.getWarmUpTimeMillisSpentLimit(); int parallelBenchmarkCount = plannerBenchmarkResult.getParallelBenchmarkCount(); int solverBenchmarkResultCount = plannerBenchmarkResult.getSolverBenchmarkResultList().size(); int cyclesCount = ConfigUtils.ceilDivide(solverBenchmarkResultCount, parallelBenchmarkCount); long timeLeftPerCycle = Math.floorDiv(timeLeftTotal, cyclesCount); Map<ProblemBenchmarkResult, List<ProblemStatistic>> originalProblemStatisticMap = new HashMap<>( plannerBenchmarkResult.getUnifiedProblemBenchmarkResultList().size()); ConcurrentMap<SolverBenchmarkResult, Integer> singleBenchmarkResultIndexMap = new ConcurrentHashMap<>( solverBenchmarkResultCount); Map<SolverBenchmarkResult, WarmUpConfigBackup> warmUpConfigBackupMap = WarmUpConfigBackup .backupBenchmarkConfig(plannerBenchmarkResult, originalProblemStatisticMap); SolverBenchmarkResult[] solverBenchmarkResultCycle = new SolverBenchmarkResult[parallelBenchmarkCount]; int solverBenchmarkResultIndex = 0; for (int i = 0; i < cyclesCount; i++) { long timeCycleEnd = System.currentTimeMillis() + timeLeftPerCycle; for (int j = 0; j < parallelBenchmarkCount; j++) { solverBenchmarkResultCycle[j] = plannerBenchmarkResult.getSolverBenchmarkResultList() .get(solverBenchmarkResultIndex % solverBenchmarkResultCount); solverBenchmarkResultIndex++; } ConcurrentMap<Future<SubSingleBenchmarkRunner>, SubSingleBenchmarkRunner> futureMap = new ConcurrentHashMap<>( parallelBenchmarkCount); warmUpPopulate(futureMap, singleBenchmarkResultIndexMap, solverBenchmarkResultCycle, timeLeftPerCycle); warmUp(futureMap, singleBenchmarkResultIndexMap, timeCycleEnd); } WarmUpConfigBackup.restoreBenchmarkConfig(plannerBenchmarkResult, originalProblemStatisticMap, warmUpConfigBackupMap); List<Runnable> notFinishedWarmUpList = warmUpExecutorService.shutdownNow(); if (!notFinishedWarmUpList.isEmpty()) { throw new IllegalStateException("Impossible state: notFinishedWarmUpList (" + notFinishedWarmUpList + ") is not empty."); } LOGGER.info("================================================================================"); LOGGER.info("Warm up ended"); LOGGER.info("================================================================================"); } private void warmUpPopulate(Map<Future<SubSingleBenchmarkRunner>, SubSingleBenchmarkRunner> futureMap, ConcurrentMap<SolverBenchmarkResult, Integer> singleBenchmarkResultIndexMap, SolverBenchmarkResult[] solverBenchmarkResultArray, long timeLeftPerSolverConfig) { for (SolverBenchmarkResult solverBenchmarkResult : solverBenchmarkResultArray) { TerminationConfig originalTerminationConfig = solverBenchmarkResult.getSolverConfig().getTerminationConfig(); TerminationConfig tmpTerminationConfig = new TerminationConfig(); if (originalTerminationConfig != null) { tmpTerminationConfig.inherit(originalTerminationConfig); } tmpTerminationConfig.shortenTimeMillisSpentLimit(timeLeftPerSolverConfig); solverBenchmarkResult.getSolverConfig().setTerminationConfig(tmpTerminationConfig); Integer singleBenchmarkResultIndex = singleBenchmarkResultIndexMap.get(solverBenchmarkResult); singleBenchmarkResultIndex = (singleBenchmarkResultIndex == null) ? 0 : singleBenchmarkResultIndex % solverBenchmarkResult.getSingleBenchmarkResultList().size(); SingleBenchmarkResult singleBenchmarkResult = solverBenchmarkResult.getSingleBenchmarkResultList() .get(singleBenchmarkResultIndex); // Just take the first subSingle, we don't need to warm up each one SubSingleBenchmarkRunner subSingleBenchmarkRunner = new SubSingleBenchmarkRunner( singleBenchmarkResult.getSubSingleBenchmarkResultList().get(0), true); Future<SubSingleBenchmarkRunner> future = warmUpExecutorCompletionService.submit(subSingleBenchmarkRunner); futureMap.put(future, subSingleBenchmarkRunner); singleBenchmarkResultIndexMap.put(solverBenchmarkResult, singleBenchmarkResultIndex + 1); } } private void warmUp(Map<Future<SubSingleBenchmarkRunner>, SubSingleBenchmarkRunner> futureMap, ConcurrentMap<SolverBenchmarkResult, Integer> singleBenchmarkResultIndexMap, long timePhaseEnd) { // Wait for the warm up benchmarks to complete int tasksCount = futureMap.size(); // Use a counter because completion order of futures is different from input order for (int i = 0; i < tasksCount; i++) { Future<SubSingleBenchmarkRunner> future; try { future = warmUpExecutorCompletionService.take(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Waiting for a warm up singleBenchmarkRunner was interrupted.", e); } Throwable failureThrowable = null; SubSingleBenchmarkRunner subSingleBenchmarkRunner; try { // Explicitly returning it in the Callable guarantees memory visibility subSingleBenchmarkRunner = future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); subSingleBenchmarkRunner = futureMap.get(future); SINGLE_BENCHMARK_RUNNER_EXCEPTION_LOGGER.error( "The warm up singleBenchmarkRunner ({}) with random seed ({}) was interrupted.", subSingleBenchmarkRunner, subSingleBenchmarkRunner.getRandomSeed(), e); failureThrowable = e; } catch (ExecutionException e) { Throwable cause = e.getCause(); subSingleBenchmarkRunner = futureMap.get(future); SINGLE_BENCHMARK_RUNNER_EXCEPTION_LOGGER.warn( "The warm up singleBenchmarkRunner ({}) with random seed ({}) failed.", subSingleBenchmarkRunner, subSingleBenchmarkRunner.getRandomSeed(), cause); failureThrowable = cause; } if (failureThrowable != null) { subSingleBenchmarkRunner.setFailureThrowable(failureThrowable); if (firstFailureSubSingleBenchmarkRunner == null) { firstFailureSubSingleBenchmarkRunner = subSingleBenchmarkRunner; } continue; // continue to the next task } SolverBenchmarkResult solverBenchmarkResult = subSingleBenchmarkRunner.getSubSingleBenchmarkResult() .getSingleBenchmarkResult().getSolverBenchmarkResult(); long timeLeftInCycle = timePhaseEnd - System.currentTimeMillis(); if (timeLeftInCycle > 0L) { SolverBenchmarkResult[] solverBenchmarkResultSingleton = new SolverBenchmarkResult[] { solverBenchmarkResult }; warmUpPopulate(futureMap, singleBenchmarkResultIndexMap, solverBenchmarkResultSingleton, timeLeftInCycle); tasksCount++; } } } protected void runSingleBenchmarks() { Map<SubSingleBenchmarkRunner, Future<SubSingleBenchmarkRunner>> futureMap = new HashMap<>(); for (ProblemBenchmarkResult<Object> problemBenchmarkResult : plannerBenchmarkResult .getUnifiedProblemBenchmarkResultList()) { for (SingleBenchmarkResult singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) { for (SubSingleBenchmarkResult subSingleBenchmarkResult : singleBenchmarkResult .getSubSingleBenchmarkResultList()) { SubSingleBenchmarkRunner subSingleBenchmarkRunner = new SubSingleBenchmarkRunner( subSingleBenchmarkResult, false); Future<SubSingleBenchmarkRunner> future = executorService.submit(subSingleBenchmarkRunner); futureMap.put(subSingleBenchmarkRunner, future); } } } // Wait for the benchmarks to complete for (Map.Entry<SubSingleBenchmarkRunner, Future<SubSingleBenchmarkRunner>> futureEntry : futureMap.entrySet()) { SubSingleBenchmarkRunner subSingleBenchmarkRunner = futureEntry.getKey(); Future<SubSingleBenchmarkRunner> future = futureEntry.getValue(); Throwable failureThrowable = null; try { // Explicitly returning it in the Callable guarantees memory visibility subSingleBenchmarkRunner = future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); SINGLE_BENCHMARK_RUNNER_EXCEPTION_LOGGER.error( "The subSingleBenchmarkRunner ({}) with random seed ({}) was interrupted.", subSingleBenchmarkRunner, subSingleBenchmarkRunner.getRandomSeed(), e); failureThrowable = e; } catch (ExecutionException e) { Throwable cause = e.getCause(); SINGLE_BENCHMARK_RUNNER_EXCEPTION_LOGGER.warn("The subSingleBenchmarkRunner ({}) with random seed ({}) failed.", subSingleBenchmarkRunner, subSingleBenchmarkRunner.getRandomSeed(), cause); failureThrowable = cause; } if (failureThrowable == null) { subSingleBenchmarkRunner.getSubSingleBenchmarkResult().setSucceeded(true); } else { subSingleBenchmarkRunner.getSubSingleBenchmarkResult().setSucceeded(false); subSingleBenchmarkRunner.setFailureThrowable(failureThrowable); if (firstFailureSubSingleBenchmarkRunner == null) { firstFailureSubSingleBenchmarkRunner = subSingleBenchmarkRunner; } } } } public void benchmarkingEnded() { List<Runnable> notExecutedBenchmarkList = executorService.shutdownNow(); if (!notExecutedBenchmarkList.isEmpty()) { throw new IllegalStateException("Impossible state: notExecutedBenchmarkList size (" + notExecutedBenchmarkList + ")."); } plannerBenchmarkResult.setBenchmarkTimeMillisSpent(calculateTimeMillisSpent()); benchmarkResultIO.writePlannerBenchmarkResult(plannerBenchmarkResult.getBenchmarkReportDirectory(), plannerBenchmarkResult); benchmarkReport.writeReport(); if (plannerBenchmarkResult.getFailureCount() == 0) { LOGGER.info("Benchmarking ended: time spent ({}), favoriteSolverBenchmark ({}), statistic html overview ({}).", plannerBenchmarkResult.getBenchmarkTimeMillisSpent(), plannerBenchmarkResult.getFavoriteSolverBenchmarkResult().getName(), benchmarkReport.getHtmlOverviewFile().getAbsolutePath()); } else { LOGGER.info("Benchmarking failed: time spent ({}), failureCount ({}), statistic html overview ({}).", plannerBenchmarkResult.getBenchmarkTimeMillisSpent(), plannerBenchmarkResult.getFailureCount(), benchmarkReport.getHtmlOverviewFile().getAbsolutePath()); throw new PlannerBenchmarkException("Benchmarking failed: failureCount (" + plannerBenchmarkResult.getFailureCount() + ")." + " The exception of the firstFailureSingleBenchmarkRunner (" + firstFailureSubSingleBenchmarkRunner.getName() + ") is chained.", firstFailureSubSingleBenchmarkRunner.getFailureThrowable()); } } public long calculateTimeMillisSpent() { long now = System.currentTimeMillis(); return now - startingSystemTimeMillis; } private static final class WarmUpConfigBackup { private final TerminationConfig terminationConfig; private final Map<SubSingleBenchmarkResult, List<PureSubSingleStatistic>> pureSubSingleStatisticMap; public WarmUpConfigBackup(TerminationConfig terminationConfig) { this.terminationConfig = terminationConfig; this.pureSubSingleStatisticMap = new HashMap<>(); } public Map<SubSingleBenchmarkResult, List<PureSubSingleStatistic>> getPureSubSingleStatisticMap() { return pureSubSingleStatisticMap; } public TerminationConfig getTerminationConfig() { return terminationConfig; } private static void restoreBenchmarkConfig(PlannerBenchmarkResult plannerBenchmarkResult, Map<ProblemBenchmarkResult, List<ProblemStatistic>> originalProblemStatisticMap, Map<SolverBenchmarkResult, WarmUpConfigBackup> warmUpConfigBackupMap) { for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) { WarmUpConfigBackup warmUpConfigBackup = warmUpConfigBackupMap.get(solverBenchmarkResult); TerminationConfig originalTerminationConfig = warmUpConfigBackup.getTerminationConfig(); solverBenchmarkResult.getSolverConfig().setTerminationConfig(originalTerminationConfig); for (SingleBenchmarkResult singleBenchmarkResult : solverBenchmarkResult.getSingleBenchmarkResultList()) { ProblemBenchmarkResult problemBenchmarkResult = singleBenchmarkResult.getProblemBenchmarkResult(); if (problemBenchmarkResult.getProblemStatisticList() == null || problemBenchmarkResult.getProblemStatisticList().size() <= 0) { problemBenchmarkResult.setProblemStatisticList(originalProblemStatisticMap.get(problemBenchmarkResult)); } for (SubSingleBenchmarkResult subSingleBenchmarkResult : singleBenchmarkResult .getSubSingleBenchmarkResultList()) { List<PureSubSingleStatistic> pureSubSingleStatisticList = warmUpConfigBackup .getPureSubSingleStatisticMap().get(subSingleBenchmarkResult); subSingleBenchmarkResult.setPureSubSingleStatisticList(pureSubSingleStatisticList); subSingleBenchmarkResult.initSubSingleStatisticMap(); } singleBenchmarkResult.initSubSingleStatisticMaps(); } } } private static Map<SolverBenchmarkResult, WarmUpConfigBackup> backupBenchmarkConfig( PlannerBenchmarkResult plannerBenchmarkResult, Map<ProblemBenchmarkResult, List<ProblemStatistic>> originalProblemStatisticMap) { // backup & remove stats, backup termination config Map<SolverBenchmarkResult, WarmUpConfigBackup> warmUpConfigBackupMap = new HashMap<>( plannerBenchmarkResult.getSolverBenchmarkResultList().size()); for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) { TerminationConfig originalTerminationConfig = solverBenchmarkResult.getSolverConfig().getTerminationConfig(); WarmUpConfigBackup warmUpConfigBackup = new WarmUpConfigBackup(originalTerminationConfig); for (SingleBenchmarkResult singleBenchmarkResult : solverBenchmarkResult.getSingleBenchmarkResultList()) { for (SubSingleBenchmarkResult subSingleBenchmarkResult : singleBenchmarkResult .getSubSingleBenchmarkResultList()) { List<PureSubSingleStatistic> originalPureSubSingleStatisticList = subSingleBenchmarkResult .getPureSubSingleStatisticList(); List<PureSubSingleStatistic> subSingleBenchmarkStatisticPutResult = warmUpConfigBackup .getPureSubSingleStatisticMap() .put(subSingleBenchmarkResult, originalPureSubSingleStatisticList); if (subSingleBenchmarkStatisticPutResult != null) { throw new IllegalStateException( "SubSingleBenchmarkStatisticMap of WarmUpConfigBackup (" + warmUpConfigBackup + ") already contained key (" + subSingleBenchmarkResult + ") with value (" + subSingleBenchmarkStatisticPutResult + ")."); } } ProblemBenchmarkResult problemBenchmarkResult = singleBenchmarkResult.getProblemBenchmarkResult(); originalProblemStatisticMap.putIfAbsent(problemBenchmarkResult, problemBenchmarkResult.getProblemStatisticList()); singleBenchmarkResult.getProblemBenchmarkResult().setProblemStatisticList(Collections.emptyList()); for (SubSingleBenchmarkResult subSingleBenchmarkResult : singleBenchmarkResult .getSubSingleBenchmarkResultList()) { // needs to happen after all problem stats subSingleBenchmarkResult.setPureSubSingleStatisticList(Collections.emptyList()); subSingleBenchmarkResult.initSubSingleStatisticMap(); } } WarmUpConfigBackup warmUpConfigBackupPutResult = warmUpConfigBackupMap.put(solverBenchmarkResult, warmUpConfigBackup); if (warmUpConfigBackupPutResult != null) { throw new IllegalStateException("WarmUpConfigBackupMap already contained key (" + solverBenchmarkResult + ") with value (" + warmUpConfigBackupPutResult + ")."); } } return warmUpConfigBackupMap; } } @Override public @NonNull File benchmarkAndShowReportInBrowser() { File benchmarkDirectoryPath = benchmark(); showReportInBrowser(); return benchmarkDirectoryPath; } private void showReportInBrowser() { File htmlOverviewFile = benchmarkReport.getHtmlOverviewFile(); Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; if (desktop == null || !desktop.isSupported(Desktop.Action.BROWSE)) { LOGGER.warn("The default browser can't be opened to show htmlOverviewFile ({}).", htmlOverviewFile); return; } try { desktop.browse(htmlOverviewFile.getAbsoluteFile().toURI()); } catch (IOException e) { throw new IllegalStateException("Failed showing htmlOverviewFile (" + htmlOverviewFile + ") in the default browser.", e); } } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/DefaultPlannerBenchmarkFactory.java
package ai.timefold.solver.benchmark.impl; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.regex.Pattern; import ai.timefold.solver.benchmark.api.PlannerBenchmark; import ai.timefold.solver.benchmark.api.PlannerBenchmarkFactory; import ai.timefold.solver.benchmark.config.PlannerBenchmarkConfig; import ai.timefold.solver.benchmark.config.SolverBenchmarkConfig; import ai.timefold.solver.benchmark.config.report.BenchmarkReportConfig; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.BenchmarkReportFactory; import ai.timefold.solver.benchmark.impl.result.PlannerBenchmarkResult; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.solver.thread.DefaultSolverThreadFactory; import org.jspecify.annotations.NonNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @see PlannerBenchmarkFactory */ public class DefaultPlannerBenchmarkFactory extends PlannerBenchmarkFactory { public static final Pattern VALID_NAME_PATTERN = Pattern.compile("(?U)^[\\w\\d _\\-\\.\\(\\)]+$"); private static final Logger LOGGER = LoggerFactory.getLogger(DefaultPlannerBenchmarkFactory.class); protected final PlannerBenchmarkConfig plannerBenchmarkConfig; public DefaultPlannerBenchmarkFactory(PlannerBenchmarkConfig plannerBenchmarkConfig) { if (plannerBenchmarkConfig == null) { throw new IllegalStateException("The plannerBenchmarkConfig (" + plannerBenchmarkConfig + ") cannot be null."); } this.plannerBenchmarkConfig = plannerBenchmarkConfig; } // ************************************************************************ // Worker methods // ************************************************************************ /** * @return never null */ @Override public @NonNull PlannerBenchmark buildPlannerBenchmark() { return buildPlannerBenchmark(new Object[0]); } @Override @SafeVarargs public final @NonNull <Solution_> PlannerBenchmark buildPlannerBenchmark(@NonNull Solution_ @NonNull... problems) { validate(); generateSolverBenchmarkConfigNames(); List<SolverBenchmarkConfig> effectiveSolverBenchmarkConfigList = buildEffectiveSolverBenchmarkConfigList(); PlannerBenchmarkResult plannerBenchmarkResult = new PlannerBenchmarkResult(); plannerBenchmarkResult.setName(plannerBenchmarkConfig.getName()); plannerBenchmarkResult.setAggregation(false); int parallelBenchmarkCount = resolveParallelBenchmarkCount(); plannerBenchmarkResult.setParallelBenchmarkCount(parallelBenchmarkCount); plannerBenchmarkResult.setWarmUpTimeMillisSpentLimit(calculateWarmUpTimeMillisSpentLimit(30L)); plannerBenchmarkResult.setUnifiedProblemBenchmarkResultList(new ArrayList<>()); plannerBenchmarkResult.setSolverBenchmarkResultList(new ArrayList<>(effectiveSolverBenchmarkConfigList.size())); for (SolverBenchmarkConfig solverBenchmarkConfig : effectiveSolverBenchmarkConfigList) { SolverBenchmarkFactory solverBenchmarkFactory = new SolverBenchmarkFactory(solverBenchmarkConfig); solverBenchmarkFactory.buildSolverBenchmark(plannerBenchmarkConfig.getClassLoader(), plannerBenchmarkResult, problems); } BenchmarkReportConfig benchmarkReportConfig_ = plannerBenchmarkConfig.getBenchmarkReportConfig() == null ? new BenchmarkReportConfig() : plannerBenchmarkConfig.getBenchmarkReportConfig(); BenchmarkReport benchmarkReport = new BenchmarkReportFactory(benchmarkReportConfig_).buildBenchmarkReport(plannerBenchmarkResult); return new DefaultPlannerBenchmark(plannerBenchmarkResult, plannerBenchmarkConfig.getBenchmarkDirectory(), buildExecutorService(parallelBenchmarkCount), buildExecutorService(parallelBenchmarkCount), benchmarkReport); } private ExecutorService buildExecutorService(int parallelBenchmarkCount) { return Executors.newFixedThreadPool(parallelBenchmarkCount, getThreadFactory()); } private ThreadFactory getThreadFactory() { var threadFactoryClass = plannerBenchmarkConfig.getThreadFactoryClass(); if (threadFactoryClass != null) { return ConfigUtils.newInstance(plannerBenchmarkConfig, "threadFactoryClass", threadFactoryClass); } else { return new DefaultSolverThreadFactory("BenchmarkThread"); } } protected void validate() { var name = plannerBenchmarkConfig.getName(); if (name != null) { if (!VALID_NAME_PATTERN.matcher(name).matches()) { throw new IllegalStateException( "The plannerBenchmark name (%s) is invalid because it does not follow the nameRegex (%s) which might cause an illegal filename." .formatted(name, VALID_NAME_PATTERN.pattern())); } if (!name.trim().equals(name)) { throw new IllegalStateException( "The plannerBenchmark name (%s) is invalid because it starts or ends with whitespace." .formatted(name)); } } if (ConfigUtils.isEmptyCollection(plannerBenchmarkConfig.getSolverBenchmarkBluePrintConfigList()) && ConfigUtils.isEmptyCollection(plannerBenchmarkConfig.getSolverBenchmarkConfigList())) { throw new IllegalArgumentException( "Configure at least 1 <solverBenchmark> (or 1 <solverBenchmarkBluePrint>) in the <plannerBenchmark> configuration."); } } protected void generateSolverBenchmarkConfigNames() { if (plannerBenchmarkConfig.getSolverBenchmarkConfigList() != null) { Set<String> nameSet = new HashSet<>(plannerBenchmarkConfig.getSolverBenchmarkConfigList().size()); Set<SolverBenchmarkConfig> noNameBenchmarkConfigSet = new LinkedHashSet<>(plannerBenchmarkConfig.getSolverBenchmarkConfigList().size()); for (SolverBenchmarkConfig solverBenchmarkConfig : plannerBenchmarkConfig.getSolverBenchmarkConfigList()) { if (solverBenchmarkConfig.getName() != null) { boolean unique = nameSet.add(solverBenchmarkConfig.getName()); if (!unique) { throw new IllegalStateException("The benchmark name (" + solverBenchmarkConfig.getName() + ") is used in more than 1 benchmark."); } } else { noNameBenchmarkConfigSet.add(solverBenchmarkConfig); } } int generatedNameIndex = 0; for (SolverBenchmarkConfig solverBenchmarkConfig : noNameBenchmarkConfigSet) { String generatedName = "Config_" + generatedNameIndex; while (nameSet.contains(generatedName)) { generatedNameIndex++; generatedName = "Config_" + generatedNameIndex; } solverBenchmarkConfig.setName(generatedName); generatedNameIndex++; } } } protected List<SolverBenchmarkConfig> buildEffectiveSolverBenchmarkConfigList() { var effectiveSolverBenchmarkConfigList = new ArrayList<SolverBenchmarkConfig>(0); var solverBenchmarkConfigList = plannerBenchmarkConfig.getSolverBenchmarkConfigList(); if (solverBenchmarkConfigList != null) { effectiveSolverBenchmarkConfigList.addAll(solverBenchmarkConfigList); } var solverBenchmarkBluePrintConfigList = plannerBenchmarkConfig.getSolverBenchmarkBluePrintConfigList(); if (solverBenchmarkBluePrintConfigList != null) { for (var solverBenchmarkBluePrintConfig : solverBenchmarkBluePrintConfigList) { effectiveSolverBenchmarkConfigList.addAll(solverBenchmarkBluePrintConfig.buildSolverBenchmarkConfigList()); } } var inheritedSolverBenchmarkConfig = plannerBenchmarkConfig.getInheritedSolverBenchmarkConfig(); if (inheritedSolverBenchmarkConfig != null) { for (var solverBenchmarkConfig : effectiveSolverBenchmarkConfigList) { // Side effect: changes the unmarshalled solverBenchmarkConfig solverBenchmarkConfig.inherit(inheritedSolverBenchmarkConfig); } } return effectiveSolverBenchmarkConfigList; } protected int resolveParallelBenchmarkCount() { var availableProcessorCount = Runtime.getRuntime().availableProcessors(); var resolvedParallelBenchmarkCount = actuallyResolverParallelBenchmarkCount(availableProcessorCount); if (resolvedParallelBenchmarkCount < 1) { throw new IllegalArgumentException( "The parallelBenchmarkCount (%s) resulted in a resolvedParallelBenchmarkCount (%d) that is lower than 1." .formatted(plannerBenchmarkConfig.getParallelBenchmarkCount(), resolvedParallelBenchmarkCount)); } if (resolvedParallelBenchmarkCount > availableProcessorCount) { LOGGER.warn("Because the resolvedParallelBenchmarkCount ({}) is higher " + "than the availableProcessorCount ({}), it is reduced to " + "availableProcessorCount.", resolvedParallelBenchmarkCount, availableProcessorCount); resolvedParallelBenchmarkCount = availableProcessorCount; } return resolvedParallelBenchmarkCount; } private int actuallyResolverParallelBenchmarkCount(int availableProcessorCount) { var parallelBenchmarkCount = plannerBenchmarkConfig.getParallelBenchmarkCount(); if (parallelBenchmarkCount == null) { return 1; } else if (parallelBenchmarkCount.equals(PlannerBenchmarkConfig.PARALLEL_BENCHMARK_COUNT_AUTO)) { return resolveParallelBenchmarkCountAutomatically(availableProcessorCount); } else { return ConfigUtils.resolvePoolSize("parallelBenchmarkCount", parallelBenchmarkCount, PlannerBenchmarkConfig.PARALLEL_BENCHMARK_COUNT_AUTO); } } protected int resolveParallelBenchmarkCountAutomatically(int availableProcessorCount) { // Tweaked based on experience if (availableProcessorCount <= 2) { return 1; } else if (availableProcessorCount <= 4) { return 2; } else { return (availableProcessorCount / 2) + 1; } } protected long calculateWarmUpTimeMillisSpentLimit(long defaultWarmUpTimeMillisSpentLimit) { if (plannerBenchmarkConfig.getWarmUpMillisecondsSpentLimit() == null && plannerBenchmarkConfig.getWarmUpSecondsSpentLimit() == null && plannerBenchmarkConfig.getWarmUpMinutesSpentLimit() == null && plannerBenchmarkConfig.getWarmUpHoursSpentLimit() == null && plannerBenchmarkConfig.getWarmUpDaysSpentLimit() == null) { return defaultWarmUpTimeMillisSpentLimit; } var warmUpTimeMillisSpentLimit = resolveLimit(plannerBenchmarkConfig.getWarmUpMillisecondsSpentLimit(), "warmUpMillisecondsSpentLimit"); warmUpTimeMillisSpentLimit += resolveLimit(plannerBenchmarkConfig.getWarmUpSecondsSpentLimit(), "warmUpSecondsSpentLimit") * 1_000L; warmUpTimeMillisSpentLimit += resolveLimit(plannerBenchmarkConfig.getWarmUpMinutesSpentLimit(), "warmUpMinutesSpentLimit") * 60_000L; warmUpTimeMillisSpentLimit += resolveLimit(plannerBenchmarkConfig.getWarmUpHoursSpentLimit(), "warmUpHoursSpentLimit") * 3_600_000L; return warmUpTimeMillisSpentLimit + resolveLimit(plannerBenchmarkConfig.getWarmUpDaysSpentLimit(), "warmUpDaysSpentLimit") * 86_400_000L; } private static long resolveLimit(Long limit, String limitName) { if (limit == null) { return 0L; } else if (limit < 0L) { throw new IllegalArgumentException("The %s (%d) cannot be negative.".formatted(limitName, limit)); } return limit; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/ProblemBenchmarksFactory.java
package ai.timefold.solver.benchmark.impl; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import ai.timefold.solver.benchmark.api.PlannerBenchmarkFactory; import ai.timefold.solver.benchmark.config.ProblemBenchmarksConfig; import ai.timefold.solver.benchmark.config.statistic.SingleStatisticType; import ai.timefold.solver.benchmark.impl.loader.FileProblemProvider; import ai.timefold.solver.benchmark.impl.loader.InstanceProblemProvider; import ai.timefold.solver.benchmark.impl.loader.ProblemProvider; import ai.timefold.solver.benchmark.impl.result.PlannerBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.ProblemBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SolverBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemStatistic; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; import ai.timefold.solver.core.impl.solver.DefaultSolverFactory; import ai.timefold.solver.persistence.common.api.domain.solution.SolutionFileIO; public class ProblemBenchmarksFactory { private final ProblemBenchmarksConfig config; public ProblemBenchmarksFactory(ProblemBenchmarksConfig config) { this.config = config; } @SuppressWarnings({ "rawtypes", "unchecked" }) public <Solution_> void buildProblemBenchmarkList(SolverBenchmarkResult solverBenchmarkResult, Solution_[] extraProblems) { PlannerBenchmarkResult plannerBenchmarkResult = solverBenchmarkResult.getPlannerBenchmarkResult(); List<ProblemBenchmarkResult> unifiedProblemBenchmarkResultList = plannerBenchmarkResult .getUnifiedProblemBenchmarkResultList(); for (ProblemProvider<Solution_> problemProvider : buildProblemProviderList( solverBenchmarkResult, extraProblems)) { // 2 SolverBenchmarks containing equal ProblemBenchmarks should contain the same instance ProblemBenchmarkResult<Solution_> newProblemBenchmarkResult = buildProblemBenchmark( plannerBenchmarkResult, problemProvider); ProblemBenchmarkResult<Solution_> problemBenchmarkResult; int index = unifiedProblemBenchmarkResultList.indexOf(newProblemBenchmarkResult); if (index < 0) { problemBenchmarkResult = newProblemBenchmarkResult; unifiedProblemBenchmarkResultList.add(problemBenchmarkResult); } else { problemBenchmarkResult = unifiedProblemBenchmarkResultList.get(index); } buildSingleBenchmark(solverBenchmarkResult, problemBenchmarkResult); } } private <Solution_> List<ProblemProvider<Solution_>> buildProblemProviderList( SolverBenchmarkResult solverBenchmarkResult, Solution_[] extraProblems) { if (ConfigUtils.isEmptyCollection(config.getInputSolutionFileList()) && extraProblems.length == 0) { throw new IllegalArgumentException( "The solverBenchmarkResult (" + solverBenchmarkResult.getName() + ") has no problems.\n" + "Maybe configure at least 1 <inputSolutionFile> directly or indirectly by inheriting it.\n" + "Or maybe pass at least one problem to " + PlannerBenchmarkFactory.class.getSimpleName() + ".buildPlannerBenchmark()."); } List<ProblemProvider<Solution_>> problemProviderList = new ArrayList<>(extraProblems.length + Objects.requireNonNullElse(config.getInputSolutionFileList(), Collections.emptyList()).size()); DefaultSolverFactory<Solution_> defaultSolverFactory = new DefaultSolverFactory<>(solverBenchmarkResult.getSolverConfig()); SolutionDescriptor<Solution_> solutionDescriptor = defaultSolverFactory.getSolutionDescriptor(); int extraProblemIndex = 0; for (Solution_ extraProblem : extraProblems) { if (extraProblem == null) { throw new IllegalStateException("The benchmark problem (" + extraProblem + ") is null."); } String problemName = "Problem_" + extraProblemIndex; problemProviderList.add(new InstanceProblemProvider<>(problemName, solutionDescriptor, extraProblem)); extraProblemIndex++; } if (ConfigUtils.isEmptyCollection(config.getInputSolutionFileList())) { if (config.getSolutionFileIOClass() != null) { throw new IllegalArgumentException("Cannot use solutionFileIOClass (" + config.getSolutionFileIOClass() + ") with an empty inputSolutionFileList (" + config.getInputSolutionFileList() + ")."); } } else { SolutionFileIO<Solution_> solutionFileIO = buildSolutionFileIO(); for (File inputSolutionFile : config.getInputSolutionFileList()) { if (!inputSolutionFile.exists()) { throw new IllegalArgumentException("The inputSolutionFile (" + inputSolutionFile + ") does not exist."); } problemProviderList.add(new FileProblemProvider<>(solutionFileIO, inputSolutionFile)); } } return problemProviderList; } @SuppressWarnings("unchecked") private <Solution_> SolutionFileIO<Solution_> buildSolutionFileIO() { var solutionFileIOClass = config.getSolutionFileIOClass(); if (solutionFileIOClass == null) { throw new IllegalArgumentException("The solutionFileIOClass cannot be null."); } return (SolutionFileIO<Solution_>) ConfigUtils.newInstance(config, "solutionFileIOClass", solutionFileIOClass); } @SuppressWarnings("rawtypes") private <Solution_> ProblemBenchmarkResult<Solution_> buildProblemBenchmark(PlannerBenchmarkResult plannerBenchmarkResult, ProblemProvider<Solution_> problemProvider) { ProblemBenchmarkResult<Solution_> problemBenchmarkResult = new ProblemBenchmarkResult<>(plannerBenchmarkResult); problemBenchmarkResult.setName(problemProvider.getProblemName()); problemBenchmarkResult.setProblemProvider(problemProvider); problemBenchmarkResult .setWriteOutputSolutionEnabled(Objects.requireNonNullElse(config.getWriteOutputSolutionEnabled(), false)); List<ProblemStatistic> problemStatisticList = getProblemStatisticList(problemBenchmarkResult); problemBenchmarkResult.setProblemStatisticList(problemStatisticList); problemBenchmarkResult.setSingleBenchmarkResultList(new ArrayList<>()); return problemBenchmarkResult; } @SuppressWarnings("rawtypes") private List<ProblemStatistic> getProblemStatisticList(ProblemBenchmarkResult problemBenchmarkResult) { var problemStatisticEnabled = config.getProblemStatisticEnabled(); if (problemStatisticEnabled != null && !problemStatisticEnabled) { if (!ConfigUtils.isEmptyCollection(config.getProblemStatisticTypeList())) { throw new IllegalArgumentException( "The problemStatisticEnabled (%b) and problemStatisticTypeList (%s) cannot be used together." .formatted(problemStatisticEnabled, config.getProblemStatisticTypeList())); } return Collections.emptyList(); } else { return config.determineProblemStatisticTypeList().stream() .map(problemStatisticType -> problemStatisticType.buildProblemStatistic(problemBenchmarkResult)) .toList(); } } @SuppressWarnings({ "rawtypes", "unchecked" }) private void buildSingleBenchmark(SolverBenchmarkResult solverBenchmarkResult, ProblemBenchmarkResult problemBenchmarkResult) { SingleBenchmarkResult singleBenchmarkResult = new SingleBenchmarkResult(solverBenchmarkResult, problemBenchmarkResult); buildSubSingleBenchmarks(singleBenchmarkResult, solverBenchmarkResult.getSubSingleCount()); List<SingleStatisticType> singleStatisticTypeList = config.determineSingleStatisticTypeList(); for (SubSingleBenchmarkResult subSingleBenchmarkResult : singleBenchmarkResult.getSubSingleBenchmarkResultList()) { subSingleBenchmarkResult.setPureSubSingleStatisticList(new ArrayList<>(singleStatisticTypeList.size())); } for (SingleStatisticType singleStatisticType : singleStatisticTypeList) { for (SubSingleBenchmarkResult subSingleBenchmarkResult : singleBenchmarkResult .getSubSingleBenchmarkResultList()) { subSingleBenchmarkResult.getPureSubSingleStatisticList().add( singleStatisticType.buildPureSubSingleStatistic(subSingleBenchmarkResult)); } } singleBenchmarkResult.initSubSingleStatisticMaps(); solverBenchmarkResult.getSingleBenchmarkResultList().add(singleBenchmarkResult); problemBenchmarkResult.getSingleBenchmarkResultList().add(singleBenchmarkResult); } private void buildSubSingleBenchmarks(SingleBenchmarkResult parent, int subSingleCount) { List<SubSingleBenchmarkResult> subSingleBenchmarkResultList = new ArrayList<>(subSingleCount); for (int i = 0; i < subSingleCount; i++) { SubSingleBenchmarkResult subSingleBenchmarkResult = new SubSingleBenchmarkResult(parent, i); subSingleBenchmarkResultList.add(subSingleBenchmarkResult); } parent.setSubSingleBenchmarkResultList(subSingleBenchmarkResultList); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/SolverBenchmarkFactory.java
package ai.timefold.solver.benchmark.impl; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import ai.timefold.solver.benchmark.config.ProblemBenchmarksConfig; import ai.timefold.solver.benchmark.config.SolverBenchmarkConfig; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.config.statistic.SingleStatisticType; import ai.timefold.solver.benchmark.impl.result.PlannerBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SolverBenchmarkResult; import ai.timefold.solver.core.config.solver.SolverConfig; import ai.timefold.solver.core.config.solver.monitoring.MonitoringConfig; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.solver.DefaultSolverFactory; public class SolverBenchmarkFactory { private final SolverBenchmarkConfig config; public SolverBenchmarkFactory(SolverBenchmarkConfig config) { this.config = config; } public <Solution_> void buildSolverBenchmark(ClassLoader classLoader, PlannerBenchmarkResult plannerBenchmark, Solution_[] extraProblems) { validate(); var solverBenchmarkResult = new SolverBenchmarkResult(plannerBenchmark); solverBenchmarkResult.setName(config.getName()); solverBenchmarkResult.setSubSingleCount(ConfigUtils.inheritOverwritableProperty(config.getSubSingleCount(), 1)); var solverConfig = Objects.requireNonNullElseGet(config.getSolverConfig(), SolverConfig::new); if (solverConfig.getClassLoader() == null) { solverConfig.setClassLoader(classLoader); } var monitoringConfig = solverConfig.getMonitoringConfig(); var monitoringSolverMetricList = monitoringConfig == null ? Collections.<SolverMetric> emptyList() : monitoringConfig.getSolverMetricList(); if (monitoringConfig != null && monitoringSolverMetricList != null && !monitoringSolverMetricList.isEmpty()) { throw new IllegalArgumentException("The solverBenchmarkConfig (%s) has a %s (%s) with a non-empty %s (%s)." .formatted(config, SolverConfig.class.getSimpleName(), solverConfig, MonitoringConfig.class.getSimpleName(), monitoringConfig)); } var solverMetricList = getSolverMetrics(config.getProblemBenchmarksConfig()); solverBenchmarkResult.setSolverConfig( solverConfig.copyConfig().withMonitoringConfig(new MonitoringConfig().withSolverMetricList(solverMetricList))); var defaultSolverFactory = new DefaultSolverFactory<Solution_>(solverConfig); var solutionDescriptor = defaultSolverFactory.getSolutionDescriptor(); for (var extraProblem : extraProblems) { if (!solutionDescriptor.getSolutionClass().isInstance(extraProblem)) { throw new IllegalArgumentException( "The solverBenchmark name (%s) for solution class (%s) cannot solve a problem (%s) of class (%s)." .formatted(config.getName(), solutionDescriptor.getSolutionClass(), extraProblem, extraProblem == null ? null : extraProblem.getClass())); } } solverBenchmarkResult.setScoreDefinition(solutionDescriptor.getScoreDefinition()); solverBenchmarkResult.setSingleBenchmarkResultList(new ArrayList<>()); var problemBenchmarksConfig = Objects.requireNonNullElseGet(config.getProblemBenchmarksConfig(), ProblemBenchmarksConfig::new); plannerBenchmark.getSolverBenchmarkResultList().add(solverBenchmarkResult); var problemBenchmarksFactory = new ProblemBenchmarksFactory(problemBenchmarksConfig); problemBenchmarksFactory.buildProblemBenchmarkList(solverBenchmarkResult, extraProblems); } protected void validate() { var configName = config.getName(); if (configName == null || !DefaultPlannerBenchmarkFactory.VALID_NAME_PATTERN.matcher(configName).matches()) { throw new IllegalStateException( "The solverBenchmark name (%s) is invalid because it does not follow the nameRegex (%s) which might cause an illegal filename." .formatted(configName, DefaultPlannerBenchmarkFactory.VALID_NAME_PATTERN.pattern())); } if (!configName.trim().equals(configName)) { throw new IllegalStateException( "The solverBenchmark name (%s) is invalid because it starts or ends with whitespace." .formatted(configName)); } var subSingleCount = config.getSubSingleCount(); if (subSingleCount != null && subSingleCount < 1) { throw new IllegalStateException( "The solverBenchmark name (%s) is invalid because the subSingleCount (%d) must be greater than 1." .formatted(configName, subSingleCount)); } } protected List<SolverMetric> getSolverMetrics(ProblemBenchmarksConfig config) { List<SolverMetric> out = new ArrayList<>(); for (ProblemStatisticType problemStatisticType : Optional.ofNullable(config) .map(ProblemBenchmarksConfig::determineProblemStatisticTypeList) .orElseGet(ProblemStatisticType::defaultList)) { if (problemStatisticType == ProblemStatisticType.SCORE_CALCULATION_SPEED) { out.add(SolverMetric.SCORE_CALCULATION_COUNT); } else if (problemStatisticType == ProblemStatisticType.MOVE_EVALUATION_SPEED) { out.add(SolverMetric.MOVE_EVALUATION_COUNT); } else { out.add(SolverMetric.valueOf(problemStatisticType.name())); } } for (SingleStatisticType singleStatisticType : Optional.ofNullable(config) .map(ProblemBenchmarksConfig::determineSingleStatisticTypeList) .orElseGet(Collections::emptyList)) { out.add(SolverMetric.valueOf(singleStatisticType.name())); } return out; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/SubSingleBenchmarkRunner.java
package ai.timefold.solver.benchmark.impl; import java.util.HashMap; import java.util.UUID; import java.util.concurrent.Callable; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.StatisticRegistry; import ai.timefold.solver.core.api.solver.SolutionManager; import ai.timefold.solver.core.api.solver.SolutionUpdatePolicy; import ai.timefold.solver.core.config.solver.SolverConfig; import ai.timefold.solver.core.impl.solver.DefaultSolver; import ai.timefold.solver.core.impl.solver.DefaultSolverFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.Tags; public class SubSingleBenchmarkRunner<Solution_> implements Callable<SubSingleBenchmarkRunner<Solution_>> { public static final String NAME_MDC = "subSingleBenchmark.name"; private static final Logger LOGGER = LoggerFactory.getLogger(SubSingleBenchmarkRunner.class); private final SubSingleBenchmarkResult subSingleBenchmarkResult; private final boolean warmUp; private Long randomSeed = null; private Throwable failureThrowable = null; /** * @param subSingleBenchmarkResult never null */ public SubSingleBenchmarkRunner(SubSingleBenchmarkResult subSingleBenchmarkResult, boolean warmUp) { this.subSingleBenchmarkResult = subSingleBenchmarkResult; this.warmUp = warmUp; } public SubSingleBenchmarkResult getSubSingleBenchmarkResult() { return subSingleBenchmarkResult; } public Long getRandomSeed() { return randomSeed; } public Throwable getFailureThrowable() { return failureThrowable; } public void setFailureThrowable(Throwable failureThrowable) { this.failureThrowable = failureThrowable; } // ************************************************************************ // Benchmark methods // ************************************************************************ @Override public SubSingleBenchmarkRunner<Solution_> call() { MDC.put(NAME_MDC, subSingleBenchmarkResult.getName()); var runtime = Runtime.getRuntime(); var singleBenchmarkResult = subSingleBenchmarkResult.getSingleBenchmarkResult(); var problemBenchmarkResult = singleBenchmarkResult.getProblemBenchmarkResult(); var problem = (Solution_) problemBenchmarkResult.readProblem(); if (!problemBenchmarkResult.getPlannerBenchmarkResult().hasMultipleParallelBenchmarks()) { runtime.gc(); subSingleBenchmarkResult.setUsedMemoryAfterInputSolution(runtime.totalMemory() - runtime.freeMemory()); } LOGGER.trace("Benchmark problem has been read for subSingleBenchmarkResult ({}).", subSingleBenchmarkResult); var solverConfig = singleBenchmarkResult.getSolverBenchmarkResult() .getSolverConfig(); if (singleBenchmarkResult.getSubSingleCount() > 1) { solverConfig = new SolverConfig(solverConfig); solverConfig.offerRandomSeedFromSubSingleIndex(subSingleBenchmarkResult.getSubSingleBenchmarkIndex()); } var subSingleBenchmarkTagMap = new HashMap<String, String>(); var runId = UUID.randomUUID().toString(); subSingleBenchmarkTagMap.put("timefold.benchmark.run", runId); solverConfig = new SolverConfig(solverConfig); randomSeed = solverConfig.getRandomSeed(); // Defensive copy of solverConfig for every SingleBenchmarkResult to reset Random, tabu lists, ... var solverFactory = new DefaultSolverFactory<Solution_>(new SolverConfig(solverConfig)); // Register metrics var statisticRegistry = new StatisticRegistry<Solution_>(solverFactory.getSolutionDescriptor().getScoreDefinition()); Metrics.addRegistry(statisticRegistry); var runTag = Tags.of("timefold.benchmark.run", runId); subSingleBenchmarkResult.getEffectiveSubSingleStatisticMap().forEach((statisticType, subSingleStatistic) -> { subSingleStatistic.open(statisticRegistry, runTag); subSingleStatistic.initPointList(); }); var solver = (DefaultSolver<Solution_>) solverFactory.buildSolver(); solver.setMonitorTagMap(subSingleBenchmarkTagMap); solver.addPhaseLifecycleListener(statisticRegistry); var solution = solver.solve(problem); solver.removePhaseLifecycleListener(statisticRegistry); Metrics.removeRegistry(statisticRegistry); var timeMillisSpent = solver.getTimeMillisSpent(); for (var subSingleStatistic : subSingleBenchmarkResult.getEffectiveSubSingleStatisticMap().values()) { subSingleStatistic.close(statisticRegistry, runTag); subSingleStatistic.hibernatePointList(); } if (!warmUp) { var solverScope = solver.getSolverScope(); var solutionDescriptor = solverScope.getSolutionDescriptor(); problemBenchmarkResult.registerProblemSizeStatistics(solverScope.getProblemSizeStatistics()); subSingleBenchmarkResult.setScore(solutionDescriptor.getScore(solution), solverScope.isBestSolutionInitialized()); subSingleBenchmarkResult.setTimeMillisSpent(timeMillisSpent); subSingleBenchmarkResult.setScoreCalculationCount(solverScope.getScoreCalculationCount()); subSingleBenchmarkResult.setMoveEvaluationCount(solverScope.getMoveEvaluationCount()); var solutionManager = SolutionManager.create(solverFactory); var isConstraintMatchEnabled = solver.getSolverScope().getScoreDirector().getConstraintMatchPolicy() .isEnabled(); if (isConstraintMatchEnabled) { // Easy calculator fails otherwise. var scoreExplanation = solutionManager.explain(solution, SolutionUpdatePolicy.NO_UPDATE); subSingleBenchmarkResult.setScoreExplanationSummary(scoreExplanation.getSummary()); } problemBenchmarkResult.writeSolution(subSingleBenchmarkResult, solution); } MDC.remove(NAME_MDC); return this; } public String getName() { return subSingleBenchmarkResult.getName(); } @Override public String toString() { return subSingleBenchmarkResult.toString(); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/package-info.java
/** * Implementation classes of Timefold Benchmark. * <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://docs.timefold.ai/timefold-solver/latest/upgrading-timefold-solver/upgrade-to-latest-version">the upgrade * recipe</a>. */ package ai.timefold.solver.benchmark.impl;
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/aggregator/BenchmarkAggregator.java
package ai.timefold.solver.benchmark.impl.aggregator; import java.awt.Desktop; import java.awt.Desktop.Action; import java.io.File; import java.io.IOException; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import ai.timefold.solver.benchmark.config.PlannerBenchmarkConfig; import ai.timefold.solver.benchmark.config.report.BenchmarkReportConfig; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.BenchmarkReportFactory; import ai.timefold.solver.benchmark.impl.result.BenchmarkResultIO; import ai.timefold.solver.benchmark.impl.result.PlannerBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SolverBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BenchmarkAggregator { private static final Logger LOGGER = LoggerFactory.getLogger(BenchmarkAggregator.class); private File benchmarkDirectory = null; private BenchmarkReportConfig benchmarkReportConfig = null; private BenchmarkReport benchmarkReport = null; public File getBenchmarkDirectory() { return benchmarkDirectory; } public void setBenchmarkDirectory(File benchmarkDirectory) { this.benchmarkDirectory = benchmarkDirectory; } public BenchmarkReportConfig getBenchmarkReportConfig() { return benchmarkReportConfig; } public void setBenchmarkReportConfig(BenchmarkReportConfig benchmarkReportConfig) { this.benchmarkReportConfig = benchmarkReportConfig; } public BenchmarkReport getBenchmarkReport() { return benchmarkReport; } public void setBenchmarkReport(BenchmarkReport benchmarkReport) { this.benchmarkReport = benchmarkReport; } // ************************************************************************ // Aggregate methods // ************************************************************************ public File aggregateBenchmarks(PlannerBenchmarkConfig benchmarkConfig) { File benchmarkDirectory = benchmarkConfig.getBenchmarkDirectory(); if (!benchmarkDirectory.exists() || !benchmarkDirectory.isDirectory()) { throw new IllegalArgumentException("Benchmark directory does not exist: %s".formatted(benchmarkDirectory)); } // Read all existing benchmark results from the directory BenchmarkResultIO benchmarkResultIO = new BenchmarkResultIO(); List<PlannerBenchmarkResult> plannerBenchmarkResults = benchmarkResultIO.readPlannerBenchmarkResultList(benchmarkDirectory); if (plannerBenchmarkResults.isEmpty()) { throw new IllegalArgumentException("No benchmark results found in directory: %s".formatted(benchmarkDirectory)); } // Collect all single benchmark results and preserve solver names List<SingleBenchmarkResult> allSingleBenchmarkResults = new ArrayList<>(); Map<SolverBenchmarkResult, String> solverBenchmarkResultNameMap = new HashMap<>(); for (PlannerBenchmarkResult plannerResult : plannerBenchmarkResults) { for (SolverBenchmarkResult solverResult : plannerResult.getSolverBenchmarkResultList()) { allSingleBenchmarkResults.addAll(solverResult.getSingleBenchmarkResultList()); solverBenchmarkResultNameMap.put(solverResult, solverResult.getName()); } } // Configure the aggregator instance this.setBenchmarkDirectory(benchmarkDirectory); this.setBenchmarkReportConfig(benchmarkConfig.getBenchmarkReportConfig()); // Perform the aggregation - returns HTML report file return this.aggregate(allSingleBenchmarkResults, solverBenchmarkResultNameMap); } public File aggregateSelectedBenchmarksInUi(List<SingleBenchmarkResult> selectedSingleBenchmarkResults, Map<SolverBenchmarkResult, String> solverBenchmarkResultNameMap) { return this.aggregate(selectedSingleBenchmarkResults, solverBenchmarkResultNameMap); } public File aggregateSelectedBenchmarks(PlannerBenchmarkConfig benchmarkConfig, List<String> selectedDirectoryNames) { File benchmarkDirectory = benchmarkConfig.getBenchmarkDirectory(); if (!benchmarkDirectory.exists() || !benchmarkDirectory.isDirectory()) { throw new IllegalArgumentException("No benchmark results found in directory: %s".formatted(benchmarkDirectory)); } // Read all benchmark results first, then filter BenchmarkResultIO benchmarkResultIO = new BenchmarkResultIO(); List<PlannerBenchmarkResult> allPlannerResults = benchmarkResultIO.readPlannerBenchmarkResultList(benchmarkDirectory); List<SingleBenchmarkResult> selectedSingleBenchmarkResults = new ArrayList<>(); Map<SolverBenchmarkResult, String> solverBenchmarkResultNameMap = new HashMap<>(); // Filter results based on selected directory names for (PlannerBenchmarkResult plannerResult : allPlannerResults) { String benchmarkDirectoryName = plannerResult.getBenchmarkReportDirectory().getName(); if (selectedDirectoryNames.contains(benchmarkDirectoryName)) { LOGGER.info("Including benchmark results from directory: {}", benchmarkDirectoryName); for (SolverBenchmarkResult solverResult : plannerResult.getSolverBenchmarkResultList()) { selectedSingleBenchmarkResults.addAll(solverResult.getSingleBenchmarkResultList()); solverBenchmarkResultNameMap.put(solverResult, solverResult.getName()); } } } if (selectedSingleBenchmarkResults.isEmpty()) { throw new IllegalArgumentException("No valid benchmark results found in the selected directories: %s" .formatted(selectedDirectoryNames)); } // Configure the aggregator instance this.setBenchmarkDirectory(benchmarkDirectory); this.setBenchmarkReportConfig(benchmarkConfig.getBenchmarkReportConfig()); // Perform the aggregation with selected results - returns HTML report file return this.aggregate(selectedSingleBenchmarkResults, solverBenchmarkResultNameMap); } public List<String> getAvailableBenchmarkDirectories(PlannerBenchmarkConfig benchmarkConfig) { File benchmarkDirectory = benchmarkConfig.getBenchmarkDirectory(); if (!benchmarkDirectory.exists() || !benchmarkDirectory.isDirectory()) { return Collections.emptyList(); } List<String> directories = new ArrayList<>(); File[] subdirs = benchmarkDirectory.listFiles(File::isDirectory); if (subdirs != null) { for (File subdir : subdirs) { // Only include directories that have a benchmark result file File resultFile = new File(subdir, "plannerBenchmarkResult.xml"); if (resultFile.exists()) { directories.add(subdir.getName()); } } } return directories; } public File aggregateAndShowReportInBrowser(PlannerBenchmarkConfig benchmarkConfig) { File benchmarkDirectoryPath = this.aggregateBenchmarks(benchmarkConfig); this.showReportInBrowser(); return benchmarkDirectoryPath; } private void showReportInBrowser() { if (this.benchmarkReport == null) { throw new IllegalStateException("No benchmark report available. Run aggregation first."); } File htmlOverviewFile = this.benchmarkReport.getHtmlOverviewFile(); Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; if (desktop != null && desktop.isSupported(Action.BROWSE)) { try { desktop.browse(htmlOverviewFile.getAbsoluteFile().toURI()); } catch (IOException e) { throw new IllegalStateException( "Failed showing htmlOverviewFile (%s) in the default browser.".formatted(htmlOverviewFile), e); } } else { LOGGER.warn("The default browser can't be opened to show htmlOverviewFile ({}).", htmlOverviewFile); } } private File aggregate(List<SingleBenchmarkResult> singleBenchmarkResultList, Map<SolverBenchmarkResult, String> solverBenchmarkResultNameMap) { if (benchmarkDirectory == null) { throw new IllegalArgumentException( "The benchmarkReportConfig (%s) must not be null.".formatted(benchmarkReportConfig)); } if (!benchmarkDirectory.exists()) { throw new IllegalArgumentException("The benchmarkDirectory (" + benchmarkDirectory + ") must exist."); } if (benchmarkReportConfig == null) { throw new IllegalArgumentException("The benchmarkDirectory (%s) must exist.".formatted(benchmarkDirectory)); } if (singleBenchmarkResultList.isEmpty()) { throw new IllegalArgumentException( "The singleBenchmarkResultList (%s) must not be empty.".formatted(singleBenchmarkResultList)); } OffsetDateTime startingTimestamp = OffsetDateTime.now(); for (SingleBenchmarkResult singleBenchmarkResult : singleBenchmarkResultList) { for (SubSingleBenchmarkResult subSingleBenchmarkResult : singleBenchmarkResult.getSubSingleBenchmarkResultList()) { subSingleBenchmarkResult.setSingleBenchmarkResult(singleBenchmarkResult); } singleBenchmarkResult.initSubSingleStatisticMaps(); } // Handle renamed solver benchmarks after statistics have been read (they're resolved by // original solver benchmarks' names) if (solverBenchmarkResultNameMap != null) { for (Entry<SolverBenchmarkResult, String> entry : solverBenchmarkResultNameMap.entrySet()) { SolverBenchmarkResult result = entry.getKey(); String newName = entry.getValue(); if (!result.getName().equals(newName)) { result.setName(newName); } } } PlannerBenchmarkResult plannerBenchmarkResult = PlannerBenchmarkResult.createMergedResult( singleBenchmarkResultList); plannerBenchmarkResult.setStartingTimestamp(startingTimestamp); plannerBenchmarkResult.initBenchmarkReportDirectory(benchmarkDirectory); BenchmarkReportFactory benchmarkReportFactory = new BenchmarkReportFactory(benchmarkReportConfig); BenchmarkReport benchmarkReport = benchmarkReportFactory.buildBenchmarkReport(plannerBenchmarkResult); plannerBenchmarkResult.accumulateResults(benchmarkReport); benchmarkReport.writeReport(); // Store the benchmark report for potential browser viewing this.benchmarkReport = benchmarkReport; LOGGER.info("Aggregation ended: statistic html overview ({}).", benchmarkReport.getHtmlOverviewFile().getAbsolutePath()); return benchmarkReport.getHtmlOverviewFile().getAbsoluteFile(); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/aggregator
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/aggregator/swingui/BenchmarkAggregatorFrame.java
package ai.timefold.solver.benchmark.impl.aggregator.swingui; import java.awt.BorderLayout; import java.awt.Desktop; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.ExecutionException; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.SwingWorker; import javax.swing.WindowConstants; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import ai.timefold.solver.benchmark.api.PlannerBenchmarkFactory; import ai.timefold.solver.benchmark.config.PlannerBenchmarkConfig; import ai.timefold.solver.benchmark.config.report.BenchmarkReportConfig; import ai.timefold.solver.benchmark.impl.aggregator.BenchmarkAggregator; import ai.timefold.solver.benchmark.impl.aggregator.swingui.MixedCheckBox.MixedCheckBoxStatus; import ai.timefold.solver.benchmark.impl.report.BenchmarkReportFactory; import ai.timefold.solver.benchmark.impl.result.BenchmarkResultIO; import ai.timefold.solver.benchmark.impl.result.PlannerBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.ProblemBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SolverBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.common.MillisecondsSpentNumberFormat; import ai.timefold.solver.swing.impl.SwingUncaughtExceptionHandler; import ai.timefold.solver.swing.impl.SwingUtils; public class BenchmarkAggregatorFrame extends JFrame { /** * Reads an XML benchmark configuration from the classpath * and uses that {@link PlannerBenchmarkConfig} to do an aggregation. * * @param benchmarkConfigResource never null, same one as in {@link PlannerBenchmarkFactory#createFromXmlResource(String)} */ public static void createAndDisplayFromXmlResource(String benchmarkConfigResource) { PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromXmlResource(benchmarkConfigResource); createAndDisplay(benchmarkConfig); } /** * Reads an Freemarker template from the classpath that generates an XML benchmark configuration * and uses that {@link PlannerBenchmarkConfig} to do an aggregation. * * @param templateResource never null, same one as in * {@link PlannerBenchmarkFactory#createFromFreemarkerXmlResource(String)} */ public static void createAndDisplayFromFreemarkerXmlResource(String templateResource) { PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlResource(templateResource); createAndDisplay(benchmarkConfig); } /** * Uses a {@link PlannerBenchmarkConfig} to do an aggregation. * * @param benchmarkConfig never null */ public static void createAndDisplay(PlannerBenchmarkConfig benchmarkConfig) { SwingUncaughtExceptionHandler.register(); SwingUtils.fixateLookAndFeel(); BenchmarkAggregator benchmarkAggregator = new BenchmarkAggregator(); benchmarkAggregator.setBenchmarkDirectory(benchmarkConfig.getBenchmarkDirectory()); BenchmarkReportConfig benchmarkReportConfig = benchmarkConfig.getBenchmarkReportConfig(); if (benchmarkReportConfig != null) { // Defensive copy benchmarkReportConfig = new BenchmarkReportConfig(benchmarkReportConfig); } else { benchmarkReportConfig = new BenchmarkReportConfig(); } benchmarkAggregator.setBenchmarkReportConfig(benchmarkReportConfig); BenchmarkAggregatorFrame benchmarkAggregatorFrame = new BenchmarkAggregatorFrame(benchmarkAggregator); benchmarkAggregatorFrame.init(); benchmarkAggregatorFrame.setVisible(true); } private final BenchmarkAggregator benchmarkAggregator; private final BenchmarkResultIO benchmarkResultIO; private final MillisecondsSpentNumberFormat millisecondsSpentNumberFormat; private List<PlannerBenchmarkResult> plannerBenchmarkResultList; private Map<SingleBenchmarkResult, DefaultMutableTreeNode> resultCheckBoxMapping = new LinkedHashMap<>(); private Map<SolverBenchmarkResult, String> solverBenchmarkResultNameMapping = new HashMap<>(); private CheckBoxTree checkBoxTree; private JTextArea detailTextArea; private JProgressBar generateProgressBar; private JButton generateReportButton; private JButton renameNodeButton; private boolean exitApplicationWhenReportFinished = true; public BenchmarkAggregatorFrame(BenchmarkAggregator benchmarkAggregator) { super("Benchmark aggregator"); this.benchmarkAggregator = benchmarkAggregator; benchmarkResultIO = new BenchmarkResultIO(); plannerBenchmarkResultList = Collections.emptyList(); Locale locale = benchmarkAggregator.getBenchmarkReportConfig().determineLocale(); millisecondsSpentNumberFormat = new MillisecondsSpentNumberFormat(locale); } public void init() { setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); initPlannerBenchmarkResultList(); setContentPane(createContentPane()); pack(); setLocationRelativeTo(null); } private JComponent createContentPane() { JPanel contentPane = new JPanel(new BorderLayout()); contentPane.add(createTopButtonPanel(), BorderLayout.NORTH); contentPane.add(createBenchmarkTreePanel(), BorderLayout.CENTER); contentPane.add(createDetailTextArea(), BorderLayout.SOUTH); return contentPane; } private JComponent createNoPlannerFoundTextField() { String infoMessage = "No planner benchmarks have been found in the benchmarkDirectory (" + benchmarkAggregator.getBenchmarkDirectory() + ")."; JTextPane textPane = new JTextPane(); textPane.setEditable(false); textPane.setText(infoMessage); // center info message StyledDocument styledDocument = textPane.getStyledDocument(); SimpleAttributeSet center = new SimpleAttributeSet(); StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER); StyleConstants.setBold(center, true); styledDocument.setParagraphAttributes(0, styledDocument.getLength(), center, false); return textPane; } private JComponent createDetailTextArea() { JPanel detailPanel = new JPanel(new BorderLayout()); JLabel detailLabel = new JLabel("Details"); detailPanel.add(detailLabel, BorderLayout.NORTH); detailTextArea = new JTextArea(5, 80); detailTextArea.setEditable(false); JScrollPane detailScrollPane = new JScrollPane(detailTextArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); detailPanel.add(detailScrollPane, BorderLayout.SOUTH); return detailPanel; } private JComponent createTopButtonPanel() { JPanel buttonPanel = new JPanel(new GridLayout(1, 6)); buttonPanel.add(new JButton(new ExpandNodesAction())); buttonPanel.add(new JButton(new CollapseNodesAction())); buttonPanel.add(new JButton(new MoveNodeAction(true))); buttonPanel.add(new JButton(new MoveNodeAction(false))); renameNodeButton = new JButton(new RenameNodeAction()); renameNodeButton.setEnabled(false); buttonPanel.add(renameNodeButton); buttonPanel.add(new JButton(new SwitchLevelsAction(false))); return buttonPanel; } private JComponent createBenchmarkTreePanel() { JPanel benchmarkTreePanel = new JPanel(new BorderLayout()); benchmarkTreePanel.add( new JScrollPane(plannerBenchmarkResultList.isEmpty() ? createNoPlannerFoundTextField() : createCheckBoxTree(), JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER); JPanel buttonPanelWrapper = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 10, 0)); generateReportButton = new JButton(new GenerateReportAction(this)); generateReportButton.setEnabled(false); buttonPanel.add(generateReportButton); generateProgressBar = new JProgressBar(); buttonPanel.add(generateProgressBar); buttonPanelWrapper.add(buttonPanel); benchmarkTreePanel.add(buttonPanelWrapper, BorderLayout.SOUTH); benchmarkTreePanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 15, 0)); return benchmarkTreePanel; } private CheckBoxTree createCheckBoxTree() { final CheckBoxTree resultCheckBoxTree = new CheckBoxTree(initBenchmarkHierarchy(true)); resultCheckBoxTree.addTreeSelectionListener(e -> { TreePath treeSelectionPath = e.getNewLeadSelectionPath(); if (treeSelectionPath != null) { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) treeSelectionPath.getLastPathComponent(); MixedCheckBox checkBox = (MixedCheckBox) treeNode.getUserObject(); detailTextArea.setText(checkBox.getDetail()); detailTextArea.setCaretPosition(0); renameNodeButton.setEnabled(checkBox.getBenchmarkResult() instanceof PlannerBenchmarkResult || checkBox.getBenchmarkResult() instanceof SolverBenchmarkResult); } }); resultCheckBoxTree.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { // Enable button if checked singleBenchmarkResults exist generateReportButton.setEnabled(!resultCheckBoxTree.getSelectedSingleBenchmarkNodes().isEmpty()); } }); checkBoxTree = resultCheckBoxTree; return resultCheckBoxTree; } private void initPlannerBenchmarkResultList() { plannerBenchmarkResultList = benchmarkResultIO.readPlannerBenchmarkResultList( benchmarkAggregator.getBenchmarkDirectory()); BenchmarkReportFactory reportFactory = new BenchmarkReportFactory(benchmarkAggregator.getBenchmarkReportConfig()); for (PlannerBenchmarkResult plannerBenchmarkResult : plannerBenchmarkResultList) { plannerBenchmarkResult.accumulateResults(reportFactory.buildBenchmarkReport(plannerBenchmarkResult)); } } private class GenerateReportAction extends AbstractAction { private final BenchmarkAggregatorFrame parentFrame; public GenerateReportAction(BenchmarkAggregatorFrame parentFrame) { super("Generate report"); this.parentFrame = parentFrame; } @Override public void actionPerformed(ActionEvent e) { parentFrame.setEnabled(false); generateReport(); } private void generateReport() { List<SingleBenchmarkResult> singleBenchmarkResultList = new ArrayList<>(); for (Map.Entry<SingleBenchmarkResult, DefaultMutableTreeNode> entry : resultCheckBoxMapping.entrySet()) { if (((MixedCheckBox) entry.getValue().getUserObject()).getStatus() == MixedCheckBoxStatus.CHECKED) { singleBenchmarkResultList.add(entry.getKey()); } } if (singleBenchmarkResultList.isEmpty()) { JOptionPane.showMessageDialog(parentFrame, "No single benchmarks have been selected.", "Warning", JOptionPane.WARNING_MESSAGE); parentFrame.setEnabled(true); } else { generateProgressBar.setIndeterminate(true); generateProgressBar.setStringPainted(true); generateProgressBar.setString("Generating..."); GenerateReportWorker worker = new GenerateReportWorker(parentFrame, singleBenchmarkResultList); worker.execute(); } } } private class ExpandNodesAction extends AbstractAction { public ExpandNodesAction() { super("Expand", new ImageIcon(BenchmarkAggregatorFrame.class.getResource("expand.png"))); setEnabled(!plannerBenchmarkResultList.isEmpty()); } @Override public void actionPerformed(ActionEvent e) { checkBoxTree.expandNodes(); } } private class CollapseNodesAction extends AbstractAction { public CollapseNodesAction() { super("Collapse", new ImageIcon(BenchmarkAggregatorFrame.class.getResource("collapse.png"))); setEnabled(!plannerBenchmarkResultList.isEmpty()); } @Override public void actionPerformed(ActionEvent e) { checkBoxTree.collapseNodes(); } } private class MoveNodeAction extends AbstractAction { private boolean directionUp; public MoveNodeAction(boolean directionUp) { super(directionUp ? "Move up" : "Move down", new ImageIcon(BenchmarkAggregatorFrame.class.getResource( directionUp ? "moveUp.png" : "moveDown.png"))); this.directionUp = directionUp; setEnabled(!plannerBenchmarkResultList.isEmpty()); } @Override public void actionPerformed(ActionEvent e) { if (checkBoxTree.getSelectionPath() != null) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) checkBoxTree.getSelectionPath() .getLastPathComponent(); DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) selectedNode.getParent(); if (parentNode != null) { DefaultMutableTreeNode immediateSiblingNode = directionUp ? (DefaultMutableTreeNode) parentNode.getChildBefore(selectedNode) : (DefaultMutableTreeNode) parentNode.getChildAfter(selectedNode); if (immediateSiblingNode != null) { parentNode.insert(immediateSiblingNode, parentNode.getIndex(selectedNode)); ((DefaultTreeModel) checkBoxTree.getModel()).nodeStructureChanged(parentNode); checkBoxTree.setSelectionPath(new TreePath(selectedNode.getPath())); } } } } } private class RenameNodeAction extends AbstractAction { public RenameNodeAction() { super("Rename", new ImageIcon(BenchmarkAggregatorFrame.class.getResource("rename.png"))); setEnabled(!plannerBenchmarkResultList.isEmpty()); } @Override public void actionPerformed(ActionEvent e) { if (checkBoxTree.getSelectionPath() != null) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) checkBoxTree.getSelectionPath() .getLastPathComponent(); MixedCheckBox mixedCheckBox = (MixedCheckBox) selectedNode.getUserObject(); if (mixedCheckBox.getBenchmarkResult() instanceof PlannerBenchmarkResult || mixedCheckBox.getBenchmarkResult() instanceof SolverBenchmarkResult) { RenameNodeDialog renameNodeDialog = new RenameNodeDialog(selectedNode); renameNodeDialog.pack(); renameNodeDialog.setLocationRelativeTo(BenchmarkAggregatorFrame.this); renameNodeDialog.setVisible(true); } } } } private class SwitchLevelsAction extends AbstractAction { private boolean solverLevelFirst; public SwitchLevelsAction(boolean solverLevelFirst) { super("Switch levels", new ImageIcon(BenchmarkAggregatorFrame.class.getResource("switchTree.png"))); this.solverLevelFirst = solverLevelFirst; setEnabled(!plannerBenchmarkResultList.isEmpty()); } @Override public void actionPerformed(ActionEvent e) { DefaultMutableTreeNode treeRoot = initBenchmarkHierarchy(solverLevelFirst); DefaultTreeModel treeModel = new DefaultTreeModel(treeRoot); checkBoxTree.setModel(treeModel); treeModel.nodeStructureChanged(treeRoot); solverLevelFirst = !solverLevelFirst; checkBoxTree.setSelectedSingleBenchmarkNodes(new HashSet<>()); for (Map.Entry<SingleBenchmarkResult, DefaultMutableTreeNode> entry : resultCheckBoxMapping.entrySet()) { if (((MixedCheckBox) entry.getValue().getUserObject()).getStatus() == MixedCheckBoxStatus.CHECKED) { checkBoxTree.getSelectedSingleBenchmarkNodes().add(entry.getValue()); } } checkBoxTree.updateHierarchyCheckBoxStates(); } } private class RenameNodeDialog extends JDialog { public RenameNodeDialog(final DefaultMutableTreeNode treeNode) { super(BenchmarkAggregatorFrame.this, "Rename node"); final MixedCheckBox mixedCheckBox = (MixedCheckBox) treeNode.getUserObject(); final Object benchmarkResult = mixedCheckBox.getBenchmarkResult(); JPanel mainPanel = new JPanel(new BorderLayout()); String benchmarkResultTextFieldText = null; if (benchmarkResult instanceof SolverBenchmarkResult) { benchmarkResultTextFieldText = solverBenchmarkResultNameMapping.get(benchmarkResult); } final JTextField benchmarkResultNameTextField = new JTextField( benchmarkResultTextFieldText == null ? benchmarkResult.toString() : benchmarkResultTextFieldText, 30); mainPanel.add(benchmarkResultNameTextField, BorderLayout.WEST); AbstractAction renamedAction = new AbstractAction("Rename") { @Override public void actionPerformed(ActionEvent e) { String newBenchmarkResultName = benchmarkResultNameTextField.getText(); if (newBenchmarkResultName == null || newBenchmarkResultName.isEmpty()) { JOptionPane.showMessageDialog(BenchmarkAggregatorFrame.this, "New benchmark's name cannot be empty.", "Warning", JOptionPane.WARNING_MESSAGE); } else { if (benchmarkResult instanceof PlannerBenchmarkResult result) { result.setName(newBenchmarkResultName); mixedCheckBox.setText(newBenchmarkResultName); ((DefaultTreeModel) checkBoxTree.getModel()).nodeChanged(treeNode); } else if (benchmarkResult instanceof SolverBenchmarkResult result) { mixedCheckBox.setText(newBenchmarkResultName + " (" + result.getRanking() + ")"); ((DefaultTreeModel) checkBoxTree.getModel()).nodeChanged(treeNode); solverBenchmarkResultNameMapping.put(result, newBenchmarkResultName); } dispose(); } } }; benchmarkResultNameTextField.addActionListener(renamedAction); JButton confirmRenameButton = new JButton(renamedAction); mainPanel.add(confirmRenameButton, BorderLayout.EAST); mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); setContentPane(mainPanel); } } private DefaultMutableTreeNode initBenchmarkHierarchy(boolean solverFirst) { DefaultMutableTreeNode parentNode = new DefaultMutableTreeNode(new MixedCheckBox("Planner benchmarks")); for (PlannerBenchmarkResult plannerBenchmarkResult : plannerBenchmarkResultList) { DefaultMutableTreeNode plannerNode = new DefaultMutableTreeNode( createPlannerBenchmarkCheckBox(plannerBenchmarkResult)); parentNode.add(plannerNode); if (solverFirst) { for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) { DefaultMutableTreeNode solverNode = new DefaultMutableTreeNode( createSolverBenchmarkCheckBox(solverBenchmarkResult)); plannerNode.add(solverNode); for (ProblemBenchmarkResult problemBenchmarkResult : plannerBenchmarkResult .getUnifiedProblemBenchmarkResultList()) { DefaultMutableTreeNode problemNode = new DefaultMutableTreeNode( createProblemBenchmarkCheckBox(problemBenchmarkResult)); solverNode.add(problemNode); initSingleBenchmarkNodes(solverBenchmarkResult, problemBenchmarkResult, problemNode); } } } else { for (ProblemBenchmarkResult problemBenchmarkResult : plannerBenchmarkResult .getUnifiedProblemBenchmarkResultList()) { DefaultMutableTreeNode problemNode = new DefaultMutableTreeNode( createProblemBenchmarkCheckBox(problemBenchmarkResult)); plannerNode.add(problemNode); for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) { DefaultMutableTreeNode solverNode = new DefaultMutableTreeNode( createSolverBenchmarkCheckBox(solverBenchmarkResult)); problemNode.add(solverNode); initSingleBenchmarkNodes(solverBenchmarkResult, problemBenchmarkResult, solverNode); } } } } return parentNode; } private void initSingleBenchmarkNodes(SolverBenchmarkResult solverBenchmarkResult, ProblemBenchmarkResult problemBenchmarkResult, DefaultMutableTreeNode problemNode) { for (SingleBenchmarkResult singleBenchmarkResult : solverBenchmarkResult.getSingleBenchmarkResultList()) { if (singleBenchmarkResult.getProblemBenchmarkResult().equals(problemBenchmarkResult)) { DefaultMutableTreeNode singleBenchmarkNode = resultCheckBoxMapping.get(singleBenchmarkResult); if (singleBenchmarkNode != null) { problemNode.add(singleBenchmarkNode); } else { DefaultMutableTreeNode singleNode = new DefaultMutableTreeNode( createSingleBenchmarkCheckBox(singleBenchmarkResult)); problemNode.add(singleNode); resultCheckBoxMapping.put(singleBenchmarkResult, singleNode); } } } } private MixedCheckBox createPlannerBenchmarkCheckBox(PlannerBenchmarkResult plannerBenchmarkResult) { String plannerBenchmarkDetail = String.format( "Average score: %s%n" + "Average problem scale: %d", plannerBenchmarkResult.getAverageScore(), plannerBenchmarkResult.getAverageProblemScale()); return new MixedCheckBox(plannerBenchmarkResult.getName(), plannerBenchmarkDetail, plannerBenchmarkResult); } private MixedCheckBox createSolverBenchmarkCheckBox(SolverBenchmarkResult solverBenchmarkResult) { String solverCheckBoxName = solverBenchmarkResult.getName() + " (" + solverBenchmarkResult.getRanking() + ")"; String solverBenchmarkDetail = String.format( "Total score: %s%n" + "Average score: %s%n" + "Total winning score difference: %s" + "Average time spent: %s%n", solverBenchmarkResult.getTotalScore(), solverBenchmarkResult.getAverageScore(), solverBenchmarkResult.getTotalWinningScoreDifference(), solverBenchmarkResult.getAverageTimeMillisSpent() == null ? "" : millisecondsSpentNumberFormat.format(solverBenchmarkResult.getAverageTimeMillisSpent())); solverBenchmarkResultNameMapping.put(solverBenchmarkResult, solverBenchmarkResult.getName()); return new MixedCheckBox(solverCheckBoxName, solverBenchmarkDetail, solverBenchmarkResult); } private MixedCheckBox createProblemBenchmarkCheckBox(ProblemBenchmarkResult problemBenchmarkResult) { String problemBenchmarkDetail = String.format( "Entity count: %d%n" + "Problem scale: %d%n" + "Used memory: %s", problemBenchmarkResult.getEntityCount(), problemBenchmarkResult.getProblemScale(), toEmptyStringIfNull(problemBenchmarkResult.getAverageUsedMemoryAfterInputSolution())); return new MixedCheckBox(problemBenchmarkResult.getName(), problemBenchmarkDetail); } private MixedCheckBox createSingleBenchmarkCheckBox(SingleBenchmarkResult singleBenchmarkResult) { String singleCheckBoxName = singleBenchmarkResult.getName() + " (" + singleBenchmarkResult.getRanking() + ")"; String singleBenchmarkDetail = String.format( "Score: %s%n" + "Used memory: %s%n" + "Time spent: %s", singleBenchmarkResult.getAverageScore(), toEmptyStringIfNull(singleBenchmarkResult.getUsedMemoryAfterInputSolution()), millisecondsSpentNumberFormat.format(singleBenchmarkResult.getTimeMillisSpent())); return new MixedCheckBox(singleCheckBoxName, singleBenchmarkDetail, singleBenchmarkResult); } private String toEmptyStringIfNull(Object obj) { return obj == null ? "" : obj.toString(); } private class GenerateReportWorker extends SwingWorker<File, Void> { private final BenchmarkAggregatorFrame parentFrame; private List<SingleBenchmarkResult> singleBenchmarkResultList; public GenerateReportWorker(BenchmarkAggregatorFrame parentFrame, List<SingleBenchmarkResult> singleBenchmarkResultList) { this.parentFrame = parentFrame; this.singleBenchmarkResultList = singleBenchmarkResultList; } @Override protected File doInBackground() { return benchmarkAggregator.aggregateSelectedBenchmarksInUi(singleBenchmarkResultList, solverBenchmarkResultNameMapping); } @Override protected void done() { try { File htmlOverviewFile = get(); ReportFinishedDialog dialog = new ReportFinishedDialog(parentFrame, htmlOverviewFile); dialog.pack(); dialog.setLocationRelativeTo(parentFrame); dialog.setVisible(true); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("The report generation was interrupted.", e); } catch (ExecutionException e) { throw new IllegalStateException("The report generation failed.", e.getCause()); } finally { detailTextArea.setText(null); generateProgressBar.setIndeterminate(false); generateProgressBar.setString(null); generateProgressBar.setStringPainted(false); } } } private class ReportFinishedDialog extends JDialog { private final BenchmarkAggregatorFrame parentFrame; private final File reportFile; private JCheckBox exitCheckBox; public ReportFinishedDialog(BenchmarkAggregatorFrame parentFrame, File reportFile) { super(parentFrame, "Report generation finished"); this.parentFrame = parentFrame; this.reportFile = reportFile; addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { refresh(); } }); JPanel mainPanel = new JPanel(new BorderLayout(0, 10)); exitCheckBox = new JCheckBox("Exit application", exitApplicationWhenReportFinished); mainPanel.add(exitCheckBox, BorderLayout.NORTH); mainPanel.add(createButtonPanel(), BorderLayout.CENTER); mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); getContentPane().add(mainPanel); } private JPanel createButtonPanel() { final Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; JPanel buttonPanel = new JPanel(new GridLayout(1, 3, 10, 10)); AbstractAction openBrowserAction = new AbstractAction("Show in browser") { @Override public void actionPerformed(ActionEvent event) { try { desktop.browse(reportFile.getAbsoluteFile().toURI()); } catch (IOException e) { throw new IllegalStateException("Failed showing reportFile (" + reportFile + ") in the default browser.", e); } finishDialog(); } }; openBrowserAction.setEnabled(desktop != null && desktop.isSupported(Desktop.Action.BROWSE)); buttonPanel.add(new JButton(openBrowserAction)); AbstractAction openFileAction = new AbstractAction("Show in files") { @Override public void actionPerformed(ActionEvent event) { try { desktop.open(reportFile.getParentFile()); } catch (IOException e) { throw new IllegalStateException("Failed showing reportFile (" + reportFile + ") in the file explorer.", e); } finishDialog(); } }; openFileAction.setEnabled(desktop != null && desktop.isSupported(Desktop.Action.OPEN)); buttonPanel.add(new JButton(openFileAction)); AbstractAction closeAction = new AbstractAction("Ok") { @Override public void actionPerformed(ActionEvent e) { finishDialog(); } }; buttonPanel.add(new JButton(closeAction)); return buttonPanel; } private void finishDialog() { exitApplicationWhenReportFinished = exitCheckBox.isSelected(); if (exitApplicationWhenReportFinished) { parentFrame.dispose(); } else { dispose(); parentFrame.refresh(); } } } private void refresh() { initPlannerBenchmarkResultList(); solverBenchmarkResultNameMapping = new HashMap<>(); resultCheckBoxMapping = new LinkedHashMap<>(); checkBoxTree.setSelectedSingleBenchmarkNodes(new HashSet<>()); DefaultMutableTreeNode newCheckBoxRootNode = initBenchmarkHierarchy(true); DefaultTreeModel treeModel = new DefaultTreeModel(newCheckBoxRootNode); checkBoxTree.setModel(treeModel); treeModel.nodeStructureChanged(newCheckBoxRootNode); setEnabled(true); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/aggregator
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/aggregator/swingui/CheckBoxTree.java
package ai.timefold.solver.benchmark.impl.aggregator.swingui; import static ai.timefold.solver.benchmark.impl.aggregator.swingui.MixedCheckBox.MixedCheckBoxStatus.CHECKED; import static ai.timefold.solver.benchmark.impl.aggregator.swingui.MixedCheckBox.MixedCheckBoxStatus.MIXED; import static ai.timefold.solver.benchmark.impl.aggregator.swingui.MixedCheckBox.MixedCheckBoxStatus.UNCHECKED; import java.awt.Color; import java.awt.Component; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Enumeration; import java.util.HashSet; import java.util.Set; import javax.swing.JTree; import javax.swing.UIManager; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import ai.timefold.solver.benchmark.impl.result.SingleBenchmarkResult; public class CheckBoxTree extends JTree { private static final Color TREE_SELECTION_COLOR = UIManager.getColor("Tree.selectionBackground"); private Set<DefaultMutableTreeNode> selectedSingleBenchmarkNodes = new HashSet<>(); public CheckBoxTree(DefaultMutableTreeNode root) { super(root); addMouseListener(new CheckBoxTreeMouseListener(this)); setCellRenderer(new CheckBoxTreeCellRenderer()); setToggleClickCount(0); getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); } public Set<DefaultMutableTreeNode> getSelectedSingleBenchmarkNodes() { return selectedSingleBenchmarkNodes; } public void setSelectedSingleBenchmarkNodes(Set<DefaultMutableTreeNode> selectedSingleBenchmarkNodes) { this.selectedSingleBenchmarkNodes = selectedSingleBenchmarkNodes; } public void expandNodes() { expandSubtree(null, true); } public void collapseNodes() { expandSubtree(null, false); } private void expandSubtree(TreePath path, boolean expand) { if (path == null) { TreePath selectionPath = getSelectionPath(); path = selectionPath == null ? new TreePath(treeModel.getRoot()) : selectionPath; } DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) path.getLastPathComponent(); Enumeration children = currentNode.children(); while (children.hasMoreElements()) { DefaultMutableTreeNode child = (DefaultMutableTreeNode) children.nextElement(); TreePath expandedPath = path.pathByAddingChild(child); expandSubtree(expandedPath, expand); } if (expand) { expandPath(path); } else if (path.getParentPath() != null) { collapsePath(path); } } public void updateHierarchyCheckBoxStates() { for (DefaultMutableTreeNode currentNode : selectedSingleBenchmarkNodes) { resolveNewCheckBoxState(currentNode, CHECKED, MIXED); } treeDidChange(); } private void resolveNewCheckBoxState(DefaultMutableTreeNode currentNode, MixedCheckBox.MixedCheckBoxStatus newStatus, MixedCheckBox.MixedCheckBoxStatus mixedStatus) { MixedCheckBox checkBox = (MixedCheckBox) currentNode.getUserObject(); checkBox.setStatus(newStatus); selectChildren(currentNode, newStatus); TreeNode[] ancestorNodes = currentNode.getPath(); // examine ancestors, don't lose track of most recent changes - bottom-up approach for (int i = ancestorNodes.length - 2; i >= 0; i--) { DefaultMutableTreeNode ancestorNode = (DefaultMutableTreeNode) ancestorNodes[i]; MixedCheckBox ancestorCheckbox = (MixedCheckBox) ancestorNode.getUserObject(); if (checkChildren(ancestorNode, newStatus)) { ancestorCheckbox.setStatus(newStatus); } else { if (mixedStatus == null) { break; } ancestorCheckbox.setStatus(mixedStatus); } } } private void selectChildren(DefaultMutableTreeNode parent, MixedCheckBox.MixedCheckBoxStatus status) { MixedCheckBox box = (MixedCheckBox) parent.getUserObject(); if (box.getBenchmarkResult() instanceof SingleBenchmarkResult) { if (status == CHECKED) { selectedSingleBenchmarkNodes.add(parent); } else if (status == UNCHECKED) { selectedSingleBenchmarkNodes.remove(parent); } } Enumeration children = parent.children(); while (children.hasMoreElements()) { DefaultMutableTreeNode child = (DefaultMutableTreeNode) children.nextElement(); MixedCheckBox childCheckBox = (MixedCheckBox) child.getUserObject(); childCheckBox.setStatus(status); selectChildren(child, status); } } private boolean checkChildren(DefaultMutableTreeNode parent, MixedCheckBox.MixedCheckBoxStatus status) { boolean childrenCheck = true; Enumeration children = parent.children(); while (children.hasMoreElements()) { DefaultMutableTreeNode child = (DefaultMutableTreeNode) children.nextElement(); MixedCheckBox checkBox = (MixedCheckBox) child.getUserObject(); if (checkBox.getStatus() != status) { childrenCheck = false; break; } } return childrenCheck; } private class CheckBoxTreeMouseListener extends MouseAdapter { private CheckBoxTree tree; private double unlabeledMixedCheckBoxWidth; public CheckBoxTreeMouseListener(CheckBoxTree tree) { this.tree = tree; unlabeledMixedCheckBoxWidth = new MixedCheckBox().getPreferredSize().getWidth(); } @Override public void mousePressed(MouseEvent e) { TreePath path = tree.getPathForLocation(e.getX(), e.getY()); if (path != null) { DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) path.getLastPathComponent(); MixedCheckBox checkBox = (MixedCheckBox) currentNode.getUserObject(); // ignore clicks on checkbox's label - enables to select it without changing the state if (e.getX() - tree.getPathBounds(path).getX() > unlabeledMixedCheckBoxWidth) { return; } switch (checkBox.getStatus()) { case CHECKED: resolveNewCheckBoxState(currentNode, UNCHECKED, MIXED); break; case UNCHECKED: resolveNewCheckBoxState(currentNode, CHECKED, MIXED); break; case MIXED: resolveNewCheckBoxState(currentNode, CHECKED, null); break; default: throw new IllegalStateException("The status (" + checkBox.getStatus() + ") is not implemented."); } tree.treeDidChange(); } } } private static class CheckBoxTreeCellRenderer implements TreeCellRenderer { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; MixedCheckBox checkBox = (MixedCheckBox) node.getUserObject(); checkBox.setBackground(selected ? TREE_SELECTION_COLOR : Color.WHITE); return checkBox; } } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/aggregator
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/aggregator/swingui/MixedCheckBox.java
package ai.timefold.solver.benchmark.impl.aggregator.swingui; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JCheckBox; public class MixedCheckBox extends JCheckBox { private String detail; private Object benchmarkResult; public MixedCheckBox() { this(null); } public MixedCheckBox(String text) { this(text, null); } public MixedCheckBox(String text, String detail) { this(text, detail, null); } public MixedCheckBox(String text, String detail, Object benchmarkResult) { super(text); this.detail = detail; this.benchmarkResult = benchmarkResult; setModel(new MixedCheckBoxModel()); setStatus(MixedCheckBoxStatus.UNCHECKED); addMouseListener(new CustomCheckboxMouseListener()); } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public Object getBenchmarkResult() { return benchmarkResult; } public void setBenchmarkResult(Object benchmarkResult) { this.benchmarkResult = benchmarkResult; } public MixedCheckBoxStatus getStatus() { return ((MixedCheckBoxModel) getModel()).getStatus(); } public void setStatus(MixedCheckBoxStatus status) { ((MixedCheckBoxModel) getModel()).setStatus(status); } private class CustomCheckboxMouseListener extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { ((MixedCheckBoxModel) getModel()).switchStatus(); } } private static class MixedCheckBoxModel extends ToggleButtonModel { private MixedCheckBoxStatus getStatus() { return isSelected() ? (isArmed() ? MixedCheckBoxStatus.MIXED : MixedCheckBoxStatus.CHECKED) : MixedCheckBoxStatus.UNCHECKED; } private void setStatus(MixedCheckBoxStatus status) { if (status == MixedCheckBoxStatus.CHECKED) { setSelected(true); setArmed(false); setPressed(false); } else if (status == MixedCheckBoxStatus.UNCHECKED) { setSelected(false); setArmed(false); setPressed(false); } else if (status == MixedCheckBoxStatus.MIXED) { setSelected(true); setArmed(true); setPressed(true); } else { throw new IllegalArgumentException("Invalid argument (" + status + ") supplied."); } } private void switchStatus() { switch (getStatus()) { case CHECKED: setStatus(MixedCheckBoxStatus.UNCHECKED); break; case UNCHECKED: setStatus(MixedCheckBoxStatus.CHECKED); break; case MIXED: setStatus(MixedCheckBoxStatus.CHECKED); break; default: throw new IllegalStateException("The status (" + getStatus() + ") is not implemented."); } } } public enum MixedCheckBoxStatus { CHECKED, UNCHECKED, MIXED } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/cli/TimefoldBenchmarkCli.java
package ai.timefold.solver.benchmark.impl.cli; import java.io.File; import ai.timefold.solver.benchmark.api.PlannerBenchmark; import ai.timefold.solver.benchmark.api.PlannerBenchmarkFactory; import ai.timefold.solver.benchmark.config.PlannerBenchmarkConfig; /** * Run this class from the command line interface * to run a benchmarkConfigFile directly (using the normal classpath from the JVM). */ public class TimefoldBenchmarkCli { public static void main(String[] args) { if (args.length != 2) { System.err.println("Usage: TimefoldBenchmarkCli benchmarkConfigFile benchmarkDirectory"); System.exit(1); } File benchmarkConfigFile = new File(args[0]); if (!benchmarkConfigFile.exists()) { System.err.println("The benchmarkConfigFile (" + benchmarkConfigFile + ") does not exist."); System.exit(1); } File benchmarkDirectory = new File(args[1]); PlannerBenchmarkConfig benchmarkConfig; if (benchmarkConfigFile.getName().endsWith(".ftl")) { benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlFile(benchmarkConfigFile); } else { benchmarkConfig = PlannerBenchmarkConfig.createFromXmlFile(benchmarkConfigFile); } benchmarkConfig.setBenchmarkDirectory(benchmarkDirectory); PlannerBenchmarkFactory benchmarkFactory = PlannerBenchmarkFactory.create(benchmarkConfig); PlannerBenchmark benchmark = benchmarkFactory.buildPlannerBenchmark(); benchmark.benchmark(); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/io/PlannerBenchmarkConfigIO.java
package ai.timefold.solver.benchmark.impl.io; import java.io.Reader; import java.io.Writer; import ai.timefold.solver.benchmark.config.PlannerBenchmarkConfig; import ai.timefold.solver.core.config.solver.SolverConfig; import ai.timefold.solver.core.impl.io.jaxb.ElementNamespaceOverride; import ai.timefold.solver.core.impl.io.jaxb.GenericJaxbIO; import ai.timefold.solver.core.impl.io.jaxb.JaxbIO; import org.w3c.dom.Document; public class PlannerBenchmarkConfigIO implements JaxbIO<PlannerBenchmarkConfig> { private static final String BENCHMARK_XSD_RESOURCE = "/benchmark.xsd"; private final GenericJaxbIO<PlannerBenchmarkConfig> genericJaxbIO = new GenericJaxbIO<>(PlannerBenchmarkConfig.class); @Override public PlannerBenchmarkConfig read(Reader reader) { Document document = genericJaxbIO.parseXml(reader); String rootElementNamespace = document.getDocumentElement().getNamespaceURI(); if (PlannerBenchmarkConfig.XML_NAMESPACE.equals(rootElementNamespace)) { // If there is the correct namespace, validate. genericJaxbIO.validate(document, BENCHMARK_XSD_RESOURCE); /* * In JAXB annotations the SolverConfig belongs to a different namespace than the PlannerBenchmarkConfig. * However, benchmark.xsd merges both namespaces into a single one. As a result, JAXB is incapable of matching * the solver element in benchmark configuration and thus the solver element's namespace needs to be overridden. */ return genericJaxbIO.readOverridingNamespace(document, ElementNamespaceOverride.of(SolverConfig.XML_ELEMENT_NAME, SolverConfig.XML_NAMESPACE)); } else if (rootElementNamespace == null || rootElementNamespace.isEmpty()) { // If not, add the missing namespace to maintain backward compatibility. return genericJaxbIO.readOverridingNamespace(document, ElementNamespaceOverride.of(PlannerBenchmarkConfig.XML_ELEMENT_NAME, PlannerBenchmarkConfig.XML_NAMESPACE), ElementNamespaceOverride.of(SolverConfig.XML_ELEMENT_NAME, SolverConfig.XML_NAMESPACE)); } else { // If there is an unexpected namespace, fail fast. String errorMessage = String.format("The <%s/> element belongs to a different namespace (%s) than expected (%s).", PlannerBenchmarkConfig.XML_ELEMENT_NAME, rootElementNamespace, PlannerBenchmarkConfig.XML_NAMESPACE); throw new IllegalArgumentException(errorMessage); } } @Override public void write(PlannerBenchmarkConfig plannerBenchmarkConfig, Writer writer) { genericJaxbIO.writeWithoutNamespaces(plannerBenchmarkConfig, writer); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/loader/FileProblemProvider.java
package ai.timefold.solver.benchmark.impl.loader; import java.io.File; import java.util.Objects; import jakarta.xml.bind.annotation.XmlTransient; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.persistence.common.api.domain.solution.SolutionFileIO; public class FileProblemProvider<Solution_> implements ProblemProvider<Solution_> { @XmlTransient private SolutionFileIO<Solution_> solutionFileIO; private File problemFile; private FileProblemProvider() { // Required by JAXB } public FileProblemProvider(SolutionFileIO<Solution_> solutionFileIO, File problemFile) { this.solutionFileIO = solutionFileIO; this.problemFile = problemFile; } public SolutionFileIO<Solution_> getSolutionFileIO() { return solutionFileIO; } @Override public String getProblemName() { String name = problemFile.getName(); int lastDotIndex = name.lastIndexOf('.'); if (lastDotIndex > 0) { return name.substring(0, lastDotIndex); } else { return name; } } @Override public Solution_ readProblem() { return solutionFileIO.read(problemFile); } @Override public void writeSolution(Solution_ solution, SubSingleBenchmarkResult subSingleBenchmarkResult) { String filename = subSingleBenchmarkResult.getSingleBenchmarkResult().getProblemBenchmarkResult().getName() + "." + solutionFileIO.getOutputFileExtension(); File solutionFile = new File(subSingleBenchmarkResult.getResultDirectory(), filename); solutionFileIO.write(solution, solutionFile); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } FileProblemProvider<?> that = (FileProblemProvider<?>) other; return Objects.equals(problemFile, that.problemFile); } @Override public int hashCode() { return Objects.hash(problemFile); } @Override public String toString() { return problemFile.toString(); } public File getProblemFile() { return problemFile; } public void setProblemFile(File problemFile) { this.problemFile = problemFile; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/loader/InstanceProblemProvider.java
package ai.timefold.solver.benchmark.impl.loader; import java.util.Objects; import jakarta.xml.bind.annotation.XmlTransient; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.core.api.domain.solution.cloner.SolutionCloner; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; public class InstanceProblemProvider<Solution_> implements ProblemProvider<Solution_> { private String problemName; @XmlTransient private Solution_ problem; @XmlTransient private SolutionCloner<Solution_> solutionCloner; public InstanceProblemProvider() { // Required by JAXB } public InstanceProblemProvider(String problemName, SolutionDescriptor<Solution_> solutionDescriptor, Solution_ problem) { this.problemName = problemName; this.problem = problem; solutionCloner = solutionDescriptor.getSolutionCloner(); } @Override public String getProblemName() { return problemName; } @Override public Solution_ readProblem() { // Return a planning clone so multiple solver benchmarks don't affect each other return solutionCloner.cloneSolution(problem); } @Override public void writeSolution(Solution_ solution, SubSingleBenchmarkResult subSingleBenchmarkResult) { // TODO maybe we can store them in a List and somehow return a List<List<Solution_>> from PlannerBenchmark? throw new UnsupportedOperationException("Writing the solution (" + solution + ") is not supported for a benchmark problem given as an instance."); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } InstanceProblemProvider<?> that = (InstanceProblemProvider<?>) other; /* * Do not compare the solutionCloner, because the same extraProblem instance or the same problem inputFile * might be benchmarked with different solvers using different SolutionCloner configurations, * yet they should be reported on a single BEST_SCORE graph. */ return Objects.equals(problemName, that.problemName) && Objects.equals(problem, that.problem); } @Override public int hashCode() { return Objects.hash(problemName, problem); } @Override public String toString() { return problemName; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/loader/ProblemProvider.java
package ai.timefold.solver.benchmark.impl.loader; import jakarta.xml.bind.annotation.XmlSeeAlso; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; /** * Subclasses need to implement {@link Object#equals(Object) equals()} and {@link Object#hashCode() hashCode()} * which are used by {@link ai.timefold.solver.benchmark.impl.ProblemBenchmarksFactory#buildProblemBenchmarkList}. * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ @XmlSeeAlso({ InstanceProblemProvider.class, FileProblemProvider.class }) public interface ProblemProvider<Solution_> { /** * @return never null */ String getProblemName(); /** * @return never null */ Solution_ readProblem(); /** * @param solution never null * @param subSingleBenchmarkResult never null */ void writeSolution(Solution_ solution, SubSingleBenchmarkResult subSingleBenchmarkResult); }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/ranking/ResilientScoreComparator.java
package ai.timefold.solver.benchmark.impl.ranking; import java.util.Comparator; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; /** * Able to compare {@link Score}s of different types or nulls. */ final class ResilientScoreComparator implements Comparator<Score> { private final ScoreDefinition aScoreDefinition; public ResilientScoreComparator(ScoreDefinition aScoreDefinition) { this.aScoreDefinition = aScoreDefinition; } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public int compare(Score a, Score b) { if (a == null) { return b == null ? 0 : -1; } else if (b == null) { return 1; } if (!aScoreDefinition.isCompatibleArithmeticArgument(a) || !aScoreDefinition.isCompatibleArithmeticArgument(b)) { var aNumbers = a.toLevelNumbers(); var bNumbers = b.toLevelNumbers(); for (var i = 0; i < aNumbers.length || i < bNumbers.length; i++) { var aToken = i < aNumbers.length ? aNumbers[i] : 0; var bToken = i < bNumbers.length ? bNumbers[i] : 0; int comparison; if (aToken.getClass().equals(bToken.getClass()) && aToken instanceof Comparable aTokenComparable && bToken instanceof Comparable bTokenComparable) { comparison = aTokenComparable.compareTo(bTokenComparable); } else { comparison = Double.compare(aToken.doubleValue(), bToken.doubleValue()); } if (comparison != 0) { return comparison; } } return 0; } return a.compareTo(b); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/ranking/ScoreSubSingleBenchmarkRankingComparator.java
package ai.timefold.solver.benchmark.impl.ranking; import java.util.Comparator; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; public class ScoreSubSingleBenchmarkRankingComparator implements Comparator<SubSingleBenchmarkResult> { @Override public int compare(SubSingleBenchmarkResult a, SubSingleBenchmarkResult b) { var aScoreDefinition = a.getSingleBenchmarkResult().getSolverBenchmarkResult().getScoreDefinition(); return Comparator // Reverse, less is better (redundant: failed benchmarks don't get ranked at all) .comparing(SubSingleBenchmarkResult::hasAnyFailure, Comparator.reverseOrder()) .thenComparing(SubSingleBenchmarkResult::isInitialized) .thenComparing(SubSingleBenchmarkResult::getScore, new ResilientScoreComparator(aScoreDefinition)) .compare(a, b); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/ranking/SolverRankingWeightFactory.java
package ai.timefold.solver.benchmark.impl.ranking; import java.util.List; import ai.timefold.solver.benchmark.impl.result.SolverBenchmarkResult; /** * Defines an interface for classes that will be used to rank solver benchmarks * in order of their respective performance. */ public interface SolverRankingWeightFactory { /** * The ranking function. Takes the provided solverBenchmarkResultList and ranks them. * * @param solverBenchmarkResultList never null * @param solverBenchmarkResult never null * @return never null */ Comparable createRankingWeight(List<SolverBenchmarkResult> solverBenchmarkResultList, SolverBenchmarkResult solverBenchmarkResult); }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/ranking/SubSingleBenchmarkRankBasedComparator.java
package ai.timefold.solver.benchmark.impl.ranking; import static java.util.Comparator.comparing; import static java.util.Comparator.naturalOrder; import static java.util.Comparator.nullsLast; import static java.util.Comparator.reverseOrder; import java.util.Comparator; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; public class SubSingleBenchmarkRankBasedComparator implements Comparator<SubSingleBenchmarkResult> { private static final Comparator<SubSingleBenchmarkResult> COMPARATOR = // Reverse, less is better (redundant: failed benchmarks don't get ranked at all) comparing(SubSingleBenchmarkResult::hasAnyFailure, reverseOrder()) .thenComparing(SubSingleBenchmarkResult::getRanking, nullsLast(naturalOrder())); @Override public int compare(SubSingleBenchmarkResult a, SubSingleBenchmarkResult b) { return COMPARATOR.compare(a, b); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/ranking/TotalRankSolverRankingWeightFactory.java
package ai.timefold.solver.benchmark.impl.ranking; import java.util.Comparator; import java.util.List; import java.util.Objects; import ai.timefold.solver.benchmark.impl.result.SingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SolverBenchmarkResult; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; /** * This {@link SolverRankingWeightFactory} orders a {@link SolverBenchmarkResult} by how many times each of its * {@link SingleBenchmarkResult}s beat {@link SingleBenchmarkResult}s of the other {@link SolverBenchmarkResult}. * It maximizes the overall ranking. * <p> * When the inputSolutions differ greatly in size or difficulty, this often produces a difference in * {@link Score} magnitude between each {@link PlanningSolution}. For example: score 10 for dataset A versus 1000 for dataset B. * In such cases, this ranking is more fair than {@link TotalScoreSolverRankingComparator}, * because in this ranking, dataset B wouldn't marginalize dataset A. */ public class TotalRankSolverRankingWeightFactory implements SolverRankingWeightFactory { private final Comparator<SingleBenchmarkResult> singleBenchmarkRankingComparator = new TotalScoreSingleBenchmarkRankingComparator(); @Override public Comparable createRankingWeight(List<SolverBenchmarkResult> solverBenchmarkResultList, SolverBenchmarkResult solverBenchmarkResult) { int betterCount = 0; int equalCount = 0; int lowerCount = 0; List<SingleBenchmarkResult> singleBenchmarkResultList = solverBenchmarkResult.getSingleBenchmarkResultList(); for (SingleBenchmarkResult single : singleBenchmarkResultList) { List<SingleBenchmarkResult> otherSingleList = single.getProblemBenchmarkResult().getSingleBenchmarkResultList(); for (SingleBenchmarkResult otherSingle : otherSingleList) { if (single == otherSingle) { continue; } int scoreComparison = singleBenchmarkRankingComparator.compare(single, otherSingle); if (scoreComparison > 0) { betterCount++; } else if (scoreComparison == 0) { equalCount++; } else { lowerCount++; } } } return new TotalRankSolverRankingWeight(solverBenchmarkResult, betterCount, equalCount, lowerCount); } public static class TotalRankSolverRankingWeight implements Comparable<TotalRankSolverRankingWeight> { private final Comparator<TotalRankSolverRankingWeight> totalRankSolverRankingWeightFactoryComparator = Comparator.comparingInt(TotalRankSolverRankingWeight::getBetterCount) .thenComparingInt(TotalRankSolverRankingWeight::getEqualCount) .thenComparingInt(TotalRankSolverRankingWeight::getLowerCount) .thenComparing(TotalRankSolverRankingWeight::getSolverBenchmarkResult, new TotalScoreSolverRankingComparator()); // Tie-breaker private final SolverBenchmarkResult solverBenchmarkResult; private final int betterCount; private final int equalCount; private final int lowerCount; public SolverBenchmarkResult getSolverBenchmarkResult() { return solverBenchmarkResult; } public int getBetterCount() { return betterCount; } public int getEqualCount() { return equalCount; } public int getLowerCount() { return lowerCount; } public TotalRankSolverRankingWeight(SolverBenchmarkResult solverBenchmarkResult, int betterCount, int equalCount, int lowerCount) { this.solverBenchmarkResult = solverBenchmarkResult; this.betterCount = betterCount; this.equalCount = equalCount; this.lowerCount = lowerCount; } @Override public int compareTo(TotalRankSolverRankingWeight other) { return totalRankSolverRankingWeightFactoryComparator.compare(this, other); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TotalRankSolverRankingWeight that = (TotalRankSolverRankingWeight) o; return this.compareTo(that) == 0; } @Override public int hashCode() { return Objects.hash(betterCount, equalCount, lowerCount); } } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/ranking/TotalScoreSingleBenchmarkRankingComparator.java
package ai.timefold.solver.benchmark.impl.ranking; import java.util.Comparator; import ai.timefold.solver.benchmark.impl.result.SingleBenchmarkResult; public class TotalScoreSingleBenchmarkRankingComparator implements Comparator<SingleBenchmarkResult> { @Override public int compare(SingleBenchmarkResult a, SingleBenchmarkResult b) { var aScoreDefinition = a.getSolverBenchmarkResult().getScoreDefinition(); return Comparator // Reverse, less is better (redundant: failed benchmarks don't get ranked at all) .comparing(SingleBenchmarkResult::hasAnyFailure, Comparator.reverseOrder()) .thenComparing(SingleBenchmarkResult::isInitialized) .thenComparing(SingleBenchmarkResult::getTotalScore, new ResilientScoreComparator(aScoreDefinition)) .compare(a, b); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/ranking/TotalScoreSolverRankingComparator.java
package ai.timefold.solver.benchmark.impl.ranking; import java.util.Comparator; import ai.timefold.solver.benchmark.impl.result.SolverBenchmarkResult; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; /** * This ranking {@link Comparator} orders a {@link SolverBenchmarkResult} by its total {@link Score}. * It maximize the overall score, so it minimizes the overall cost if all {@link PlanningSolution}s would be executed. * <p> * When the inputSolutions differ greatly in size or difficulty, this often results in a big difference in * {@link Score} magnitude between each {@link PlanningSolution}. For example: score 10 for dataset A versus 1000 for dataset B. * In such cases, dataset B would marginalize dataset A. * To avoid that, use {@link TotalRankSolverRankingWeightFactory}. */ public class TotalScoreSolverRankingComparator implements Comparator<SolverBenchmarkResult> { private final Comparator<SolverBenchmarkResult> worstScoreSolverRankingComparator = new WorstScoreSolverRankingComparator(); @Override public int compare(SolverBenchmarkResult a, SolverBenchmarkResult b) { ScoreDefinition aScoreDefinition = a.getScoreDefinition(); return Comparator .comparing(SolverBenchmarkResult::getFailureCount, Comparator.reverseOrder()) .thenComparing(SolverBenchmarkResult::getTotalScore, new ResilientScoreComparator(aScoreDefinition)) .thenComparing(worstScoreSolverRankingComparator) .compare(a, b); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/ranking/WorstScoreSolverRankingComparator.java
package ai.timefold.solver.benchmark.impl.ranking; import java.util.Comparator; import java.util.List; import ai.timefold.solver.benchmark.impl.result.SingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SolverBenchmarkResult; import ai.timefold.solver.core.api.score.Score; /** * This ranking {@link Comparator} orders a {@link SolverBenchmarkResult} by its worst {@link Score}. * It minimizes the worst case scenario. */ public class WorstScoreSolverRankingComparator implements Comparator<SolverBenchmarkResult> { private final Comparator<SingleBenchmarkResult> singleBenchmarkComparator = new TotalScoreSingleBenchmarkRankingComparator(); @Override public int compare(SolverBenchmarkResult a, SolverBenchmarkResult b) { List<SingleBenchmarkResult> aSingleBenchmarkResultList = a.getSingleBenchmarkResultList(); List<SingleBenchmarkResult> bSingleBenchmarkResultList = b.getSingleBenchmarkResultList(); // Order scores from worst to best aSingleBenchmarkResultList.sort(singleBenchmarkComparator); bSingleBenchmarkResultList.sort(singleBenchmarkComparator); int aSize = aSingleBenchmarkResultList.size(); int bSize = bSingleBenchmarkResultList.size(); for (int i = 0; i < aSize && i < bSize; i++) { int comparison = singleBenchmarkComparator.compare(aSingleBenchmarkResultList.get(i), bSingleBenchmarkResultList.get(i)); if (comparison != 0) { return comparison; } } return Integer.compare(aSize, bSize); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/report/BarChart.java
package ai.timefold.solver.benchmark.impl.report; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.Objects; import java.util.Set; import java.util.TreeMap; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; public record BarChart<Y extends Number & Comparable<Y>>(String id, String title, String xLabel, String yLabel, List<String> categories, List<Dataset<Y>> datasets, boolean timeOnY) implements Chart { public BarChart { id = Chart.makeIdUnique(id); } @SuppressWarnings("unused") // Used by FreeMarker. public BigDecimal yMin() { return LineChart.min(getYValues()); } private List<Y> getYValues() { return datasets.stream() .flatMap(d -> d.data().stream()) .filter(Objects::nonNull) .toList(); } @SuppressWarnings("unused") // Used by FreeMarker. public BigDecimal yMax() { return LineChart.max(getYValues()); } @SuppressWarnings("unused") // Used by FreeMarker. public BigDecimal yStepSize() { return LineChart.stepSize(yMin(), yMax()); } @SuppressWarnings("unused") // Used by FreeMarker. public boolean yLogarithmic() { if (timeOnY) { // Logarithmic time doesn't make sense. return false; } return LineChart.useLogarithmicProblemScale(getYValues()); } @Override public void writeToFile(Path parentFolder) { File file = new File(parentFolder.toFile(), id() + ".js"); file.getParentFile().mkdirs(); Configuration freeMarkerCfg = BenchmarkReport.createFreeMarkerConfiguration(); freeMarkerCfg.setClassForTemplateLoading(getClass(), ""); String templateFilename = "chart-bar.js.ftl"; Map<String, Object> model = new HashMap<>(); model.put("chart", this); try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) { Template template = freeMarkerCfg.getTemplate(templateFilename); template.process(model, writer); } catch (IOException e) { throw new IllegalArgumentException("Can not read templateFilename (" + templateFilename + ") or write chart file (" + file + ").", e); } catch (TemplateException e) { throw new IllegalArgumentException("Can not process Freemarker templateFilename (" + templateFilename + ") to chart file (" + id + ").", e); } } public static final class Builder<Y extends Number & Comparable<Y>> { private final Map<String, NavigableMap<String, Y>> data = new LinkedHashMap<>(); private final Set<String> favoriteSet = new HashSet<>(); public Builder<Y> add(String dataset, String category, Y y) { data.computeIfAbsent(dataset, k -> new TreeMap<>()) .put(category, y); return this; } public Set<String> keys() { return data.keySet(); } public Builder<Y> markFavorite(String dataset) { favoriteSet.add(dataset); return this; } public BarChart<Y> build(String fileName, String title, String xLabel, String yLabel, boolean timeOnY) { // First find all categories across all data sets. List<String> categories = data.values().stream() .flatMap(m -> m.keySet().stream()) .distinct() .sorted(Comparable::compareTo) .toList(); /* * Now gather Y values for every such category, even if some are null. * Specifying the data like this helps avoid Chart.js quirks during rendering. */ List<Dataset<Y>> datasetList = new ArrayList<>(data.size()); for (String datasetLabel : data.keySet()) { List<Y> datasetData = new ArrayList<>(categories.size()); for (String category : categories) { Y yValue = data.get(datasetLabel).get(category); datasetData.add(yValue); } datasetList.add(new Dataset<>(datasetLabel, datasetData, favoriteSet.contains(datasetLabel))); } return new BarChart<>(fileName, title, xLabel, yLabel, categories, datasetList, timeOnY); } } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/report/BenchmarkReport.java
package ai.timefold.solver.benchmark.impl.report; import static java.lang.Double.isFinite; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.time.ZoneId; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.ToLongFunction; import ai.timefold.solver.benchmark.impl.ranking.SolverRankingWeightFactory; import ai.timefold.solver.benchmark.impl.result.LoggingLevel; import ai.timefold.solver.benchmark.impl.result.PlannerBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.ProblemBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SolverBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.PureSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.SubSingleStatistic; import ai.timefold.solver.core.config.solver.EnvironmentMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.Version; public class BenchmarkReport { public static Configuration createFreeMarkerConfiguration() { Configuration freeMarkerCfg = new Configuration(new Version(2, 3, 32)); freeMarkerCfg.setDefaultEncoding("UTF-8"); return freeMarkerCfg; } private static final Logger LOGGER = LoggerFactory.getLogger(BenchmarkReport.class); public static final int CHARTED_SCORE_LEVEL_SIZE = 15; public static final int LOG_SCALE_MIN_DATASETS_COUNT = 5; private final PlannerBenchmarkResult plannerBenchmarkResult; private Locale locale = null; private ZoneId timezoneId = null; private Comparator<SolverBenchmarkResult> solverRankingComparator = null; private SolverRankingWeightFactory solverRankingWeightFactory = null; private List<BarChart<Double>> bestScoreSummaryChartList = null; private List<LineChart<Long, Double>> bestScoreScalabilitySummaryChartList = null; private List<BoxPlot> bestScoreDistributionSummaryChartList = null; private List<BarChart<Double>> winningScoreDifferenceSummaryChartList = null; private List<BarChart<Double>> worstScoreDifferencePercentageSummaryChartList = null; private LineChart<Long, Long> scoreCalculationSpeedSummaryChart; private LineChart<Long, Long> moveEvaluationSpeedSummaryChart; private BarChart<Double> worstScoreCalculationSpeedDifferencePercentageSummaryChart = null; private BarChart<Long> timeSpentSummaryChart = null; private LineChart<Long, Long> timeSpentScalabilitySummaryChart = null; private List<LineChart<Long, Double>> bestScorePerTimeSpentSummaryChartList = null; private Integer defaultShownScoreLevelIndex = null; private File htmlOverviewFile = null; public BenchmarkReport(PlannerBenchmarkResult plannerBenchmarkResult) { this.plannerBenchmarkResult = plannerBenchmarkResult; } public PlannerBenchmarkResult getPlannerBenchmarkResult() { return plannerBenchmarkResult; } public Locale getLocale() { return locale; } public void setLocale(Locale locale) { this.locale = locale; } @SuppressWarnings("unused") // Used by FreeMarker. public ZoneId getTimezoneId() { return timezoneId; } public void setTimezoneId(ZoneId timezoneId) { this.timezoneId = timezoneId; } public Comparator<SolverBenchmarkResult> getSolverRankingComparator() { return solverRankingComparator; } public void setSolverRankingComparator(Comparator<SolverBenchmarkResult> solverRankingComparator) { this.solverRankingComparator = solverRankingComparator; } public SolverRankingWeightFactory getSolverRankingWeightFactory() { return solverRankingWeightFactory; } public void setSolverRankingWeightFactory(SolverRankingWeightFactory solverRankingWeightFactory) { this.solverRankingWeightFactory = solverRankingWeightFactory; } @SuppressWarnings("unused") // Used by FreeMarker. public List<BarChart<Double>> getBestScoreSummaryChartList() { return bestScoreSummaryChartList; } @SuppressWarnings("unused") // Used by FreeMarker. public List<LineChart<Long, Double>> getBestScoreScalabilitySummaryChartList() { return bestScoreScalabilitySummaryChartList; } @SuppressWarnings("unused") // Used by FreeMarker. public List<BoxPlot> getBestScoreDistributionSummaryChartList() { return bestScoreDistributionSummaryChartList; } @SuppressWarnings("unused") // Used by FreeMarker. public List<BarChart<Double>> getWinningScoreDifferenceSummaryChartList() { return winningScoreDifferenceSummaryChartList; } @SuppressWarnings("unused") // Used by FreeMarker. public List<BarChart<Double>> getWorstScoreDifferencePercentageSummaryChartList() { return worstScoreDifferencePercentageSummaryChartList; } @SuppressWarnings("unused") // Used by FreeMarker. public LineChart<Long, Long> getScoreCalculationSpeedSummaryChart() { return scoreCalculationSpeedSummaryChart; } @SuppressWarnings("unused") // Used by FreeMarker. public LineChart<Long, Long> getMoveEvaluationSpeedSummaryChart() { return moveEvaluationSpeedSummaryChart; } @SuppressWarnings("unused") // Used by FreeMarker. public BarChart<Double> getWorstScoreCalculationSpeedDifferencePercentageSummaryChart() { return worstScoreCalculationSpeedDifferencePercentageSummaryChart; } @SuppressWarnings("unused") // Used by FreeMarker. public BarChart<Long> getTimeSpentSummaryChart() { return timeSpentSummaryChart; } @SuppressWarnings("unused") // Used by FreeMarker. public LineChart<Long, Long> getTimeSpentScalabilitySummaryChart() { return timeSpentScalabilitySummaryChart; } @SuppressWarnings("unused") // Used by FreeMarker. public List<LineChart<Long, Double>> getBestScorePerTimeSpentSummaryChartList() { return bestScorePerTimeSpentSummaryChartList; } @SuppressWarnings("unused") // Used by FreeMarker. public Integer getDefaultShownScoreLevelIndex() { return defaultShownScoreLevelIndex; } public File getHtmlOverviewFile() { return htmlOverviewFile; } // ************************************************************************ // Smart getters // ************************************************************************ @SuppressWarnings("unused") // Used by FreeMarker. public String getSolverRankingClassSimpleName() { Class solverRankingClass = getSolverRankingClass(); return solverRankingClass == null ? null : solverRankingClass.getSimpleName(); } @SuppressWarnings("unused") // Used by FreeMarker. public String getSolverRankingClassFullName() { Class solverRankingClass = getSolverRankingClass(); return solverRankingClass == null ? null : solverRankingClass.getName(); } // ************************************************************************ // Write methods // ************************************************************************ public void writeReport() { LOGGER.info("Generating benchmark report..."); plannerBenchmarkResult.accumulateResults(this); bestScoreSummaryChartList = createBestScoreSummaryChart(); bestScoreScalabilitySummaryChartList = createBestScoreScalabilitySummaryChart(); winningScoreDifferenceSummaryChartList = createWinningScoreDifferenceSummaryChart(); worstScoreDifferencePercentageSummaryChartList = createWorstScoreDifferencePercentageSummaryChart(); bestScoreDistributionSummaryChartList = createBestScoreDistributionSummaryChart(); scoreCalculationSpeedSummaryChart = createScoreCalculationSpeedSummaryChart(); moveEvaluationSpeedSummaryChart = createMoveEvaluationSpeedSummaryChart(); worstScoreCalculationSpeedDifferencePercentageSummaryChart = createWorstScoreCalculationSpeedDifferencePercentageSummaryChart(); timeSpentSummaryChart = createTimeSpentSummaryChart(); timeSpentScalabilitySummaryChart = createTimeSpentScalabilitySummaryChart(); bestScorePerTimeSpentSummaryChartList = createBestScorePerTimeSpentSummaryChart(); for (ProblemBenchmarkResult<?> problemBenchmarkResult : plannerBenchmarkResult.getUnifiedProblemBenchmarkResultList()) { for (SingleBenchmarkResult singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) { for (SubSingleBenchmarkResult subSingleBenchmarkResult : singleBenchmarkResult .getSubSingleBenchmarkResultList()) { if (!subSingleBenchmarkResult.hasAllSuccess()) { continue; } for (SubSingleStatistic<?, ?> subSingleStatistic : subSingleBenchmarkResult .getEffectiveSubSingleStatisticMap().values()) { try { subSingleStatistic.unhibernatePointList(); } catch (IllegalStateException e) { if (!plannerBenchmarkResult.getAggregation()) { throw new IllegalStateException("Failed to unhibernate point list of SubSingleStatistic (" + subSingleStatistic + ") of SubSingleBenchmark (" + subSingleBenchmarkResult + ").", e); } LOGGER.trace("This is expected, aggregator doesn't copy CSV files. Could not read CSV file " + "({}) of sub single statistic ({}).", subSingleStatistic.getCsvFile().getAbsolutePath(), subSingleStatistic); } } } } } List<Chart> chartsToWrite = new ArrayList<>(bestScoreSummaryChartList); chartsToWrite.addAll(bestScoreSummaryChartList); chartsToWrite.addAll(bestScoreScalabilitySummaryChartList); chartsToWrite.addAll(winningScoreDifferenceSummaryChartList); chartsToWrite.addAll(worstScoreDifferencePercentageSummaryChartList); chartsToWrite.addAll(bestScoreDistributionSummaryChartList); chartsToWrite.add(scoreCalculationSpeedSummaryChart); chartsToWrite.add(moveEvaluationSpeedSummaryChart); chartsToWrite.add(worstScoreCalculationSpeedDifferencePercentageSummaryChart); chartsToWrite.add(timeSpentSummaryChart); chartsToWrite.add(timeSpentScalabilitySummaryChart); chartsToWrite.addAll(bestScorePerTimeSpentSummaryChartList); for (ProblemBenchmarkResult<?> problemBenchmarkResult : plannerBenchmarkResult .getUnifiedProblemBenchmarkResultList()) { if (problemBenchmarkResult.hasAnySuccess()) { for (ProblemStatistic<?> problemStatistic : problemBenchmarkResult.getProblemStatisticList()) { problemStatistic.createChartList(this); chartsToWrite.addAll(problemStatistic.getChartList()); } for (SingleBenchmarkResult singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) { if (singleBenchmarkResult.hasAllSuccess()) { for (PureSubSingleStatistic<?, ?, ?> pureSubSingleStatistic : singleBenchmarkResult.getMedian() .getPureSubSingleStatisticList()) { pureSubSingleStatistic.createChartList(this); chartsToWrite.addAll(pureSubSingleStatistic.getChartList()); } } } } } // Now write all JavaScript files for the charts. chartsToWrite.parallelStream() .forEach(c -> c .writeToFile(plannerBenchmarkResult.getBenchmarkReportDirectory().toPath().resolve("website/js"))); for (ProblemBenchmarkResult<?> problemBenchmarkResult : plannerBenchmarkResult.getUnifiedProblemBenchmarkResultList()) { for (SingleBenchmarkResult singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) { for (SubSingleBenchmarkResult subSingleBenchmarkResult : singleBenchmarkResult .getSubSingleBenchmarkResultList()) { if (!subSingleBenchmarkResult.hasAllSuccess()) { continue; } for (SubSingleStatistic<?, ?> subSingleStatistic : subSingleBenchmarkResult .getEffectiveSubSingleStatisticMap().values()) { if (plannerBenchmarkResult.getAggregation()) { subSingleStatistic.setPointList(null); } else { subSingleStatistic.hibernatePointList(); } } } } } determineDefaultShownScoreLevelIndex(); writeHtmlOverviewFile(); } public List<String> getWarningList() { List<String> warningList = new ArrayList<>(); String javaVmName = System.getProperty("java.vm.name"); if (javaVmName != null && javaVmName.contains("Client VM")) { warningList.add("The Java VM (" + javaVmName + ") is the Client VM." + " This decreases performance." + " Maybe start the java process with the argument \"-server\" to get better results."); } Integer parallelBenchmarkCount = plannerBenchmarkResult.getParallelBenchmarkCount(); Integer availableProcessors = plannerBenchmarkResult.getAvailableProcessors(); if (parallelBenchmarkCount != null && availableProcessors != null && parallelBenchmarkCount > availableProcessors) { warningList.add("The parallelBenchmarkCount (" + parallelBenchmarkCount + ") is higher than the number of availableProcessors (" + availableProcessors + ")." + " This decreases performance." + " Maybe reduce the parallelBenchmarkCount."); } EnvironmentMode environmentMode = plannerBenchmarkResult.getEnvironmentMode(); if (environmentMode != null && environmentMode.isStepAssertOrMore()) { // Phase assert performance impact is negligible. warningList.add( "The environmentMode (%s) is step-asserting or more. This decreases performance. Maybe set the environmentMode to %s." .formatted(environmentMode, EnvironmentMode.PHASE_ASSERT)); } LoggingLevel loggingLevelTimefoldCore = plannerBenchmarkResult.getLoggingLevelTimefoldSolverCore(); if (loggingLevelTimefoldCore == LoggingLevel.TRACE) { warningList.add("The loggingLevel (" + loggingLevelTimefoldCore + ") of ai.timefold.solver.core is high." + " This decreases performance." + " Maybe set the loggingLevel to " + LoggingLevel.DEBUG + " or lower."); } return warningList; } private List<BarChart<Double>> createBestScoreSummaryChart() { List<BarChart.Builder<Double>> builderList = new ArrayList<>(CHARTED_SCORE_LEVEL_SIZE); for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) { String solverLabel = solverBenchmarkResult.getNameWithFavoriteSuffix(); for (SingleBenchmarkResult singleBenchmarkResult : solverBenchmarkResult.getSingleBenchmarkResultList()) { String problemLabel = singleBenchmarkResult.getProblemBenchmarkResult().getName(); if (singleBenchmarkResult.hasAllSuccess()) { double[] levelValues = singleBenchmarkResult.getAverageScore().toLevelDoubles(); for (int i = 0; i < levelValues.length && i < CHARTED_SCORE_LEVEL_SIZE; i++) { if (i >= builderList.size()) { builderList.add(new BarChart.Builder<>()); } if (isFinite(levelValues[i])) { BarChart.Builder<Double> builder = builderList.get(i); builder.add(solverLabel, problemLabel, levelValues[i]); if (solverBenchmarkResult.isFavorite()) { builder.markFavorite(solverLabel); } } } } } } List<BarChart<Double>> chartList = new ArrayList<>(builderList.size()); int scoreLevelIndex = 0; for (BarChart.Builder<Double> builder : builderList) { String scoreLevelLabel = plannerBenchmarkResult.findScoreLevelLabel(scoreLevelIndex); BarChart<Double> chart = builder.build("bestScoreSummaryChart" + scoreLevelIndex, "Best " + scoreLevelLabel + " summary (higher is better)", "Data", "Best " + scoreLevelLabel, false); chartList.add(chart); scoreLevelIndex++; } return chartList; } private List<LineChart<Long, Double>> createBestScoreScalabilitySummaryChart() { List<LineChart.Builder<Long, Double>> builderList = new ArrayList<>(CHARTED_SCORE_LEVEL_SIZE); for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) { String solverLabel = solverBenchmarkResult.getNameWithFavoriteSuffix(); for (SingleBenchmarkResult singleBenchmarkResult : solverBenchmarkResult.getSingleBenchmarkResultList()) { if (singleBenchmarkResult.hasAllSuccess()) { long problemScale = singleBenchmarkResult.getProblemBenchmarkResult().getProblemScale(); double[] levelValues = singleBenchmarkResult.getAverageScore().toLevelDoubles(); for (int i = 0; i < levelValues.length && i < CHARTED_SCORE_LEVEL_SIZE; i++) { if (i >= builderList.size()) { builderList.add(new LineChart.Builder<>()); } LineChart.Builder<Long, Double> builder = builderList.get(i); builder.add(solverLabel, problemScale, levelValues[i]); if (solverBenchmarkResult.isFavorite()) { builder.markFavorite(solverLabel); } } } } } List<LineChart<Long, Double>> chartList = new ArrayList<>(builderList.size()); int scoreLevelIndex = 0; for (LineChart.Builder<Long, Double> builder : builderList) { String scoreLevelLabel = plannerBenchmarkResult.findScoreLevelLabel(scoreLevelIndex); chartList.add(builder.build("bestScoreScalabilitySummaryChart" + scoreLevelIndex, "Best " + scoreLevelLabel + " scalability summary (higher is better)", "Problem scale", "Best " + scoreLevelLabel, false, false, false)); scoreLevelIndex++; } return chartList; } private List<BoxPlot> createBestScoreDistributionSummaryChart() { List<BoxPlot.Builder> builderList = new ArrayList<>(CHARTED_SCORE_LEVEL_SIZE); for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) { String solverLabel = solverBenchmarkResult.getNameWithFavoriteSuffix(); for (SingleBenchmarkResult singleBenchmarkResult : solverBenchmarkResult.getSingleBenchmarkResultList()) { String problemLabel = singleBenchmarkResult.getProblemBenchmarkResult().getName(); if (singleBenchmarkResult.hasAllSuccess()) { List<List<Double>> distributionLevelList = new ArrayList<>(CHARTED_SCORE_LEVEL_SIZE); for (SubSingleBenchmarkResult subSingleBenchmarkResult : singleBenchmarkResult .getSubSingleBenchmarkResultList()) { double[] levelValues = subSingleBenchmarkResult.getAverageScore().toLevelDoubles(); for (int i = 0; i < levelValues.length && i < CHARTED_SCORE_LEVEL_SIZE; i++) { if (i >= distributionLevelList.size()) { distributionLevelList.add(new ArrayList<>(singleBenchmarkResult.getSubSingleCount())); } distributionLevelList.get(i).add(levelValues[i]); } } for (int i = 0; i < distributionLevelList.size() && i < CHARTED_SCORE_LEVEL_SIZE; i++) { if (i >= builderList.size()) { builderList.add(new BoxPlot.Builder()); } BoxPlot.Builder builder = builderList.get(i); for (double y : distributionLevelList.get(i)) { builder.add(solverLabel, problemLabel, y); } if (solverBenchmarkResult.isFavorite()) { builder.markFavorite(solverLabel); } } } } } List<BoxPlot> chartList = new ArrayList<>(builderList.size()); int scoreLevelIndex = 0; for (BoxPlot.Builder builder : builderList) { String scoreLevelLabel = plannerBenchmarkResult.findScoreLevelLabel(scoreLevelIndex); BoxPlot boxPlot = builder.build("bestScoreDistributionSummaryChart" + scoreLevelIndex, "Best " + scoreLevelLabel + " distribution summary (higher is better)", "Data", "Best " + scoreLevelLabel); chartList.add(boxPlot); scoreLevelIndex++; } return chartList; } private List<BarChart<Double>> createWinningScoreDifferenceSummaryChart() { return createScoreDifferenceSummaryChart( singleBenchmarkResult -> singleBenchmarkResult.getWinningScoreDifference().toLevelDoubles(), scoreLevelIndex -> "winningScoreDifferenceSummaryChart" + scoreLevelIndex, scoreLevelLabel -> "Winning " + scoreLevelLabel + " difference summary (higher is better)", scoreLevelLabel -> "Winning " + scoreLevelLabel + " difference"); } private List<BarChart<Double>> createWorstScoreDifferencePercentageSummaryChart() { return createScoreDifferenceSummaryChart( singleBenchmarkResult -> singleBenchmarkResult.getWorstScoreDifferencePercentage().percentageLevels(), scoreLevelIndex -> "worstScoreDifferencePercentageSummaryChart" + scoreLevelIndex, scoreLevelLabel -> "Worst " + scoreLevelLabel + " difference percentage" + " summary (higher is better)", scoreLevelLabel -> "Worst " + scoreLevelLabel + " difference percentage"); } private List<BarChart<Double>> createScoreDifferenceSummaryChart( Function<SingleBenchmarkResult, double[]> scoreLevelValueFunction, IntFunction<String> idFunction, Function<String, String> titleFunction, Function<String, String> yLabelFunction) { List<BarChart.Builder<Double>> builderList = new ArrayList<>(CHARTED_SCORE_LEVEL_SIZE); for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) { String solverLabel = solverBenchmarkResult.getNameWithFavoriteSuffix(); for (SingleBenchmarkResult singleBenchmarkResult : solverBenchmarkResult.getSingleBenchmarkResultList()) { String problemLabel = singleBenchmarkResult.getProblemBenchmarkResult().getName(); if (singleBenchmarkResult.hasAllSuccess()) { double[] levelValues = scoreLevelValueFunction.apply(singleBenchmarkResult); for (int i = 0; i < levelValues.length && i < CHARTED_SCORE_LEVEL_SIZE; i++) { if (i >= builderList.size()) { builderList.add(new BarChart.Builder<>()); } if (isFinite(levelValues[i])) { BarChart.Builder<Double> builder = builderList.get(i); builder.add(solverLabel, problemLabel, levelValues[i] * 100); if (solverBenchmarkResult.isFavorite()) { builder.markFavorite(solverLabel); } } } } } } List<BarChart<Double>> chartList = new ArrayList<>(builderList.size()); int scoreLevelIndex = 0; for (BarChart.Builder<Double> builder : builderList) { String scoreLevelLabel = plannerBenchmarkResult.findScoreLevelLabel(scoreLevelIndex); BarChart<Double> chart = builder.build(idFunction.apply(scoreLevelIndex), titleFunction.apply(scoreLevelLabel), "Data", yLabelFunction.apply(scoreLevelLabel), false); chartList.add(chart); scoreLevelIndex++; } return chartList; } private LineChart<Long, Long> createScoreCalculationSpeedSummaryChart() { return createScalabilitySummaryChart(SingleBenchmarkResult::getScoreCalculationSpeed, "scoreCalculationSpeedSummaryChart", "Score calculation speed summary (higher is better)", "Score calculation speed per second", false); } private LineChart<Long, Long> createMoveEvaluationSpeedSummaryChart() { return createScalabilitySummaryChart(SingleBenchmarkResult::getMoveEvaluationSpeed, "moveEvaluationSpeedSummaryChart", "Move evaluation speed summary (higher is better)", "Move evaluation speed per second", false); } private BarChart<Double> createWorstScoreCalculationSpeedDifferencePercentageSummaryChart() { return createSummaryBarChart(result -> result.getWorstScoreCalculationSpeedDifferencePercentage() * 100, "worstScoreCalculationSpeedDifferencePercentageSummaryChart", "Worst score calculation speed difference percentage summary (higher is better)", "Worst score calculation speed difference percentage", false); } private BarChart<Long> createTimeSpentSummaryChart() { return createSummaryBarChart(SingleBenchmarkResult::getTimeMillisSpent, "timeSpentSummaryChart", "Time spent summary (lower time is better)", "Time spent", true); } private <N extends Number & Comparable<N>> BarChart<N> createSummaryBarChart( Function<SingleBenchmarkResult, N> valueFunction, String id, String title, String yLabel, boolean timeOnY) { BarChart.Builder<N> builder = new BarChart.Builder<>(); for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) { String solverLabel = solverBenchmarkResult.getNameWithFavoriteSuffix(); for (SingleBenchmarkResult singleBenchmarkResult : solverBenchmarkResult.getSingleBenchmarkResultList()) { String problemLabel = singleBenchmarkResult.getProblemBenchmarkResult().getName(); if (singleBenchmarkResult.hasAllSuccess()) { builder.add(solverLabel, problemLabel, valueFunction.apply(singleBenchmarkResult)); if (solverBenchmarkResult.isFavorite()) { builder.markFavorite(solverLabel); } } } } return builder.build(id, title, "Data", yLabel, timeOnY); } private LineChart<Long, Long> createTimeSpentScalabilitySummaryChart() { return createScalabilitySummaryChart(SingleBenchmarkResult::getTimeMillisSpent, "timeSpentScalabilitySummaryChart", "Time spent scalability summary (lower is better)", "Time spent", true); } private LineChart<Long, Long> createScalabilitySummaryChart(ToLongFunction<SingleBenchmarkResult> valueFunction, String id, String title, String yLabel, boolean timeOnY) { LineChart.Builder<Long, Long> builder = new LineChart.Builder<>(); for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) { String solverLabel = solverBenchmarkResult.getNameWithFavoriteSuffix(); if (solverBenchmarkResult.isFavorite()) { builder.markFavorite(solverLabel); } solverBenchmarkResult.getSingleBenchmarkResultList() .stream() .filter(SingleBenchmarkResult::hasAllSuccess) .forEach(singleBenchmarkResult -> { long problemScale = singleBenchmarkResult.getProblemBenchmarkResult().getProblemScale(); long timeMillisSpent = valueFunction.applyAsLong(singleBenchmarkResult); builder.add(solverLabel, problemScale, timeMillisSpent); }); } return builder.build(id, title, "Problem scale", yLabel, false, false, timeOnY); } private List<LineChart<Long, Double>> createBestScorePerTimeSpentSummaryChart() { List<LineChart.Builder<Long, Double>> builderList = new ArrayList<>(CHARTED_SCORE_LEVEL_SIZE); for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) { String solverLabel = solverBenchmarkResult.getNameWithFavoriteSuffix(); for (SingleBenchmarkResult singleBenchmarkResult : solverBenchmarkResult.getSingleBenchmarkResultList()) { if (singleBenchmarkResult.hasAllSuccess()) { long timeMillisSpent = singleBenchmarkResult.getTimeMillisSpent(); double[] levelValues = singleBenchmarkResult.getAverageScore().toLevelDoubles(); for (int i = 0; i < levelValues.length && i < CHARTED_SCORE_LEVEL_SIZE; i++) { if (i >= builderList.size()) { builderList.add(new LineChart.Builder<>()); } LineChart.Builder<Long, Double> builder = builderList.get(i); builder.add(solverLabel, timeMillisSpent, levelValues[i]); if (solverBenchmarkResult.isFavorite()) { builder.markFavorite(solverLabel); } } } } } bestScorePerTimeSpentSummaryChartList = new ArrayList<>(builderList.size()); int scoreLevelIndex = 0; for (LineChart.Builder<Long, Double> builder : builderList) { String scoreLevelLabel = plannerBenchmarkResult.findScoreLevelLabel(scoreLevelIndex); LineChart<Long, Double> chart = builder.build("bestScorePerTimeSpentSummaryChart" + scoreLevelIndex, "Best " + scoreLevelLabel + " per time spent summary (higher left is better)", "Time spent", "Best " + scoreLevelLabel, false, true, false); bestScorePerTimeSpentSummaryChartList.add(chart); scoreLevelIndex++; } return bestScorePerTimeSpentSummaryChartList; } // ************************************************************************ // Chart helper methods // ************************************************************************ private void determineDefaultShownScoreLevelIndex() { defaultShownScoreLevelIndex = Integer.MAX_VALUE; for (ProblemBenchmarkResult<Object> problemBenchmarkResult : plannerBenchmarkResult .getUnifiedProblemBenchmarkResultList()) { if (problemBenchmarkResult.hasAnySuccess()) { double[] winningScoreLevels = problemBenchmarkResult.getWinningSingleBenchmarkResult().getAverageScore().toLevelDoubles(); int[] differenceCount = new int[winningScoreLevels.length]; for (int i = 0; i < differenceCount.length; i++) { differenceCount[i] = 0; } for (SingleBenchmarkResult singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) { if (singleBenchmarkResult.hasAllSuccess()) { double[] scoreLevels = singleBenchmarkResult.getAverageScore().toLevelDoubles(); for (int i = 0; i < scoreLevels.length; i++) { if (scoreLevels[i] != winningScoreLevels[i]) { differenceCount[i] = differenceCount[i] + 1; } } } } int firstInterestingLevel = differenceCount.length - 1; for (int i = 0; i < differenceCount.length; i++) { if (differenceCount[i] > 0) { firstInterestingLevel = i; break; } } if (defaultShownScoreLevelIndex > firstInterestingLevel) { defaultShownScoreLevelIndex = firstInterestingLevel; } } } } private void writeHtmlOverviewFile() { File benchmarkReportDirectory = plannerBenchmarkResult.getBenchmarkReportDirectory(); WebsiteResourceUtils.copyResourcesTo(benchmarkReportDirectory); htmlOverviewFile = new File(benchmarkReportDirectory, "index.html"); Configuration freemarkerCfg = createFreeMarkerConfiguration(); freemarkerCfg.setLocale(locale); freemarkerCfg.setClassForTemplateLoading(BenchmarkReport.class, ""); freemarkerCfg.setCustomNumberFormats(Map.of("msDuration", MillisecondDurationNumberFormatFactory.INSTANCE)); String templateFilename = "benchmarkReport.html.ftl"; Map<String, Object> model = new HashMap<>(); model.put("benchmarkReport", this); model.put("reportHelper", new ReportHelper()); try (Writer writer = new OutputStreamWriter(new FileOutputStream(htmlOverviewFile), "UTF-8")) { Template template = freemarkerCfg.getTemplate(templateFilename); template.process(model, writer); } catch (IOException e) { throw new IllegalArgumentException("Can not read templateFilename (" + templateFilename + ") or write htmlOverviewFile (" + htmlOverviewFile + ").", e); } catch (TemplateException e) { throw new IllegalArgumentException("Can not process Freemarker templateFilename (" + templateFilename + ") to htmlOverviewFile (" + htmlOverviewFile + ").", e); } } private Class getSolverRankingClass() { if (solverRankingComparator != null) { return solverRankingComparator.getClass(); } else if (solverRankingWeightFactory != null) { return solverRankingWeightFactory.getClass(); } else { return null; } } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/report/BenchmarkReportFactory.java
package ai.timefold.solver.benchmark.impl.report; import java.time.ZoneId; import java.util.Comparator; import ai.timefold.solver.benchmark.config.report.BenchmarkReportConfig; import ai.timefold.solver.benchmark.impl.ranking.SolverRankingWeightFactory; import ai.timefold.solver.benchmark.impl.ranking.TotalRankSolverRankingWeightFactory; import ai.timefold.solver.benchmark.impl.ranking.TotalScoreSolverRankingComparator; import ai.timefold.solver.benchmark.impl.ranking.WorstScoreSolverRankingComparator; import ai.timefold.solver.benchmark.impl.result.PlannerBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SolverBenchmarkResult; import ai.timefold.solver.core.config.util.ConfigUtils; public class BenchmarkReportFactory { private final BenchmarkReportConfig config; public BenchmarkReportFactory(BenchmarkReportConfig config) { this.config = config; } public BenchmarkReport buildBenchmarkReport(PlannerBenchmarkResult plannerBenchmark) { BenchmarkReport benchmarkReport = new BenchmarkReport(plannerBenchmark); benchmarkReport.setLocale(config.determineLocale()); benchmarkReport.setTimezoneId(ZoneId.systemDefault()); supplySolverRanking(benchmarkReport); return benchmarkReport; } protected void supplySolverRanking(BenchmarkReport benchmarkReport) { var solverRankingType = config.getSolverRankingType(); var solverRankingComparatorClass = config.getSolverRankingComparatorClass(); var solverRankingWeightFactoryClass = config.getSolverRankingWeightFactoryClass(); if (solverRankingType != null && solverRankingComparatorClass != null) { throw new IllegalStateException( "The PlannerBenchmark cannot have a solverRankingType (%s) and a solverRankingComparatorClass (%s) at the same time." .formatted(solverRankingType, solverRankingComparatorClass.getName())); } else if (solverRankingType != null && solverRankingWeightFactoryClass != null) { throw new IllegalStateException( "The PlannerBenchmark cannot have a solverRankingType (%s) and a solverRankingWeightFactoryClass (%s) at the same time." .formatted(solverRankingType, solverRankingWeightFactoryClass.getName())); } else if (solverRankingComparatorClass != null && solverRankingWeightFactoryClass != null) { throw new IllegalStateException( "The PlannerBenchmark cannot have a solverRankingComparatorClass (%s) and a solverRankingWeightFactoryClass (%s) at the same time." .formatted(solverRankingComparatorClass.getName(), solverRankingWeightFactoryClass.getName())); } Comparator<SolverBenchmarkResult> solverRankingComparator = null; SolverRankingWeightFactory solverRankingWeightFactory = null; if (solverRankingType != null) { switch (solverRankingType) { case TOTAL_SCORE: solverRankingComparator = new TotalScoreSolverRankingComparator(); break; case WORST_SCORE: solverRankingComparator = new WorstScoreSolverRankingComparator(); break; case TOTAL_RANKING: solverRankingWeightFactory = new TotalRankSolverRankingWeightFactory(); break; default: throw new IllegalStateException("The solverRankingType (%s) is not implemented." .formatted(solverRankingType)); } } if (solverRankingComparatorClass != null) { solverRankingComparator = ConfigUtils.newInstance(config, "solverRankingComparatorClass", solverRankingComparatorClass); } if (solverRankingWeightFactoryClass != null) { solverRankingWeightFactory = ConfigUtils.newInstance(config, "solverRankingWeightFactoryClass", solverRankingWeightFactoryClass); } if (solverRankingComparator != null) { benchmarkReport.setSolverRankingComparator(solverRankingComparator); } else if (solverRankingWeightFactory != null) { benchmarkReport.setSolverRankingWeightFactory(solverRankingWeightFactory); } else { benchmarkReport.setSolverRankingComparator(new TotalScoreSolverRankingComparator()); } } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/report/BoxPlot.java
package ai.timefold.solver.benchmark.impl.report; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.Set; import java.util.TreeMap; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; /** * * @param title * @param xLabel * @param yLabel * @param categories Typically dataset names. * @param ranges Keys are range labels (such "Machine reassignment Tabu Search"), values are ranges for each category. * Value may be null if there is no data for a category, such as the solver did not run on the dataset. * @param favorites Range labels that should be highlighted. */ public record BoxPlot(String id, String title, String xLabel, String yLabel, List<String> categories, Map<String, List<Range>> ranges, Set<String> favorites) implements Chart { public BoxPlot { id = Chart.makeIdUnique(id); } @Override public void writeToFile(Path parentFolder) { File file = new File(parentFolder.toFile(), id() + ".js"); file.getParentFile().mkdirs(); Configuration freeMarkerCfg = BenchmarkReport.createFreeMarkerConfiguration(); freeMarkerCfg.setClassForTemplateLoading(getClass(), ""); String templateFilename = "chart-box.js.ftl"; Map<String, Object> model = new HashMap<>(); model.put("chart", this); try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) { Template template = freeMarkerCfg.getTemplate(templateFilename); template.process(model, writer); } catch (IOException e) { throw new IllegalArgumentException("Can not read templateFilename (" + templateFilename + ") or write chart file (" + file + ").", e); } catch (TemplateException e) { throw new IllegalArgumentException("Can not process Freemarker templateFilename (" + templateFilename + ") to chart file (" + id + ").", e); } } @SuppressWarnings("unused") // Used by FreeMarker. public static final class Builder { private final Map<String, NavigableMap<String, List<Double>>> data = new LinkedHashMap<>(); private final Set<String> favoriteSet = new HashSet<>(); public Builder add(String dataset, String category, double y) { data.computeIfAbsent(dataset, k -> new TreeMap<>()) .computeIfAbsent(category, k -> new ArrayList<>()) .add(y); return this; } public Set<String> keys() { return data.keySet(); } public Builder markFavorite(String dataset) { favoriteSet.add(dataset); return this; } public BoxPlot build(String fileName, String title, String xLabel, String yLabel) { // First find all categories across all data sets. List<String> categories = data.values().stream() .flatMap(m -> m.keySet().stream()) .distinct() .sorted(Comparable::compareTo) .toList(); // Now gather Y values for every such category, even if some are null. // Specifying the data like this helps avoid Chart.js quirks during rendering. Map<String, List<Range>> rangeMap = new LinkedHashMap<>(data.size()); for (String rangeLabel : data.keySet()) { List<Range> rangeList = new ArrayList<>(); for (String category : categories) { List<Double> values = data.get(rangeLabel) .getOrDefault(category, Collections.emptyList()); if (values.size() == 0) { rangeList.add(null); } else { DescriptiveStatistics stats = new DescriptiveStatistics(); values.forEach(stats::addValue); rangeList.add(new Range(rangeLabel, stats.getMin(), stats.getPercentile(25), stats.getPercentile(50), stats.getPercentile(75), stats.getMax(), stats.getMean())); } } rangeMap.put(rangeLabel, rangeList); } return new BoxPlot(fileName, title, xLabel, yLabel, categories, rangeMap, favoriteSet); } } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/report/Chart.java
package ai.timefold.solver.benchmark.impl.report; import java.nio.file.Path; @SuppressWarnings("unused") // Used by FreeMarker. public interface Chart { /** * It is not possible to guarantee that an ID we generate in the Java code * will be unique in the HTML page without making the Java code complex enough to track those IDs. * For that reason, we take a human-readable ID and make it unique by appending a random number. * * @param id never null * @return never null, guaranteed to be unique */ static String makeIdUnique(String id) { return id + "_" + Integer.toHexString((int) (Math.random() * 1_000_000)); } String id(); String title(); String xLabel(); String yLabel(); void writeToFile(Path parentFolder); }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/report/Dataset.java
package ai.timefold.solver.benchmark.impl.report; import java.util.List; public record Dataset<X extends Number>(String label, List<X> data, boolean favorite) { }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/report/LineChart.java
package ai.timefold.solver.benchmark.impl.report; import static ai.timefold.solver.benchmark.impl.report.BenchmarkReport.LOG_SCALE_MIN_DATASETS_COUNT; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.math.BigDecimal; import java.math.MathContext; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.stream.IntStream; import ai.timefold.solver.core.impl.util.Pair; import freemarker.template.TemplateException; public record LineChart<X extends Number & Comparable<X>, Y extends Number & Comparable<Y>>(String id, String title, String xLabel, String yLabel, List<X> keys, List<Dataset<Y>> datasets, boolean stepped, boolean timeOnX, boolean timeOnY) implements Chart { public LineChart { id = Chart.makeIdUnique(id); } @SuppressWarnings("unused") // Used by FreeMarker. public BigDecimal xMin() { return min(keys); } static <Number_ extends Number & Comparable<Number_>> BigDecimal min(List<Number_> values) { if (values.isEmpty()) { return BigDecimal.ZERO; } var min = Collections.min(values).doubleValue(); if (min > 0) { // Always start with zero. return BigDecimal.ZERO; } else { return BigDecimal.valueOf(min); } } @SuppressWarnings("unused") // Used by FreeMarker. public BigDecimal xMax() { return max(keys); } static <Number_ extends Number & Comparable<Number_>> BigDecimal max(List<Number_> values) { if (values.isEmpty()) { return BigDecimal.ZERO; } var max = Collections.max(values).doubleValue(); if (max < 0) { // Always start with zero. return BigDecimal.ZERO; } else { return BigDecimal.valueOf(max); } } @SuppressWarnings("unused") // Used by FreeMarker. public BigDecimal yMin() { return min(getYValues()); } private List<Y> getYValues() { return datasets.stream() .flatMap(d -> d.data().stream()) .filter(Objects::nonNull) .toList(); } @SuppressWarnings("unused") // Used by FreeMarker. public BigDecimal yMax() { return max(getYValues()); } @SuppressWarnings("unused") // Used by FreeMarker. public BigDecimal xStepSize() { return stepSize(xMin(), xMax()); } @SuppressWarnings("unused") // Used by FreeMarker. public BigDecimal yStepSize() { return stepSize(yMin(), yMax()); } @SuppressWarnings("unused") // Used by FreeMarker. public boolean xLogarithmic() { if (timeOnX) { // Logarithmic time doesn't make sense. return false; } return useLogarithmicProblemScale(keys); } @SuppressWarnings("unused") // Used by FreeMarker. public boolean yLogarithmic() { if (timeOnY) { // Logarithmic time doesn't make sense. return false; } return useLogarithmicProblemScale(getYValues()); } @SuppressWarnings("unused") // Used by FreeMarker. public List<Pair<X, Y>> points(String label) { var dataset = datasets().stream().filter(d -> d.label().equals(label)).findFirst() .orElseThrow(() -> new IllegalArgumentException("Dataset %s not found.".formatted(label))); return IntStream.range(0, dataset.data().size()) .filter(i -> dataset.data().get(i) != null) .mapToObj(i -> new Pair<>(keys().get(i), dataset.data().get(i))) .toList(); } static <N extends Number & Comparable<N>> boolean useLogarithmicProblemScale(List<N> seriesList) { NavigableSet<Double> valueSet = new TreeSet<>(); for (var dataItem : seriesList) { var value = dataItem.doubleValue(); if (value <= 0) { // Logarithm undefined. return false; } valueSet.add(value); } if (valueSet.size() < LOG_SCALE_MIN_DATASETS_COUNT) { return false; } // If 60% of the points are in 20% of the value space, use a logarithmic scale. var threshold = 0.2 * (valueSet.last() - valueSet.first()); var belowThresholdCount = valueSet.headSet(threshold).size(); return belowThresholdCount >= (0.6 * valueSet.size()); } static BigDecimal stepSize(BigDecimal min, BigDecimal max) { // Prevents ticks of ugly values. // For example, if the diff is 123_456_789, the step size will be 1_000_000. var diff = max.subtract(min).abs(); if (diff.signum() == 0) { return BigDecimal.ONE; } else { var nearestPowerOfTen = (int) Math.round(Math.log10(diff.doubleValue())); return BigDecimal.TEN.pow(nearestPowerOfTen - 2, MathContext.DECIMAL64); } } @Override public void writeToFile(Path parentFolder) { var file = new File(parentFolder.toFile(), id() + ".js"); file.getParentFile().mkdirs(); var freeMarkerCfg = BenchmarkReport.createFreeMarkerConfiguration(); freeMarkerCfg.setClassForTemplateLoading(getClass(), ""); var templateFilename = "chart-line.js.ftl"; Map<String, Object> model = new HashMap<>(); model.put("chart", this); try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) { var template = freeMarkerCfg.getTemplate(templateFilename); template.process(model, writer); } catch (IOException e) { throw new IllegalArgumentException("Can not read templateFilename (" + templateFilename + ") or write chart file (" + file + ").", e); } catch (TemplateException e) { throw new IllegalArgumentException("Can not process Freemarker templateFilename (" + templateFilename + ") to chart file (" + id + ").", e); } } public static final class Builder<X extends Number & Comparable<X>, Y extends Number & Comparable<Y>> { private static final int MAX_CHART_WIDTH = 3840; private final Map<String, NavigableMap<X, Y>> data = new LinkedHashMap<>(); private final Set<String> favoriteSet = new HashSet<>(); public Builder<X, Y> add(String dataset, X x, Y y) { data.computeIfAbsent(dataset, k -> new TreeMap<>()) .put(x, y); return this; } public Set<String> keys() { return data.keySet(); } public int count(String dataset) { return data.getOrDefault(dataset, Collections.emptyNavigableMap()).size(); } public Y getLastValue(String dataset) { return data.getOrDefault(dataset, Collections.emptyNavigableMap()) .lastEntry() .getValue(); } public Builder<X, Y> markFavorite(String dataset) { favoriteSet.add(dataset); return this; } public LineChart<X, Y> build(String fileName, String title, String xLabel, String yLabel, boolean stepped, boolean timeOnX, boolean timeOnY) { /* * If two of the same value have another of that value between them, remove it. * This allows Chart.js to only draw the absolute minimum necessary points. */ data.values().forEach(map -> { var entries = map.entrySet().stream().toList(); if (entries.size() < 3) { return; } for (var i = 0; i < entries.size() - 2; i++) { var entry1 = entries.get(i); var entry2 = entries.get(i + 1); if (!entry1.getValue().equals(entry2.getValue())) { continue; } var entry3 = entries.get(i + 2); if (entry2.getValue().equals(entry3.getValue())) { map.remove(entry2.getKey()); } } }); /* * Sometimes, when the dataset size is large, it can cause the browser to freeze or use excessive memory * while rendering the line chart. To solve the issue of a large volume of data points, we use the * Largest-Triangle-Three-Buckets algorithm to down-sample the data. */ Map<String, Map<X, Y>> datasetMap = new LinkedHashMap<>(data.size()); for (var entry : data.entrySet()) { datasetMap.put(entry.getKey(), largestTriangleThreeBuckets(entry.getValue(), MAX_CHART_WIDTH)); } // We need to merge all the keys after the down-sampling process to create a consistent X values list. // The xValues list size can be "MAX_CHART_WIDTH * data.size" in the worst case. var xValues = data.values().stream() .flatMap(k -> k.keySet().stream()) .distinct() .sorted(Comparable::compareTo) .toList(); /* * Finally gather Y values for every such X, even if some are null. * Specifying the data like this helps avoid Chart.js quirks during rendering. */ List<Dataset<Y>> datasetList = new ArrayList<>(data.size()); for (var entry : datasetMap.entrySet()) { List<Y> datasetData = new ArrayList<>(xValues.size()); var dataset = entry.getValue(); for (var xValue : xValues) { var yValue = dataset.get(xValue); datasetData.add(yValue); } datasetList.add(new Dataset<>(entry.getKey(), datasetData, favoriteSet.contains(entry.getKey()))); } return new LineChart<>(fileName, title, xLabel, yLabel, xValues, datasetList, stepped, timeOnX, timeOnY); } /** * The method uses the Largest-Triangle-Three-Buckets approach to reduce the size of the data points list. * * @param datasetDataMap The ordered map of data points * @param sampleSize The final sample size * * @return The compressed data * * @see https://github.com/sveinn-steinarsson/flot-downsample/ */ private Map<X, Y> largestTriangleThreeBuckets(NavigableMap<X, Y> datasetDataMap, int sampleSize) { if (datasetDataMap.size() <= sampleSize) { return datasetDataMap; } var sampled = new LinkedHashMap<X, Y>(sampleSize); List<X> keys = new ArrayList<>(datasetDataMap.keySet()); // Bucket size. Leave room for start and end data points var every = (double) (datasetDataMap.size() - 2) / (double) (sampleSize - 2); var a = 0; // Initially a is the first point in the triangle var nextA = 0; Y maxAreaPoint = null; double maxArea; double area; // Always add the first point datasetDataMap.entrySet().stream().findFirst().ifPresent(e -> sampled.put(e.getKey(), e.getValue())); for (var i = 0; i < sampleSize - 2; i++) { // Calculate point average for next bucket (containing c) var avgX = 0.0D; var avgY = 0.0D; var avgRangeStart = (int) Math.floor((i + 1) * every) + 1; var avgRangeEnd = (int) Math.floor((i + 2) * every) + 1; avgRangeEnd = Math.min(avgRangeEnd, datasetDataMap.size()); var avgRangeLength = avgRangeEnd - avgRangeStart; while (avgRangeStart < avgRangeEnd) { avgX += keys.get(avgRangeStart).doubleValue(); avgY += datasetDataMap.get(keys.get(avgRangeStart)).doubleValue(); avgRangeStart++; } avgX /= avgRangeLength; avgY /= avgRangeLength; // Get the range for this bucket var rangeOffs = (int) Math.floor(i * every) + 1; var rangeTo = (int) Math.floor((i + 1) * every) + 1; // Point a var pointAX = keys.get(a).doubleValue(); var pointAY = datasetDataMap.get(keys.get(a)).doubleValue(); maxArea = -1; while (rangeOffs < rangeTo) { // Calculate triangle area over three buckets area = Math.abs((pointAX - avgX) * (datasetDataMap.get(keys.get(rangeOffs)).doubleValue() - pointAY) - (pointAX - keys.get(rangeOffs).doubleValue()) * (avgY - pointAY)) * 0.5D; if (area > maxArea) { maxArea = area; maxAreaPoint = datasetDataMap.get(keys.get(rangeOffs)); // Next a is this b nextA = rangeOffs; } rangeOffs++; } // Pick this point from the bucket sampled.put(keys.get(nextA), maxAreaPoint); // This a is the next a (chosen b) a = nextA; } // Always add last sampled.put(keys.get(keys.size() - 1), datasetDataMap.get(keys.get(keys.size() - 1))); return sampled; } } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/report/MillisecondDurationNumberFormatFactory.java
package ai.timefold.solver.benchmark.impl.report; import java.time.Duration; import java.util.Locale; import freemarker.core.Environment; import freemarker.core.TemplateFormatUtil; import freemarker.core.TemplateNumberFormat; import freemarker.core.TemplateNumberFormatFactory; import freemarker.core.TemplateValueFormatException; import freemarker.template.TemplateModelException; import freemarker.template.TemplateNumberModel; public final class MillisecondDurationNumberFormatFactory extends TemplateNumberFormatFactory { static final MillisecondDurationNumberFormatFactory INSTANCE = new MillisecondDurationNumberFormatFactory(); @Override public TemplateNumberFormat get(String params, Locale locale, Environment environment) throws TemplateValueFormatException { TemplateFormatUtil.checkHasNoParameters(params); return new MillisecondDurationNumberFormat(locale); } static final class MillisecondDurationNumberFormat extends TemplateNumberFormat { private final Locale locale; public MillisecondDurationNumberFormat(Locale locale) { this.locale = locale; } @Override public String formatToPlainText(TemplateNumberModel templateNumberModel) throws TemplateModelException { Number n = templateNumberModel.getAsNumber(); if (n == null) { return "None."; } long millis = n.longValue(); return formatMillis(locale, millis); } @Override public boolean isLocaleBound() { return true; } @Override public String getDescription() { return "Millisecond Duration"; } } public static String formatMillis(Locale locale, long millis) { if (millis == 0L) { return "0 ms."; } Duration duration = Duration.ofMillis(millis); long daysPart = duration.toDaysPart(); long hoursPart = duration.toHoursPart(); long minutesPart = duration.toMinutesPart(); double seconds = duration.toSecondsPart() + (duration.toMillisPart() / 1000.0d); if (daysPart > 0) { return String.format(locale, "%02d:%02d:%02d:%06.3f s. (%,d ms.)", daysPart, hoursPart, minutesPart, seconds, millis); } else if (hoursPart > 0) { return String.format(locale, "%02d:%02d:%06.3f s. (%,d ms.)", hoursPart, minutesPart, seconds, millis); } else if (minutesPart > 0) { return String.format(locale, "%02d:%06.3f s. (%,d ms.)", minutesPart, seconds, millis); } else { return String.format(locale, "%.3f s. (%,d ms.)", seconds, millis); } } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/report/Range.java
package ai.timefold.solver.benchmark.impl.report; public record Range(String label, double min, double q1, double median, double q3, double max, double average) { }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/report/ReportHelper.java
package ai.timefold.solver.benchmark.impl.report; import org.jspecify.annotations.NonNull; public class ReportHelper { /** * Escape illegal HTML element id characters, such as a dot. * <p> * This escape function guarantees that 2 distinct strings will result into 2 distinct escape strings * (presuming that both have been escaped by this method). * */ public static @NonNull String escapeHtmlId(@NonNull String rawHtmlId) { // Uses unicode numbers to escape, see http://unicode-table.com // Uses '-' as the escape character return rawHtmlId .replaceAll(" ", "-0020") .replaceAll("!", "-0021") .replaceAll("#", "-0023") .replaceAll("\\$", "-0024") .replaceAll(",", "-002C") .replaceAll("-", "-002D") .replaceAll("\\.", "-002E") .replaceAll("\\(", "-0028") .replaceAll("\\)", "-0029") .replaceAll(":", "-003A") .replaceAll(";", "-003B") .replaceAll("\\?", "-003F"); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/report/WebsiteResourceUtils.java
package ai.timefold.solver.benchmark.impl.report; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.util.function.Function; public final class WebsiteResourceUtils { private static final String RESOURCE_NAMESPACE = "/ai/timefold/solver/benchmark/impl/report/"; private static final String WEBJAR_RESOURCE_NAMESPACE = "META-INF/resources/webjars/timefold/"; public static void copyResourcesTo(File benchmarkReportDirectory) { // Manually extract webjars, as webjar-locator had issues with Quarkus. copyWebjarResource(benchmarkReportDirectory, "css/timefold-webui.css"); copyWebjarResource(benchmarkReportDirectory, "js/timefold-webui.js"); copyWebjarResource(benchmarkReportDirectory, "img/timefold-favicon.svg"); copyWebjarResource(benchmarkReportDirectory, "img/timefold-logo-horizontal-negative.svg"); copyWebjarResource(benchmarkReportDirectory, "img/timefold-logo-horizontal-positive.svg"); copyWebjarResource(benchmarkReportDirectory, "img/timefold-logo-stacked-positive.svg"); // Manually copy some other resources. copyResource(benchmarkReportDirectory, "website/css/prettify.css"); copyResource(benchmarkReportDirectory, "website/css/app.css"); copyResource(benchmarkReportDirectory, "website/js/chartjs-plugin-watermark.js"); copyResource(benchmarkReportDirectory, "website/js/prettify.js"); copyResource(benchmarkReportDirectory, "website/js/app.js"); } private static void copyWebjarResource(File benchmarkReportDirectory, String websiteResource) { copyResource(benchmarkReportDirectory, WEBJAR_RESOURCE_NAMESPACE, websiteResource, "website/" + websiteResource, s -> WebsiteResourceUtils.class.getClassLoader().getResourceAsStream(s)); } private static void copyResource(File benchmarkReportDirectory, String websiteResource) { copyResource(benchmarkReportDirectory, RESOURCE_NAMESPACE, websiteResource, websiteResource, WebsiteResourceUtils.class::getResourceAsStream); } private static void copyResource(File benchmarkReportDirectory, String namespace, String websiteResource, String targetResource, Function<String, InputStream> resourceLoader) { var outputFile = new File(benchmarkReportDirectory, targetResource); outputFile.getParentFile().mkdirs(); try (var in = resourceLoader.apply(namespace + websiteResource)) { if (in == null) { throw new IllegalStateException("The websiteResource (%s) does not exist." .formatted(websiteResource)); } Files.copy(in, outputFile.toPath()); } catch (IOException e) { throw new IllegalStateException("Could not copy websiteResource (%s) to outputFile (%s)." .formatted(websiteResource, outputFile), e); } } private WebsiteResourceUtils() { } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/result/BenchmarkResult.java
package ai.timefold.solver.benchmark.impl.result; import java.io.File; import ai.timefold.solver.core.api.score.Score; public interface BenchmarkResult { String getName(); /** * @return the name of the directory that holds the benchmark's results */ String getResultDirectoryName(); /** * @return the benchmark result directory as a file */ File getResultDirectory(); /** * @return true if there is a failed child benchmark and the variable is initialized */ boolean hasAnyFailure(); /** * @return true if all child benchmarks were a success and the variable is initialized */ boolean hasAllSuccess(); Score getAverageScore(); }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/result/BenchmarkResultIO.java
package ai.timefold.solver.benchmark.impl.result; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import ai.timefold.solver.benchmark.impl.statistic.ProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.PureSubSingleStatistic; import ai.timefold.solver.core.config.solver.SolverConfig; import ai.timefold.solver.core.impl.io.jaxb.ElementNamespaceOverride; import ai.timefold.solver.core.impl.io.jaxb.GenericJaxbIO; import ai.timefold.solver.core.impl.io.jaxb.TimefoldXmlSerializationException; import ai.timefold.solver.core.impl.solver.DefaultSolverFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BenchmarkResultIO { // BenchmarkResult contains <solverConfig/> element instead of the default SolverConfig.XML_ELEMENT_NAME. private static final String SOLVER_CONFIG_XML_ELEMENT_NAME = "solverConfig"; private static final String PLANNER_BENCHMARK_RESULT_FILENAME = "plannerBenchmarkResult.xml"; private static final Logger LOGGER = LoggerFactory.getLogger(BenchmarkResultIO.class); private final GenericJaxbIO<PlannerBenchmarkResult> genericJaxbIO = new GenericJaxbIO<>(PlannerBenchmarkResult.class); public void writePlannerBenchmarkResult(File benchmarkReportDirectory, PlannerBenchmarkResult plannerBenchmarkResult) { File plannerBenchmarkResultFile = new File(benchmarkReportDirectory, PLANNER_BENCHMARK_RESULT_FILENAME); try (Writer writer = new OutputStreamWriter(new FileOutputStream(plannerBenchmarkResultFile), StandardCharsets.UTF_8)) { write(plannerBenchmarkResult, writer); } catch (IOException e) { throw new IllegalArgumentException( "Failed writing plannerBenchmarkResultFile (" + plannerBenchmarkResultFile + ").", e); } } public List<PlannerBenchmarkResult> readPlannerBenchmarkResultList(File benchmarkDirectory) { if (!benchmarkDirectory.exists() || !benchmarkDirectory.isDirectory()) { throw new IllegalArgumentException("The benchmarkDirectory (" + benchmarkDirectory + ") does not exist or is not a directory."); } File[] benchmarkReportDirectories = benchmarkDirectory.listFiles(File::isDirectory); if (benchmarkReportDirectories == null) { throw new IllegalStateException("Unable to list the subdirectories in the benchmarkDirectory (" + benchmarkDirectory.getAbsolutePath() + ")."); } Arrays.sort(benchmarkReportDirectories); List<PlannerBenchmarkResult> plannerBenchmarkResultList = new ArrayList<>(benchmarkReportDirectories.length); for (File benchmarkReportDirectory : benchmarkReportDirectories) { File plannerBenchmarkResultFile = new File(benchmarkReportDirectory, PLANNER_BENCHMARK_RESULT_FILENAME); if (plannerBenchmarkResultFile.exists()) { PlannerBenchmarkResult plannerBenchmarkResult = readPlannerBenchmarkResult(plannerBenchmarkResultFile); plannerBenchmarkResultList.add(plannerBenchmarkResult); } } return plannerBenchmarkResultList; } protected PlannerBenchmarkResult readPlannerBenchmarkResult(File plannerBenchmarkResultFile) { if (!plannerBenchmarkResultFile.exists()) { throw new IllegalArgumentException("The plannerBenchmarkResultFile (" + plannerBenchmarkResultFile + ") does not exist."); } PlannerBenchmarkResult plannerBenchmarkResult; try (Reader reader = new InputStreamReader(new FileInputStream(plannerBenchmarkResultFile), StandardCharsets.UTF_8)) { plannerBenchmarkResult = read(reader); } catch (TimefoldXmlSerializationException e) { LOGGER.warn("Failed reading plannerBenchmarkResultFile ({}).", plannerBenchmarkResultFile, e); // If the plannerBenchmarkResultFile's format has changed, the app should not crash entirely String benchmarkReportDirectoryName = plannerBenchmarkResultFile.getParentFile().getName(); plannerBenchmarkResult = PlannerBenchmarkResult.createUnmarshallingFailedResult( benchmarkReportDirectoryName); } catch (IOException e) { throw new IllegalArgumentException( "Failed reading plannerBenchmarkResultFile (" + plannerBenchmarkResultFile + ").", e); } plannerBenchmarkResult.setBenchmarkReportDirectory(plannerBenchmarkResultFile.getParentFile()); restoreOmittedBidirectionalFields(plannerBenchmarkResult); restoreOtherOmittedFields(plannerBenchmarkResult); return plannerBenchmarkResult; } protected PlannerBenchmarkResult read(Reader reader) { return genericJaxbIO.readOverridingNamespace(reader, ElementNamespaceOverride.of(SOLVER_CONFIG_XML_ELEMENT_NAME, SolverConfig.XML_NAMESPACE)); } protected void write(PlannerBenchmarkResult plannerBenchmarkResult, Writer writer) { genericJaxbIO.writeWithoutNamespaces(plannerBenchmarkResult, writer); } private void restoreOmittedBidirectionalFields(PlannerBenchmarkResult plannerBenchmarkResult) { for (ProblemBenchmarkResult<Object> problemBenchmarkResult : plannerBenchmarkResult .getUnifiedProblemBenchmarkResultList()) { problemBenchmarkResult.setPlannerBenchmarkResult(plannerBenchmarkResult); if (problemBenchmarkResult.getProblemStatisticList() == null) { problemBenchmarkResult.setProblemStatisticList(new ArrayList<>(0)); } for (ProblemStatistic problemStatistic : problemBenchmarkResult.getProblemStatisticList()) { problemStatistic.setProblemBenchmarkResult(problemBenchmarkResult); } for (SingleBenchmarkResult singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) { singleBenchmarkResult.setProblemBenchmarkResult(problemBenchmarkResult); } } for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) { solverBenchmarkResult.setPlannerBenchmarkResult(plannerBenchmarkResult); for (SingleBenchmarkResult singleBenchmarkResult : solverBenchmarkResult.getSingleBenchmarkResultList()) { singleBenchmarkResult.setSolverBenchmarkResult(solverBenchmarkResult); for (SubSingleBenchmarkResult subSingleBenchmarkResult : singleBenchmarkResult .getSubSingleBenchmarkResultList()) { if (subSingleBenchmarkResult.getPureSubSingleStatisticList() == null) { subSingleBenchmarkResult.setPureSubSingleStatisticList(new ArrayList<>(0)); } } for (SubSingleBenchmarkResult subSingleBenchmarkResult : singleBenchmarkResult .getSubSingleBenchmarkResultList()) { for (PureSubSingleStatistic pureSubSingleStatistic : subSingleBenchmarkResult .getPureSubSingleStatisticList()) { pureSubSingleStatistic.setSubSingleBenchmarkResult(subSingleBenchmarkResult); } } } } } private void restoreOtherOmittedFields(PlannerBenchmarkResult plannerBenchmarkResult) { for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) { SolverConfig solverConfig = solverBenchmarkResult.getSolverConfig(); DefaultSolverFactory<?> defaultSolverFactory = new DefaultSolverFactory<>(solverConfig); solverBenchmarkResult.setScoreDefinition(defaultSolverFactory.getSolutionDescriptor().getScoreDefinition()); } } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/result/LoggingLevel.java
package ai.timefold.solver.benchmark.impl.result; public enum LoggingLevel { OFF, ERROR, WARN, INFO, DEBUG, TRACE }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/result/PlannerBenchmarkResult.java
package ai.timefold.solver.benchmark.impl.result; import java.io.File; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlTransient; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.solver.Solver; 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.score.definition.ScoreDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents the benchmarks on multiple {@link Solver} configurations on multiple problem instances (data sets). */ @XmlRootElement(name = "plannerBenchmarkResult") public class PlannerBenchmarkResult { private String name; private Boolean aggregation; @XmlTransient // Moving or renaming a report directory after creation is allowed private File benchmarkReportDirectory; // If it is an aggregation, many properties can stay null private Integer availableProcessors = null; private LoggingLevel loggingLevelTimefoldSolverCore = null; private Long maxMemory = null; private String timefoldSolverVersion = null; private String javaVersion = null; private String javaVM = null; private String operatingSystem = null; private Integer parallelBenchmarkCount = null; private Long warmUpTimeMillisSpentLimit = null; private EnvironmentMode environmentMode = null; @XmlElement(name = "solverBenchmarkResult") private List<SolverBenchmarkResult> solverBenchmarkResultList = null; @XmlElement(name = "unifiedProblemBenchmarkResult") private List<ProblemBenchmarkResult> unifiedProblemBenchmarkResultList = null; private OffsetDateTime startingTimestamp = null; private Long benchmarkTimeMillisSpent = null; // ************************************************************************ // Report accumulates // ************************************************************************ private Integer failureCount = null; private Long averageProblemScale = null; private Score averageScore = null; private SolverBenchmarkResult favoriteSolverBenchmarkResult = null; // ************************************************************************ // Constructors and simple getters/setters // ************************************************************************ public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getAggregation() { return aggregation; } public void setAggregation(Boolean aggregation) { this.aggregation = aggregation; } public File getBenchmarkReportDirectory() { return benchmarkReportDirectory; } public void setBenchmarkReportDirectory(File benchmarkReportDirectory) { this.benchmarkReportDirectory = benchmarkReportDirectory; } public Integer getAvailableProcessors() { return availableProcessors; } public LoggingLevel getLoggingLevelTimefoldSolverCore() { return loggingLevelTimefoldSolverCore; } public Long getMaxMemory() { return maxMemory; } public String getJavaVersion() { return javaVersion; } public String getJavaVM() { return javaVM; } public String getOperatingSystem() { return operatingSystem; } @SuppressWarnings("unused") // Used by FreeMarker. public String getTimefoldSolverVersion() { return timefoldSolverVersion; } public Integer getParallelBenchmarkCount() { return parallelBenchmarkCount; } public void setParallelBenchmarkCount(Integer parallelBenchmarkCount) { this.parallelBenchmarkCount = parallelBenchmarkCount; } public Long getWarmUpTimeMillisSpentLimit() { return warmUpTimeMillisSpentLimit; } public void setWarmUpTimeMillisSpentLimit(Long warmUpTimeMillisSpentLimit) { this.warmUpTimeMillisSpentLimit = warmUpTimeMillisSpentLimit; } public EnvironmentMode getEnvironmentMode() { return environmentMode; } public List<SolverBenchmarkResult> getSolverBenchmarkResultList() { return solverBenchmarkResultList; } public void setSolverBenchmarkResultList(List<SolverBenchmarkResult> solverBenchmarkResultList) { this.solverBenchmarkResultList = solverBenchmarkResultList; } public List<ProblemBenchmarkResult> getUnifiedProblemBenchmarkResultList() { return unifiedProblemBenchmarkResultList; } public void setUnifiedProblemBenchmarkResultList(List<ProblemBenchmarkResult> unifiedProblemBenchmarkResultList) { this.unifiedProblemBenchmarkResultList = unifiedProblemBenchmarkResultList; } public OffsetDateTime getStartingTimestamp() { return startingTimestamp; } public void setStartingTimestamp(OffsetDateTime startingTimestamp) { this.startingTimestamp = startingTimestamp; } public Long getBenchmarkTimeMillisSpent() { return benchmarkTimeMillisSpent; } public void setBenchmarkTimeMillisSpent(Long benchmarkTimeMillisSpent) { this.benchmarkTimeMillisSpent = benchmarkTimeMillisSpent; } public Integer getFailureCount() { return failureCount; } public Long getAverageProblemScale() { return averageProblemScale; } public Score getAverageScore() { return averageScore; } public SolverBenchmarkResult getFavoriteSolverBenchmarkResult() { return favoriteSolverBenchmarkResult; } // ************************************************************************ // Smart getters // ************************************************************************ public boolean hasMultipleParallelBenchmarks() { return parallelBenchmarkCount == null || parallelBenchmarkCount > 1; } public boolean hasAnyFailure() { return failureCount > 0; } @SuppressWarnings("unused") // Used by FreeMarker. public int getMaximumSubSingleCount() { int maximumSubSingleCount = 0; for (ProblemBenchmarkResult problemBenchmarkResult : unifiedProblemBenchmarkResultList) { int problemMaximumSubSingleCount = problemBenchmarkResult.getMaximumSubSingleCount(); if (problemMaximumSubSingleCount > maximumSubSingleCount) { maximumSubSingleCount = problemMaximumSubSingleCount; } } return maximumSubSingleCount; } public String findScoreLevelLabel(int scoreLevel) { String[] levelLabels = solverBenchmarkResultList.get(0).getScoreDefinition().getLevelLabels(); if (scoreLevel >= levelLabels.length) { // Occurs when mixing multiple examples in the same benchmark run, such as GeneralTimefoldBenchmarkApp return "unknown-" + (scoreLevel - levelLabels.length); } return levelLabels[scoreLevel]; } @SuppressWarnings("unused") // Used by FreeMarker. public String getStartingTimestampAsMediumString() { return startingTimestamp == null ? null : startingTimestamp.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)); } // ************************************************************************ // Accumulate methods // ************************************************************************ public void initBenchmarkReportDirectory(File benchmarkDirectory) { String timestampString = startingTimestamp.format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmmss")); if (name == null || name.isEmpty()) { name = timestampString; } if (!benchmarkDirectory.mkdirs()) { if (!benchmarkDirectory.isDirectory()) { throw new IllegalArgumentException("The benchmarkDirectory (" + benchmarkDirectory + ") already exists, but is not a directory."); } if (!benchmarkDirectory.canWrite()) { throw new IllegalArgumentException("The benchmarkDirectory (" + benchmarkDirectory + ") already exists, but is not writable."); } } int duplicationIndex = 0; do { String directoryName = timestampString + (duplicationIndex == 0 ? "" : "_" + duplicationIndex); duplicationIndex++; benchmarkReportDirectory = new File(benchmarkDirectory, (aggregation != null && !aggregation) ? directoryName : directoryName + "_aggregation"); } while (!benchmarkReportDirectory.mkdir()); for (ProblemBenchmarkResult problemBenchmarkResult : unifiedProblemBenchmarkResultList) { problemBenchmarkResult.makeDirs(); } } public void initSystemProperties() { availableProcessors = Runtime.getRuntime().availableProcessors(); loggingLevelTimefoldSolverCore = resolveLoggingLevel("ai.timefold.solver.core"); maxMemory = Runtime.getRuntime().maxMemory(); timefoldSolverVersion = TimefoldSolverEnterpriseService.identifySolverVersion(); javaVersion = "Java " + System.getProperty("java.version") + " (" + System.getProperty("java.vendor") + ")"; javaVM = "Java " + System.getProperty("java.vm.name") + " " + System.getProperty("java.vm.version") + " (" + System.getProperty("java.vm.vendor") + ")"; operatingSystem = System.getProperty("os.name") + " " + System.getProperty("os.arch") + " " + System.getProperty("os.version"); } private static LoggingLevel resolveLoggingLevel(String loggerName) { Logger logger = LoggerFactory.getLogger(loggerName); if (logger.isTraceEnabled()) { return LoggingLevel.TRACE; } else if (logger.isDebugEnabled()) { return LoggingLevel.DEBUG; } else if (logger.isInfoEnabled()) { return LoggingLevel.INFO; } else if (logger.isWarnEnabled()) { return LoggingLevel.WARN; } else if (logger.isErrorEnabled()) { return LoggingLevel.ERROR; } else { // Reached when no SLF4J implementation found on the classpath. return LoggingLevel.OFF; } } public int getTotalSubSingleCount() { int totalSubSingleCount = 0; for (ProblemBenchmarkResult problemBenchmarkResult : unifiedProblemBenchmarkResultList) { totalSubSingleCount += problemBenchmarkResult.getTotalSubSingleCount(); } return totalSubSingleCount; } public void accumulateResults(BenchmarkReport benchmarkReport) { for (ProblemBenchmarkResult problemBenchmarkResult : unifiedProblemBenchmarkResultList) { problemBenchmarkResult.accumulateResults(benchmarkReport); } for (SolverBenchmarkResult solverBenchmarkResult : solverBenchmarkResultList) { solverBenchmarkResult.accumulateResults(benchmarkReport); } determineTotalsAndAverages(); determineSolverRanking(benchmarkReport); } private <Score_ extends Score<Score_>> void determineTotalsAndAverages() { failureCount = 0; long totalProblemScale = 0L; int problemScaleCount = 0; for (ProblemBenchmarkResult problemBenchmarkResult : unifiedProblemBenchmarkResultList) { Long problemScale = problemBenchmarkResult.getProblemScale(); if (problemScale != null && problemScale >= 0L) { totalProblemScale += problemScale; problemScaleCount++; } failureCount += problemBenchmarkResult.getFailureCount(); } averageProblemScale = problemScaleCount == 0 ? null : totalProblemScale / problemScaleCount; Score_ totalScore = null; int solverBenchmarkCount = 0; boolean firstSolverBenchmarkResult = true; for (SolverBenchmarkResult solverBenchmarkResult : solverBenchmarkResultList) { EnvironmentMode solverEnvironmentMode = solverBenchmarkResult.getEnvironmentMode(); if (firstSolverBenchmarkResult && solverEnvironmentMode != null) { environmentMode = solverEnvironmentMode; firstSolverBenchmarkResult = false; } else if (!firstSolverBenchmarkResult && solverEnvironmentMode != environmentMode) { environmentMode = null; } Score_ score = (Score_) solverBenchmarkResult.getAverageScore(); if (score != null) { ScoreDefinition<Score_> scoreDefinition = solverBenchmarkResult.getScoreDefinition(); if (totalScore != null && !scoreDefinition.isCompatibleArithmeticArgument(totalScore)) { // Mixing different use cases with different score definitions. totalScore = null; break; } totalScore = (totalScore == null) ? score : totalScore.add(score); solverBenchmarkCount++; } } if (totalScore != null) { averageScore = totalScore.divide(solverBenchmarkCount); } } private void determineSolverRanking(BenchmarkReport benchmarkReport) { List<SolverBenchmarkResult> rankableSolverBenchmarkResultList = new ArrayList<>(solverBenchmarkResultList); // Do not rank a SolverBenchmarkResult that has a failure rankableSolverBenchmarkResultList.removeIf(SolverBenchmarkResult::hasAnyFailure); List<List<SolverBenchmarkResult>> sameRankingListList = createSameRankingListList( benchmarkReport, rankableSolverBenchmarkResultList); int ranking = 0; for (List<SolverBenchmarkResult> sameRankingList : sameRankingListList) { for (SolverBenchmarkResult solverBenchmarkResult : sameRankingList) { solverBenchmarkResult.setRanking(ranking); } ranking += sameRankingList.size(); } favoriteSolverBenchmarkResult = sameRankingListList.isEmpty() ? null : sameRankingListList.get(0).get(0); } private List<List<SolverBenchmarkResult>> createSameRankingListList( BenchmarkReport benchmarkReport, List<SolverBenchmarkResult> rankableSolverBenchmarkResultList) { List<List<SolverBenchmarkResult>> sameRankingListList = new ArrayList<>( rankableSolverBenchmarkResultList.size()); if (benchmarkReport.getSolverRankingComparator() != null) { Comparator<SolverBenchmarkResult> comparator = Collections.reverseOrder( benchmarkReport.getSolverRankingComparator()); rankableSolverBenchmarkResultList.sort(comparator); List<SolverBenchmarkResult> sameRankingList = null; SolverBenchmarkResult previousSolverBenchmarkResult = null; for (SolverBenchmarkResult solverBenchmarkResult : rankableSolverBenchmarkResultList) { if (previousSolverBenchmarkResult == null || comparator.compare(previousSolverBenchmarkResult, solverBenchmarkResult) != 0) { // New rank sameRankingList = new ArrayList<>(); sameRankingListList.add(sameRankingList); } sameRankingList.add(solverBenchmarkResult); previousSolverBenchmarkResult = solverBenchmarkResult; } } else if (benchmarkReport.getSolverRankingWeightFactory() != null) { SortedMap<Comparable, List<SolverBenchmarkResult>> rankedMap = new TreeMap<>(Collections.reverseOrder()); for (SolverBenchmarkResult solverBenchmarkResult : rankableSolverBenchmarkResultList) { Comparable rankingWeight = benchmarkReport.getSolverRankingWeightFactory() .createRankingWeight(rankableSolverBenchmarkResultList, solverBenchmarkResult); List<SolverBenchmarkResult> sameRankingList = rankedMap.computeIfAbsent(rankingWeight, k -> new ArrayList<>()); sameRankingList.add(solverBenchmarkResult); } for (Map.Entry<Comparable, List<SolverBenchmarkResult>> entry : rankedMap.entrySet()) { sameRankingListList.add(entry.getValue()); } } else { throw new IllegalStateException("Ranking is impossible" + " because solverRankingComparator and solverRankingWeightFactory are null."); } return sameRankingListList; } // ************************************************************************ // Merger methods // ************************************************************************ public static PlannerBenchmarkResult createMergedResult( List<SingleBenchmarkResult> singleBenchmarkResultList) { PlannerBenchmarkResult mergedResult = createMergeSingleton(singleBenchmarkResultList); Map<SolverBenchmarkResult, SolverBenchmarkResult> solverMergeMap = SolverBenchmarkResult.createMergeMap(mergedResult, singleBenchmarkResultList); Map<ProblemBenchmarkResult, ProblemBenchmarkResult> problemMergeMap = ProblemBenchmarkResult .createMergeMap(mergedResult, singleBenchmarkResultList); for (SingleBenchmarkResult singleBenchmarkResult : singleBenchmarkResultList) { SolverBenchmarkResult solverBenchmarkResult = solverMergeMap.get( singleBenchmarkResult.getSolverBenchmarkResult()); ProblemBenchmarkResult problemBenchmarkResult = problemMergeMap.get( singleBenchmarkResult.getProblemBenchmarkResult()); SingleBenchmarkResult.createMerge( solverBenchmarkResult, problemBenchmarkResult, singleBenchmarkResult); } return mergedResult; } protected static PlannerBenchmarkResult createMergeSingleton(List<SingleBenchmarkResult> singleBenchmarkResultList) { PlannerBenchmarkResult newResult = null; Map<PlannerBenchmarkResult, PlannerBenchmarkResult> mergeMap = new IdentityHashMap<>(); for (SingleBenchmarkResult singleBenchmarkResult : singleBenchmarkResultList) { PlannerBenchmarkResult oldResult = singleBenchmarkResult .getSolverBenchmarkResult().getPlannerBenchmarkResult(); if (!mergeMap.containsKey(oldResult)) { if (newResult == null) { newResult = new PlannerBenchmarkResult(); newResult.setAggregation(true); newResult.availableProcessors = oldResult.availableProcessors; newResult.loggingLevelTimefoldSolverCore = oldResult.loggingLevelTimefoldSolverCore; newResult.maxMemory = oldResult.maxMemory; newResult.timefoldSolverVersion = oldResult.timefoldSolverVersion; newResult.javaVersion = oldResult.javaVersion; newResult.javaVM = oldResult.javaVM; newResult.operatingSystem = oldResult.operatingSystem; newResult.parallelBenchmarkCount = oldResult.parallelBenchmarkCount; newResult.warmUpTimeMillisSpentLimit = oldResult.warmUpTimeMillisSpentLimit; newResult.environmentMode = oldResult.environmentMode; newResult.solverBenchmarkResultList = new ArrayList<>(); newResult.unifiedProblemBenchmarkResultList = new ArrayList<>(); newResult.startingTimestamp = null; newResult.benchmarkTimeMillisSpent = null; } else { newResult.availableProcessors = ConfigUtils.mergeProperty( newResult.availableProcessors, oldResult.availableProcessors); newResult.loggingLevelTimefoldSolverCore = ConfigUtils.mergeProperty( newResult.loggingLevelTimefoldSolverCore, oldResult.loggingLevelTimefoldSolverCore); newResult.maxMemory = ConfigUtils.mergeProperty( newResult.maxMemory, oldResult.maxMemory); newResult.timefoldSolverVersion = ConfigUtils.mergeProperty( newResult.timefoldSolverVersion, oldResult.timefoldSolverVersion); newResult.javaVersion = ConfigUtils.mergeProperty( newResult.javaVersion, oldResult.javaVersion); newResult.javaVM = ConfigUtils.mergeProperty( newResult.javaVM, oldResult.javaVM); newResult.operatingSystem = ConfigUtils.mergeProperty( newResult.operatingSystem, oldResult.operatingSystem); newResult.parallelBenchmarkCount = ConfigUtils.mergeProperty( newResult.parallelBenchmarkCount, oldResult.parallelBenchmarkCount); newResult.warmUpTimeMillisSpentLimit = ConfigUtils.mergeProperty( newResult.warmUpTimeMillisSpentLimit, oldResult.warmUpTimeMillisSpentLimit); newResult.environmentMode = ConfigUtils.mergeProperty( newResult.environmentMode, oldResult.environmentMode); } mergeMap.put(oldResult, newResult); } } return newResult; } public static PlannerBenchmarkResult createUnmarshallingFailedResult(String benchmarkReportDirectoryName) { PlannerBenchmarkResult result = new PlannerBenchmarkResult(); result.setName("Failed unmarshalling " + benchmarkReportDirectoryName); result.setSolverBenchmarkResultList(Collections.emptyList()); result.setUnifiedProblemBenchmarkResultList(Collections.emptyList()); return result; } @Override public String toString() { return getName(); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/result/ProblemBenchmarkResult.java
package ai.timefold.solver.benchmark.impl.result; import java.io.File; 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.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlElements; import jakarta.xml.bind.annotation.XmlIDREF; import jakarta.xml.bind.annotation.XmlTransient; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.config.statistic.SingleStatisticType; import ai.timefold.solver.benchmark.impl.loader.FileProblemProvider; import ai.timefold.solver.benchmark.impl.loader.InstanceProblemProvider; import ai.timefold.solver.benchmark.impl.loader.ProblemProvider; import ai.timefold.solver.benchmark.impl.ranking.TotalScoreSingleBenchmarkRankingComparator; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.ReportHelper; import ai.timefold.solver.benchmark.impl.statistic.ProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.PureSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.bestscore.BestScoreProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.bestsolutionmutation.BestSolutionMutationProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.memoryuse.MemoryUseProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.movecountperstep.MoveCountPerStepProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.movecountpertype.MoveCountPerTypeProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.moveevaluationspeed.MoveEvaluationSpeedProblemStatisticTime; import ai.timefold.solver.benchmark.impl.statistic.scorecalculationspeed.ScoreCalculationSpeedProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.stepscore.StepScoreProblemStatistic; import ai.timefold.solver.core.api.domain.solution.PlanningScore; import ai.timefold.solver.core.api.solver.ProblemSizeStatistics; import ai.timefold.solver.core.api.solver.Solver; import ai.timefold.solver.core.config.util.ConfigUtils; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents 1 problem instance (data set) benchmarked on multiple {@link Solver} configurations. */ public class ProblemBenchmarkResult<Solution_> { private static final Logger LOGGER = LoggerFactory.getLogger(ProblemBenchmarkResult.class); @XmlTransient // Bi-directional relationship restored through BenchmarkResultIO private PlannerBenchmarkResult plannerBenchmarkResult; private String name = null; @XmlElements({ @XmlElement(type = InstanceProblemProvider.class, name = "instanceProblemProvider"), @XmlElement(type = FileProblemProvider.class, name = "fileProblemProvider") }) private ProblemProvider<Solution_> problemProvider; private boolean writeOutputSolutionEnabled = false; @XmlElements({ @XmlElement(name = "bestScoreProblemStatistic", type = BestScoreProblemStatistic.class), @XmlElement(name = "stepScoreProblemStatistic", type = StepScoreProblemStatistic.class), @XmlElement(name = "scoreCalculationSpeedProblemStatistic", type = ScoreCalculationSpeedProblemStatistic.class), @XmlElement(name = "moveEvaluationSpeedProblemStatistic", type = MoveEvaluationSpeedProblemStatisticTime.class), @XmlElement(name = "bestSolutionMutationProblemStatistic", type = BestSolutionMutationProblemStatistic.class), @XmlElement(name = "moveCountPerStepProblemStatistic", type = MoveCountPerStepProblemStatistic.class), @XmlElement(name = "moveCountPerTypeProblemStatistic", type = MoveCountPerTypeProblemStatistic.class), @XmlElement(name = "memoryUseProblemStatistic", type = MemoryUseProblemStatistic.class), }) private List<ProblemStatistic> problemStatisticList = null; @XmlIDREF @XmlElement(name = "singleBenchmarkResult") private List<SingleBenchmarkResult> singleBenchmarkResultList = null; private Long entityCount = null; private Long variableCount = null; private Long maximumValueCount = null; private Long problemScale = null; private Long inputSolutionLoadingTimeMillisSpent = null; @XmlTransient // Loaded lazily from singleBenchmarkResults private Integer maximumSubSingleCount = null; // ************************************************************************ // Report accumulates // ************************************************************************ private Long averageUsedMemoryAfterInputSolution = null; private Integer failureCount = null; private SingleBenchmarkResult winningSingleBenchmarkResult = null; private SingleBenchmarkResult worstSingleBenchmarkResult = null; private Long worstScoreCalculationSpeed = null; // ************************************************************************ // Constructors and simple getters/setters // ************************************************************************ private ProblemBenchmarkResult() { // Required by JAXB } public ProblemBenchmarkResult(PlannerBenchmarkResult plannerBenchmarkResult) { this.plannerBenchmarkResult = plannerBenchmarkResult; } public PlannerBenchmarkResult getPlannerBenchmarkResult() { return plannerBenchmarkResult; } public void setPlannerBenchmarkResult(PlannerBenchmarkResult plannerBenchmarkResult) { this.plannerBenchmarkResult = plannerBenchmarkResult; } /** * @return never null, filename safe */ public String getName() { return name; } public void setName(String name) { this.name = name; } public ProblemProvider<Solution_> getProblemProvider() { return problemProvider; } public void setProblemProvider(ProblemProvider<Solution_> problemProvider) { this.problemProvider = problemProvider; } public boolean isWriteOutputSolutionEnabled() { return writeOutputSolutionEnabled; } public void setWriteOutputSolutionEnabled(boolean writeOutputSolutionEnabled) { this.writeOutputSolutionEnabled = writeOutputSolutionEnabled; } public List<ProblemStatistic> getProblemStatisticList() { return problemStatisticList; } public void setProblemStatisticList(List<ProblemStatistic> problemStatisticList) { this.problemStatisticList = problemStatisticList; } public List<SingleBenchmarkResult> getSingleBenchmarkResultList() { return singleBenchmarkResultList; } public void setSingleBenchmarkResultList(List<SingleBenchmarkResult> singleBenchmarkResultList) { this.singleBenchmarkResultList = singleBenchmarkResultList; } public Long getEntityCount() { return entityCount; } @SuppressWarnings("unused") // Used by FreeMarker. public Long getVariableCount() { return variableCount; } @SuppressWarnings("unused") // Used by FreeMarker. public Long getMaximumValueCount() { return maximumValueCount; } public Long getProblemScale() { return problemScale; } @SuppressWarnings("unused") // Used by FreeMarker. public Long getInputSolutionLoadingTimeMillisSpent() { return inputSolutionLoadingTimeMillisSpent; } public Integer getMaximumSubSingleCount() { return maximumSubSingleCount; } public Long getAverageUsedMemoryAfterInputSolution() { return averageUsedMemoryAfterInputSolution; } public Integer getFailureCount() { return failureCount; } public SingleBenchmarkResult getWinningSingleBenchmarkResult() { return winningSingleBenchmarkResult; } @SuppressWarnings("unused") // Used by FreeMarker. public SingleBenchmarkResult getWorstSingleBenchmarkResult() { return worstSingleBenchmarkResult; } @SuppressWarnings("unused") // Used by FreeMarker. public Long getWorstScoreCalculationSpeed() { return worstScoreCalculationSpeed; } // ************************************************************************ // Smart getters // ************************************************************************ @SuppressWarnings("unused") // Used by FreeMarker. public String getAnchorId() { return ReportHelper.escapeHtmlId(name); } public String findScoreLevelLabel(int scoreLevel) { ScoreDefinition scoreDefinition = singleBenchmarkResultList.get(0).getSolverBenchmarkResult().getScoreDefinition(); String[] levelLabels = scoreDefinition.getLevelLabels(); if (scoreLevel >= levelLabels.length) { throw new IllegalArgumentException("The scoreLevel (" + scoreLevel + ") isn't lower than the scoreLevelsSize (" + scoreDefinition.getLevelsSize() + ") implied by the @" + PlanningScore.class.getSimpleName() + " on the planning solution class."); } return levelLabels[scoreLevel]; } public File getBenchmarkReportDirectory() { return plannerBenchmarkResult.getBenchmarkReportDirectory(); } public boolean hasAnyFailure() { return failureCount > 0; } public boolean hasAnySuccess() { return singleBenchmarkResultList.size() - failureCount > 0; } @SuppressWarnings("unused") // Used by FreeMarker. public boolean hasAnyStatistic() { if (problemStatisticList.size() > 0) { return true; } for (SingleBenchmarkResult singleBenchmarkResult : singleBenchmarkResultList) { if (singleBenchmarkResult.getMedian().getPureSubSingleStatisticList().size() > 0) { return true; } } return false; } public boolean hasProblemStatisticType(ProblemStatisticType problemStatisticType) { for (ProblemStatistic problemStatistic : problemStatisticList) { if (problemStatistic.getProblemStatisticType() == problemStatisticType) { return true; } } return false; } @SuppressWarnings("unused") // Used by FreeMarker. public Collection<SingleStatisticType> extractSingleStatisticTypeList() { Set<SingleStatisticType> singleStatisticTypeSet = new LinkedHashSet<>(); for (SingleBenchmarkResult singleBenchmarkResult : singleBenchmarkResultList) { for (PureSubSingleStatistic pureSubSingleStatistic : singleBenchmarkResult.getMedian() .getPureSubSingleStatisticList()) { singleStatisticTypeSet.add(pureSubSingleStatistic.getStatisticType()); } } return singleStatisticTypeSet; } @SuppressWarnings("unused") // Used by FreeMarker. public List<PureSubSingleStatistic> extractPureSubSingleStatisticList(SingleStatisticType singleStatisticType) { List<PureSubSingleStatistic> pureSubSingleStatisticList = new ArrayList<>( singleBenchmarkResultList.size()); for (SingleBenchmarkResult singleBenchmarkResult : singleBenchmarkResultList) { for (PureSubSingleStatistic pureSubSingleStatistic : singleBenchmarkResult.getMedian() .getPureSubSingleStatisticList()) { if (pureSubSingleStatistic.getStatisticType() == singleStatisticType) { pureSubSingleStatisticList.add(pureSubSingleStatistic); } } } return pureSubSingleStatisticList; } // ************************************************************************ // Work methods // ************************************************************************ public String getProblemReportDirectoryName() { return name; } public File getProblemReportDirectory() { return new File(getBenchmarkReportDirectory(), name); } public void makeDirs() { File problemReportDirectory = getProblemReportDirectory(); problemReportDirectory.mkdirs(); for (SingleBenchmarkResult singleBenchmarkResult : singleBenchmarkResultList) { singleBenchmarkResult.makeDirs(); } } public int getTotalSubSingleCount() { int totalSubSingleCount = 0; for (SingleBenchmarkResult singleBenchmarkResult : singleBenchmarkResultList) { totalSubSingleCount += singleBenchmarkResult.getSubSingleCount(); } return totalSubSingleCount; } public Solution_ readProblem() { long startTimeMillis = System.currentTimeMillis(); Solution_ inputSolution = problemProvider.readProblem(); inputSolutionLoadingTimeMillisSpent = System.currentTimeMillis() - startTimeMillis; return inputSolution; } public void writeSolution(SubSingleBenchmarkResult subSingleBenchmarkResult, Solution_ solution) { if (!writeOutputSolutionEnabled) { return; } problemProvider.writeSolution(solution, subSingleBenchmarkResult); } // ************************************************************************ // Accumulate methods // ************************************************************************ public void accumulateResults(BenchmarkReport benchmarkReport) { for (SingleBenchmarkResult singleBenchmarkResult : singleBenchmarkResultList) { singleBenchmarkResult.accumulateResults(benchmarkReport); } determineTotalsAndAveragesAndRanking(); determineWinningScoreDifference(); } private void determineTotalsAndAveragesAndRanking() { failureCount = 0; maximumSubSingleCount = 0; worstScoreCalculationSpeed = null; long totalUsedMemoryAfterInputSolution = 0L; int usedMemoryAfterInputSolutionCount = 0; List<SingleBenchmarkResult> successResultList = new ArrayList<>(singleBenchmarkResultList); // Do not rank a SingleBenchmarkResult that has a failure for (Iterator<SingleBenchmarkResult> it = successResultList.iterator(); it.hasNext();) { SingleBenchmarkResult singleBenchmarkResult = it.next(); if (singleBenchmarkResult.hasAnyFailure()) { failureCount++; it.remove(); } else { int subSingleCount = singleBenchmarkResult.getSubSingleBenchmarkResultList().size(); if (subSingleCount > maximumSubSingleCount) { maximumSubSingleCount = subSingleCount; } if (singleBenchmarkResult.getUsedMemoryAfterInputSolution() != null) { totalUsedMemoryAfterInputSolution += singleBenchmarkResult.getUsedMemoryAfterInputSolution(); usedMemoryAfterInputSolutionCount++; } if (worstScoreCalculationSpeed == null || singleBenchmarkResult.getScoreCalculationSpeed() < worstScoreCalculationSpeed) { worstScoreCalculationSpeed = singleBenchmarkResult.getScoreCalculationSpeed(); } } } if (usedMemoryAfterInputSolutionCount > 0) { averageUsedMemoryAfterInputSolution = totalUsedMemoryAfterInputSolution / usedMemoryAfterInputSolutionCount; } determineRanking(successResultList); } private void determineRanking(List<SingleBenchmarkResult> rankedSingleBenchmarkResultList) { Comparator<SingleBenchmarkResult> singleBenchmarkRankingComparator = new TotalScoreSingleBenchmarkRankingComparator(); rankedSingleBenchmarkResultList.sort(Collections.reverseOrder(singleBenchmarkRankingComparator)); int ranking = 0; SingleBenchmarkResult previousSingleBenchmarkResult = null; int previousSameRankingCount = 0; for (SingleBenchmarkResult singleBenchmarkResult : rankedSingleBenchmarkResultList) { if (previousSingleBenchmarkResult != null && singleBenchmarkRankingComparator.compare(previousSingleBenchmarkResult, singleBenchmarkResult) != 0) { ranking += previousSameRankingCount; previousSameRankingCount = 0; } singleBenchmarkResult.setRanking(ranking); previousSingleBenchmarkResult = singleBenchmarkResult; previousSameRankingCount++; } winningSingleBenchmarkResult = rankedSingleBenchmarkResultList.isEmpty() ? null : rankedSingleBenchmarkResultList.get(0); worstSingleBenchmarkResult = rankedSingleBenchmarkResultList.isEmpty() ? null : rankedSingleBenchmarkResultList.get(rankedSingleBenchmarkResultList.size() - 1); } private void determineWinningScoreDifference() { for (SingleBenchmarkResult singleBenchmarkResult : singleBenchmarkResultList) { if (singleBenchmarkResult.hasAnyFailure()) { continue; } singleBenchmarkResult.setWinningScoreDifference( singleBenchmarkResult.getAverageScore().subtract(winningSingleBenchmarkResult.getAverageScore())); singleBenchmarkResult.setWorstScoreDifferencePercentage( ScoreDifferencePercentage.calculateScoreDifferencePercentage( worstSingleBenchmarkResult.getAverageScore(), singleBenchmarkResult.getAverageScore())); singleBenchmarkResult.setWorstScoreCalculationSpeedDifferencePercentage( ScoreDifferencePercentage.calculateDifferencePercentage( (double) worstScoreCalculationSpeed, (double) singleBenchmarkResult.getScoreCalculationSpeed())); } } /** * HACK to avoid loading the problem just to extract its problemScale. * Called multiple times, for every {@link SingleBenchmarkResult} of this {@link ProblemBenchmarkResult}. * * @param problemSizeStatistics never null */ public void registerProblemSizeStatistics(ProblemSizeStatistics problemSizeStatistics) { if (entityCount == null) { entityCount = problemSizeStatistics.entityCount(); } else if (entityCount.longValue() != problemSizeStatistics.entityCount()) { LOGGER.warn("The problemBenchmarkResult ({}) has different entityCount values ([{},{}]).\n" + "This is normally impossible for 1 inputSolutionFile.", getName(), entityCount, problemSizeStatistics.entityCount()); // The entityCount is not unknown (null), but known to be ambiguous entityCount = -1L; } if (variableCount == null) { variableCount = problemSizeStatistics.variableCount(); } else if (variableCount.longValue() != problemSizeStatistics.variableCount()) { LOGGER.warn("The problemBenchmarkResult ({}) has different variableCount values ([{},{}]).\n" + "This is normally impossible for 1 inputSolutionFile.", getName(), variableCount, problemSizeStatistics.variableCount()); // The variableCount is not unknown (null), but known to be ambiguous variableCount = -1L; } if (maximumValueCount == null) { maximumValueCount = problemSizeStatistics.approximateValueCount(); } else if (maximumValueCount.longValue() != problemSizeStatistics.approximateValueCount()) { LOGGER.warn("The problemBenchmarkResult ({}) has different approximateValueCount values ([{},{}]).\n" + "This is normally impossible for 1 inputSolutionFile.", getName(), maximumValueCount, problemSizeStatistics.approximateValueCount()); // The approximateValueCount is not unknown (null), but known to be ambiguous maximumValueCount = -1L; } if (problemScale == null) { problemScale = problemSizeStatistics.approximateProblemScaleLogAsFixedPointLong(); } else if (problemScale.longValue() != problemSizeStatistics.approximateProblemScaleLogAsFixedPointLong()) { LOGGER.warn("The problemBenchmarkResult ({}) has different problemScale values ([{},{}]).\n" + "This is normally impossible for 1 inputSolutionFile.", getName(), problemScale, problemSizeStatistics.approximateProblemScaleLogAsFixedPointLong()); // The problemScale is not unknown (null), but known to be ambiguous problemScale = -1L; } } /** * Used by {@link ai.timefold.solver.benchmark.impl.ProblemBenchmarksFactory#buildProblemBenchmarkList}. * * @param other sometimes null * @return true if equal */ @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } ProblemBenchmarkResult<?> that = (ProblemBenchmarkResult<?>) other; return Objects.equals(problemProvider, that.problemProvider); } @Override public int hashCode() { return Objects.hash(problemProvider); } // ************************************************************************ // Merger methods // ************************************************************************ protected static <Solution_> Map<ProblemBenchmarkResult, ProblemBenchmarkResult> createMergeMap( PlannerBenchmarkResult newPlannerBenchmarkResult, List<SingleBenchmarkResult> singleBenchmarkResultList) { // IdentityHashMap but despite that different ProblemBenchmarkResult instances are merged Map<ProblemBenchmarkResult, ProblemBenchmarkResult> mergeMap = new IdentityHashMap<>(); Map<ProblemProvider<Solution_>, ProblemBenchmarkResult> problemProviderToNewResultMap = new HashMap<>(); for (SingleBenchmarkResult singleBenchmarkResult : singleBenchmarkResultList) { ProblemBenchmarkResult<Solution_> oldResult = singleBenchmarkResult.getProblemBenchmarkResult(); if (!mergeMap.containsKey(oldResult)) { ProblemBenchmarkResult<Solution_> newResult; if (!problemProviderToNewResultMap.containsKey(oldResult.problemProvider)) { newResult = new ProblemBenchmarkResult<>(newPlannerBenchmarkResult); newResult.name = oldResult.name; newResult.problemProvider = oldResult.problemProvider; // Skip oldResult.problemReportDirectory newResult.problemStatisticList = new ArrayList<>(oldResult.problemStatisticList.size()); for (ProblemStatistic oldProblemStatistic : oldResult.problemStatisticList) { newResult.problemStatisticList.add( oldProblemStatistic.getProblemStatisticType().buildProblemStatistic(newResult)); } newResult.singleBenchmarkResultList = new ArrayList<>( oldResult.singleBenchmarkResultList.size()); newResult.entityCount = oldResult.entityCount; newResult.variableCount = oldResult.variableCount; newResult.maximumValueCount = oldResult.maximumValueCount; newResult.problemScale = oldResult.problemScale; problemProviderToNewResultMap.put(oldResult.problemProvider, newResult); newPlannerBenchmarkResult.getUnifiedProblemBenchmarkResultList().add(newResult); } else { newResult = problemProviderToNewResultMap.get(oldResult.problemProvider); if (!Objects.equals(oldResult.name, newResult.name)) { throw new IllegalStateException( "The oldResult (" + oldResult + ") and newResult (" + newResult + ") should have the same name, because they have the same problemProvider (" + oldResult.problemProvider + ")."); } newResult.problemStatisticList.removeIf( newStatistic -> !oldResult.hasProblemStatisticType(newStatistic.getProblemStatisticType())); newResult.entityCount = ConfigUtils.meldProperty(oldResult.entityCount, newResult.entityCount); newResult.variableCount = ConfigUtils.meldProperty(oldResult.variableCount, newResult.variableCount); newResult.maximumValueCount = ConfigUtils.meldProperty(oldResult.maximumValueCount, newResult.maximumValueCount); newResult.problemScale = ConfigUtils.meldProperty(oldResult.problemScale, newResult.problemScale); } mergeMap.put(oldResult, newResult); } } return mergeMap; } @Override public String toString() { return getName(); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/result/ScoreDifferencePercentage.java
package ai.timefold.solver.benchmark.impl.result; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Arrays; import java.util.Locale; import ai.timefold.solver.core.api.score.Score; public record ScoreDifferencePercentage(double[] percentageLevels) { public static <Score_ extends Score<Score_>> ScoreDifferencePercentage calculateScoreDifferencePercentage( Score_ baseScore, Score_ valueScore) { double[] baseLevels = baseScore.toLevelDoubles(); double[] valueLevels = valueScore.toLevelDoubles(); if (baseLevels.length != valueLevels.length) { throw new IllegalStateException("The baseScore (" + baseScore + ")'s levelsLength (" + baseLevels.length + ") is different from the valueScore (" + valueScore + ")'s levelsLength (" + valueLevels.length + ")."); } double[] percentageLevels = new double[baseLevels.length]; for (int i = 0; i < baseLevels.length; i++) { percentageLevels[i] = calculateDifferencePercentage(baseLevels[i], valueLevels[i]); } return new ScoreDifferencePercentage(percentageLevels); } public static double calculateDifferencePercentage(double base, double value) { double difference = value - base; if (base < 0.0) { return difference / -base; } else if (base == 0.0) { if (difference == 0.0) { return 0.0; } else { // will return Infinity or -Infinity return difference / base; } } else { return difference / base; } } // ************************************************************************ // Worker methods // ************************************************************************ public ScoreDifferencePercentage add(ScoreDifferencePercentage addend) { if (percentageLevels.length != addend.percentageLevels().length) { throw new IllegalStateException("The addend (" + addend + ")'s levelsLength (" + addend.percentageLevels().length + ") is different from the base (" + this + ")'s levelsLength (" + percentageLevels.length + ")."); } double[] newPercentageLevels = new double[percentageLevels.length]; for (int i = 0; i < percentageLevels.length; i++) { newPercentageLevels[i] = percentageLevels[i] + addend.percentageLevels[i]; } return new ScoreDifferencePercentage(newPercentageLevels); } public ScoreDifferencePercentage subtract(ScoreDifferencePercentage subtrahend) { if (percentageLevels.length != subtrahend.percentageLevels().length) { throw new IllegalStateException("The subtrahend (" + subtrahend + ")'s levelsLength (" + subtrahend.percentageLevels().length + ") is different from the base (" + this + ")'s levelsLength (" + percentageLevels.length + ")."); } double[] newPercentageLevels = new double[percentageLevels.length]; for (int i = 0; i < percentageLevels.length; i++) { newPercentageLevels[i] = percentageLevels[i] - subtrahend.percentageLevels[i]; } return new ScoreDifferencePercentage(newPercentageLevels); } public ScoreDifferencePercentage multiply(double multiplicand) { double[] newPercentageLevels = new double[percentageLevels.length]; for (int i = 0; i < percentageLevels.length; i++) { newPercentageLevels[i] = percentageLevels[i] * multiplicand; } return new ScoreDifferencePercentage(newPercentageLevels); } public ScoreDifferencePercentage divide(double divisor) { double[] newPercentageLevels = new double[percentageLevels.length]; for (int i = 0; i < percentageLevels.length; i++) { newPercentageLevels[i] = percentageLevels[i] / divisor; } return new ScoreDifferencePercentage(newPercentageLevels); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ScoreDifferencePercentage that = (ScoreDifferencePercentage) o; return Arrays.equals(percentageLevels, that.percentageLevels); } @Override public int hashCode() { return Arrays.hashCode(percentageLevels); } @Override public String toString() { return toString(Locale.US); } public String toString(Locale locale) { StringBuilder s = new StringBuilder(percentageLevels.length * 8); DecimalFormat decimalFormat = new DecimalFormat("0.00%", DecimalFormatSymbols.getInstance(locale)); for (int i = 0; i < percentageLevels.length; i++) { if (i > 0) { s.append("/"); } s.append(decimalFormat.format(percentageLevels[i])); } return s.toString(); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/result/SingleBenchmarkResult.java
package ai.timefold.solver.benchmark.impl.result; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlID; import jakarta.xml.bind.annotation.XmlTransient; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.ranking.ScoreSubSingleBenchmarkRankingComparator; import ai.timefold.solver.benchmark.impl.ranking.SubSingleBenchmarkRankBasedComparator; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.ReportHelper; import ai.timefold.solver.benchmark.impl.statistic.StatisticUtils; import ai.timefold.solver.benchmark.impl.statistic.SubSingleStatistic; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.solver.Solver; import ai.timefold.solver.core.config.util.ConfigUtils; /** * Represents 1 benchmark for 1 {@link Solver} configuration for 1 problem instance (data set). */ public class SingleBenchmarkResult implements BenchmarkResult { // Required by JAXB to refer to existing instances of this class private static final AtomicLong ID_GENERATOR = new AtomicLong(1L); @XmlID @XmlAttribute private String id = String.valueOf(ID_GENERATOR.getAndIncrement()); @XmlTransient // Bi-directional relationship restored through BenchmarkResultIO private SolverBenchmarkResult solverBenchmarkResult; @XmlTransient // Bi-directional relationship restored through BenchmarkResultIO private ProblemBenchmarkResult problemBenchmarkResult; @XmlElement(name = "subSingleBenchmarkResult") private List<SubSingleBenchmarkResult> subSingleBenchmarkResultList = null; private Long usedMemoryAfterInputSolution = null; private Integer failureCount = null; private Score totalScore = null; private Score averageScore = null; private boolean allScoresInitialized = false; private SubSingleBenchmarkResult median = null; private SubSingleBenchmarkResult best = null; private SubSingleBenchmarkResult worst = null; // Not a Score because // - the squaring would cause overflow for relatively small int and long scores. // - standard deviation should not be rounded to integer numbers private double[] standardDeviationDoubles = null; private long timeMillisSpent = -1L; private long scoreCalculationCount = -1L; private long moveEvaluationCount = -1L; private String scoreExplanationSummary = null; // ************************************************************************ // Report accumulates // ************************************************************************ // Compared to winningSingleBenchmarkResult in the same ProblemBenchmarkResult (which might not be the overall favorite) private Score<?> winningScoreDifference = null; private ScoreDifferencePercentage worstScoreDifferencePercentage = null; private Double worstScoreCalculationSpeedDifferencePercentage = null; // Ranking starts from 0 private Integer ranking = null; // ************************************************************************ // Constructors and simple getters/setters // ************************************************************************ public SingleBenchmarkResult() { // Required by JAXB } public SingleBenchmarkResult(SolverBenchmarkResult solverBenchmarkResult, ProblemBenchmarkResult problemBenchmarkResult) { this.solverBenchmarkResult = solverBenchmarkResult; this.problemBenchmarkResult = problemBenchmarkResult; } public void initSubSingleStatisticMaps() { for (var subSingleBenchmarkResult : subSingleBenchmarkResultList) { subSingleBenchmarkResult.initSubSingleStatisticMap(); } } public SolverBenchmarkResult getSolverBenchmarkResult() { return solverBenchmarkResult; } public void setSolverBenchmarkResult(SolverBenchmarkResult solverBenchmarkResult) { this.solverBenchmarkResult = solverBenchmarkResult; } public ProblemBenchmarkResult getProblemBenchmarkResult() { return problemBenchmarkResult; } public void setProblemBenchmarkResult(ProblemBenchmarkResult problemBenchmarkResult) { this.problemBenchmarkResult = problemBenchmarkResult; } public List<SubSingleBenchmarkResult> getSubSingleBenchmarkResultList() { return subSingleBenchmarkResultList; } public void setSubSingleBenchmarkResultList(List<SubSingleBenchmarkResult> subSingleBenchmarkResultList) { this.subSingleBenchmarkResultList = subSingleBenchmarkResultList; } /** * @return null if {@link PlannerBenchmarkResult#hasMultipleParallelBenchmarks()} return true */ public Long getUsedMemoryAfterInputSolution() { return usedMemoryAfterInputSolution; } public void setUsedMemoryAfterInputSolution(Long usedMemoryAfterInputSolution) { this.usedMemoryAfterInputSolution = usedMemoryAfterInputSolution; } @SuppressWarnings("unused") // Used by FreeMarker. public Integer getFailureCount() { return failureCount; } public void setFailureCount(Integer failureCount) { this.failureCount = failureCount; } public long getTimeMillisSpent() { return timeMillisSpent; } public void setTimeMillisSpent(long timeMillisSpent) { this.timeMillisSpent = timeMillisSpent; } public long getScoreCalculationCount() { return scoreCalculationCount; } public void setScoreCalculationCount(long scoreCalculationCount) { this.scoreCalculationCount = scoreCalculationCount; } public long getMoveEvaluationCount() { return moveEvaluationCount; } public void setMoveEvaluationCount(long moveEvaluationCount) { this.moveEvaluationCount = moveEvaluationCount; } @SuppressWarnings("unused") // Used by FreeMarker. public String getScoreExplanationSummary() { return scoreExplanationSummary; } public Score<?> getWinningScoreDifference() { return winningScoreDifference; } public void setWinningScoreDifference(Score<?> winningScoreDifference) { this.winningScoreDifference = winningScoreDifference; } public ScoreDifferencePercentage getWorstScoreDifferencePercentage() { return worstScoreDifferencePercentage; } public void setWorstScoreDifferencePercentage(ScoreDifferencePercentage worstScoreDifferencePercentage) { this.worstScoreDifferencePercentage = worstScoreDifferencePercentage; } public Double getWorstScoreCalculationSpeedDifferencePercentage() { return worstScoreCalculationSpeedDifferencePercentage; } public void setWorstScoreCalculationSpeedDifferencePercentage(Double worstScoreCalculationSpeedDifferencePercentage) { this.worstScoreCalculationSpeedDifferencePercentage = worstScoreCalculationSpeedDifferencePercentage; } public Integer getRanking() { return ranking; } public void setRanking(Integer ranking) { this.ranking = ranking; } @Override public Score getAverageScore() { return averageScore; } public void setAverageAndTotalScoreForTesting(Score<?> averageAndTotalScore, boolean allScoresInitialized) { this.averageScore = averageAndTotalScore; this.totalScore = averageAndTotalScore; this.allScoresInitialized = allScoresInitialized; } public SubSingleBenchmarkResult getMedian() { return median; } public SubSingleBenchmarkResult getBest() { return best; } public SubSingleBenchmarkResult getWorst() { return worst; } public Score<?> getTotalScore() { return totalScore; } // ************************************************************************ // Smart getters // ************************************************************************ @SuppressWarnings("unused") // Used by FreeMarker. public String getAnchorId() { return ReportHelper.escapeHtmlId(getName()); } /** * @return never null, filename safe */ @Override public String getName() { return problemBenchmarkResult.getName() + "_" + solverBenchmarkResult.getName(); } @Override public boolean hasAllSuccess() { return failureCount != null && failureCount == 0; } public boolean isInitialized() { return averageScore != null && allScoresInitialized; } @Override public boolean hasAnyFailure() { return failureCount != null && failureCount != 0; } public boolean isScoreFeasible() { return averageScore.isFeasible(); } public Long getScoreCalculationSpeed() { var scoreCalculationCountByThousand = scoreCalculationCount * 1000L; // Avoid divide by zero exception on a fast CPU return timeMillisSpent == 0L ? scoreCalculationCountByThousand : scoreCalculationCountByThousand / timeMillisSpent; } public Long getMoveEvaluationSpeed() { var moveEvaluationCountByThousand = moveEvaluationCount * 1000L; // Avoid divide by zero exception on a fast CPU return timeMillisSpent == 0L ? moveEvaluationCountByThousand : moveEvaluationCountByThousand / timeMillisSpent; } @SuppressWarnings("unused") // Used By FreeMarker. public boolean isWinner() { return ranking != null && ranking.intValue() == 0; } public SubSingleStatistic getSubSingleStatistic(ProblemStatisticType problemStatisticType) { return getMedian().getEffectiveSubSingleStatisticMap().get(problemStatisticType); } public int getSuccessCount() { return subSingleBenchmarkResultList.size() - failureCount; } @SuppressWarnings("unused") // Used by FreeMarker. public String getStandardDeviationString() { return StatisticUtils.getStandardDeviationString(standardDeviationDoubles); } // ************************************************************************ // Accumulate methods // ************************************************************************ @Override public String getResultDirectoryName() { return solverBenchmarkResult.getName(); } @Override public File getResultDirectory() { return new File(problemBenchmarkResult.getProblemReportDirectory(), getResultDirectoryName()); } public void makeDirs() { var singleReportDirectory = getResultDirectory(); singleReportDirectory.mkdirs(); for (var subSingleBenchmarkResult : subSingleBenchmarkResultList) { subSingleBenchmarkResult.makeDirs(); } } public int getSubSingleCount() { return subSingleBenchmarkResultList.size(); } public void accumulateResults(BenchmarkReport benchmarkReport) { for (var subSingleBenchmarkResult : subSingleBenchmarkResultList) { subSingleBenchmarkResult.accumulateResults(benchmarkReport); } determineTotalsAndAveragesAndRanking(); standardDeviationDoubles = StatisticUtils.determineStandardDeviationDoubles(subSingleBenchmarkResultList, averageScore, getSuccessCount()); determineRepresentativeSubSingleBenchmarkResult(); } private void determineRepresentativeSubSingleBenchmarkResult() { if (subSingleBenchmarkResultList == null || subSingleBenchmarkResultList.isEmpty()) { throw new IllegalStateException( "Cannot get representative subSingleBenchmarkResult from empty subSingleBenchmarkResultList."); } var subSingleBenchmarkResultListCopy = new ArrayList<>(subSingleBenchmarkResultList); // sort (according to ranking) so that the best subSingle is at index 0 subSingleBenchmarkResultListCopy.sort(new SubSingleBenchmarkRankBasedComparator()); best = subSingleBenchmarkResultListCopy.get(0); worst = subSingleBenchmarkResultListCopy.get(subSingleBenchmarkResultListCopy.size() - 1); median = subSingleBenchmarkResultListCopy.get(ConfigUtils.ceilDivide(subSingleBenchmarkResultListCopy.size() - 1, 2)); usedMemoryAfterInputSolution = median.getUsedMemoryAfterInputSolution(); timeMillisSpent = median.getTimeMillisSpent(); scoreCalculationCount = median.getScoreCalculationCount(); moveEvaluationCount = median.getMoveEvaluationCount(); scoreExplanationSummary = median.getScoreExplanationSummary(); } private void determineTotalsAndAveragesAndRanking() { failureCount = 0; var firstNonFailure = true; totalScore = null; var successResultList = new ArrayList<>(subSingleBenchmarkResultList); // Do not rank a SubSingleBenchmarkResult that has a failure for (var it = successResultList.iterator(); it.hasNext();) { var subSingleBenchmarkResult = it.next(); if (subSingleBenchmarkResult.hasAnyFailure()) { failureCount++; it.remove(); } else { var isInitialized = subSingleBenchmarkResult.isInitialized(); if (firstNonFailure) { totalScore = subSingleBenchmarkResult.getAverageScore(); allScoresInitialized = isInitialized; firstNonFailure = false; } else { totalScore = totalScore.add(subSingleBenchmarkResult.getAverageScore()); allScoresInitialized = allScoresInitialized || isInitialized; } } } if (!firstNonFailure) { averageScore = totalScore.divide(getSuccessCount()); } determineRanking(successResultList); } private static void determineRanking(List<SubSingleBenchmarkResult> rankedSubSingleBenchmarkResultList) { var subSingleBenchmarkRankingComparator = new ScoreSubSingleBenchmarkRankingComparator(); rankedSubSingleBenchmarkResultList.sort(Collections.reverseOrder(subSingleBenchmarkRankingComparator)); var ranking = 0; SubSingleBenchmarkResult previousSubSingleBenchmarkResult = null; var previousSameRankingCount = 0; for (var subSingleBenchmarkResult : rankedSubSingleBenchmarkResultList) { if (previousSubSingleBenchmarkResult != null && subSingleBenchmarkRankingComparator.compare(previousSubSingleBenchmarkResult, subSingleBenchmarkResult) != 0) { ranking += previousSameRankingCount; previousSameRankingCount = 0; } subSingleBenchmarkResult.setRanking(ranking); previousSubSingleBenchmarkResult = subSingleBenchmarkResult; previousSameRankingCount++; } } // ************************************************************************ // Merger methods // ************************************************************************ protected static SingleBenchmarkResult createMerge( SolverBenchmarkResult solverBenchmarkResult, ProblemBenchmarkResult problemBenchmarkResult, SingleBenchmarkResult oldResult) { var newResult = new SingleBenchmarkResult(solverBenchmarkResult, problemBenchmarkResult); newResult.subSingleBenchmarkResultList = new ArrayList<>(oldResult.getSubSingleBenchmarkResultList().size()); var subSingleBenchmarkIndex = 0; for (var oldSubResult : oldResult.subSingleBenchmarkResultList) { SubSingleBenchmarkResult.createMerge(newResult, oldSubResult, subSingleBenchmarkIndex); subSingleBenchmarkIndex++; } newResult.median = oldResult.median; newResult.best = oldResult.best; newResult.worst = oldResult.worst; solverBenchmarkResult.getSingleBenchmarkResultList().add(newResult); problemBenchmarkResult.getSingleBenchmarkResultList().add(newResult); return newResult; } @Override public String toString() { return getName(); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/result/SolverBenchmarkResult.java
package ai.timefold.solver.benchmark.impl.result; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlTransient; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.ReportHelper; import ai.timefold.solver.benchmark.impl.statistic.StatisticUtils; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.solver.Solver; import ai.timefold.solver.core.config.solver.EnvironmentMode; import ai.timefold.solver.core.config.solver.SolverConfig; import ai.timefold.solver.core.impl.io.jaxb.GenericJaxbIO; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; /** * Represents 1 {@link Solver} configuration benchmarked on multiple problem instances (data sets). */ public class SolverBenchmarkResult { @XmlTransient // Bi-directional relationship restored through BenchmarkResultIO private PlannerBenchmarkResult plannerBenchmarkResult; private String name = null; private Integer subSingleCount = null; @XmlElement(namespace = SolverConfig.XML_NAMESPACE) private SolverConfig solverConfig = null; @XmlTransient // Restored through BenchmarkResultIO private ScoreDefinition scoreDefinition = null; @XmlElement(name = "singleBenchmarkResult") private List<SingleBenchmarkResult> singleBenchmarkResultList = null; // ************************************************************************ // Report accumulates // ************************************************************************ private Integer failureCount = null; private Integer uninitializedSolutionCount = null; private Integer infeasibleScoreCount = null; private Score totalScore = null; private Score averageScore = null; // Not a Score because // - the squaring would cause overflow for relatively small int and long scores. // - standard deviation should not be rounded to integer numbers private double[] standardDeviationDoubles = null; private Score totalWinningScoreDifference = null; private ScoreDifferencePercentage averageWorstScoreDifferencePercentage = null; // The average of the average is not just the overall average if the SingleBenchmarkResult's timeMillisSpent differ private Long averageScoreCalculationSpeed = null; private Long averageMoveEvaluationSpeed = null; private Long averageTimeMillisSpent = null; private Double averageWorstScoreCalculationSpeedDifferencePercentage = null; // Ranking starts from 0 private Integer ranking = null; // ************************************************************************ // Constructors and simple getters/setters // ************************************************************************ private SolverBenchmarkResult() { // Required by JAXB } public SolverBenchmarkResult(PlannerBenchmarkResult plannerBenchmarkResult) { this.plannerBenchmarkResult = plannerBenchmarkResult; } public PlannerBenchmarkResult getPlannerBenchmarkResult() { return plannerBenchmarkResult; } public void setPlannerBenchmarkResult(PlannerBenchmarkResult plannerBenchmarkResult) { this.plannerBenchmarkResult = plannerBenchmarkResult; } /** * @return never null, filename safe */ public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSubSingleCount() { return subSingleCount; } public void setSubSingleCount(Integer subSingleCount) { this.subSingleCount = subSingleCount; } public SolverConfig getSolverConfig() { return solverConfig; } public void setSolverConfig(SolverConfig solverConfig) { this.solverConfig = solverConfig; } public ScoreDefinition getScoreDefinition() { return scoreDefinition; } public void setScoreDefinition(ScoreDefinition scoreDefinition) { this.scoreDefinition = scoreDefinition; } public List<SingleBenchmarkResult> getSingleBenchmarkResultList() { return singleBenchmarkResultList; } public void setSingleBenchmarkResultList(List<SingleBenchmarkResult> singleBenchmarkResultList) { this.singleBenchmarkResultList = singleBenchmarkResultList; } public Integer getFailureCount() { return failureCount; } public Integer getUninitializedSolutionCount() { return uninitializedSolutionCount; } public Integer getInfeasibleScoreCount() { return infeasibleScoreCount; } public Score getTotalScore() { return totalScore; } public Score getAverageScore() { return averageScore; } public Score getTotalWinningScoreDifference() { return totalWinningScoreDifference; } @SuppressWarnings("unused") // Used by FreeMarker. public ScoreDifferencePercentage getAverageWorstScoreDifferencePercentage() { return averageWorstScoreDifferencePercentage; } @SuppressWarnings("unused") // Used by FreeMarker. public Long getAverageScoreCalculationSpeed() { return averageScoreCalculationSpeed; } @SuppressWarnings("unused") // Used by FreeMarker. public Long getAverageMoveEvaluationSpeed() { return averageMoveEvaluationSpeed; } public Long getAverageTimeMillisSpent() { return averageTimeMillisSpent; } @SuppressWarnings("unused") // Used by FreeMarker. public Double getAverageWorstScoreCalculationSpeedDifferencePercentage() { return averageWorstScoreCalculationSpeedDifferencePercentage; } public Integer getRanking() { return ranking; } public void setRanking(Integer ranking) { this.ranking = ranking; } // ************************************************************************ // Smart getters // ************************************************************************ @SuppressWarnings("unused") // Used by FreeMarker. public String getAnchorId() { return ReportHelper.escapeHtmlId(name); } public String getNameWithFavoriteSuffix() { if (isFavorite()) { return name + " (favorite)"; } return name; } public int getSuccessCount() { return getSingleBenchmarkResultList().size() - getFailureCount(); } @SuppressWarnings("unused") // Used by FreeMarker. public boolean hasAnySuccess() { return getSuccessCount() > 0; } public boolean hasAnyFailure() { return failureCount > 0; } @SuppressWarnings("unused") // Used by FreeMarker. public boolean hasAnyUninitializedSolution() { return uninitializedSolutionCount > 0; } @SuppressWarnings("unused") // Used by FreeMarker. public boolean hasAnyInfeasibleScore() { return infeasibleScoreCount > 0; } public boolean isFavorite() { return ranking != null && ranking.intValue() == 0; } @SuppressWarnings("unused") // Used by FreeMarker. public Score getAverageWinningScoreDifference() { if (totalWinningScoreDifference == null) { return null; } return totalWinningScoreDifference.divide(getSuccessCount()); } /** * @param problemBenchmarkResult never null * @return sometimes null */ @SuppressWarnings("unused") // Used by FreeMarker. public SingleBenchmarkResult findSingleBenchmark(ProblemBenchmarkResult problemBenchmarkResult) { for (SingleBenchmarkResult singleBenchmarkResult : singleBenchmarkResultList) { if (problemBenchmarkResult.equals(singleBenchmarkResult.getProblemBenchmarkResult())) { return singleBenchmarkResult; } } return null; } @SuppressWarnings("unused") // Used by FreeMarker. public String getSolverConfigAsString() { GenericJaxbIO<SolverConfig> xmlIO = new GenericJaxbIO<>(SolverConfig.class); StringWriter stringWriter = new StringWriter(); xmlIO.write(solverConfig, stringWriter); return stringWriter.toString(); } public EnvironmentMode getEnvironmentMode() { return solverConfig.determineEnvironmentMode(); } @SuppressWarnings("unused") // Used by FreeMarker. public String getStandardDeviationString() { return StatisticUtils.getStandardDeviationString(standardDeviationDoubles); } // ************************************************************************ // Accumulate methods // ************************************************************************ /** * Does not call {@link SingleBenchmarkResult#accumulateResults(BenchmarkReport)}, * because {@link PlannerBenchmarkResult#accumulateResults(BenchmarkReport)} does that already on * {@link PlannerBenchmarkResult#getUnifiedProblemBenchmarkResultList()}. * * @param benchmarkReport never null */ public void accumulateResults(BenchmarkReport benchmarkReport) { determineTotalsAndAverages(); standardDeviationDoubles = StatisticUtils.determineStandardDeviationDoubles(singleBenchmarkResultList, averageScore, getSuccessCount()); } protected void determineTotalsAndAverages() { failureCount = 0; boolean firstNonFailure = true; totalScore = null; totalWinningScoreDifference = null; ScoreDifferencePercentage totalWorstScoreDifferencePercentage = null; long totalScoreCalculationSpeed = 0L; long totalMoveEvaluationSpeed = 0L; long totalTimeMillisSpent = 0L; double totalWorstScoreCalculationSpeedDifferencePercentage = 0.0; uninitializedSolutionCount = 0; infeasibleScoreCount = 0; for (SingleBenchmarkResult singleBenchmarkResult : singleBenchmarkResultList) { if (singleBenchmarkResult.hasAnyFailure()) { failureCount++; } else { if (!singleBenchmarkResult.isInitialized()) { uninitializedSolutionCount++; } else if (!singleBenchmarkResult.isScoreFeasible()) { infeasibleScoreCount++; } if (firstNonFailure) { totalScore = singleBenchmarkResult.getAverageScore(); totalWinningScoreDifference = singleBenchmarkResult.getWinningScoreDifference(); totalWorstScoreDifferencePercentage = singleBenchmarkResult.getWorstScoreDifferencePercentage(); totalScoreCalculationSpeed = singleBenchmarkResult.getScoreCalculationSpeed(); totalMoveEvaluationSpeed = singleBenchmarkResult.getMoveEvaluationSpeed(); totalTimeMillisSpent = singleBenchmarkResult.getTimeMillisSpent(); totalWorstScoreCalculationSpeedDifferencePercentage = singleBenchmarkResult .getWorstScoreCalculationSpeedDifferencePercentage(); firstNonFailure = false; } else { totalScore = totalScore.add(singleBenchmarkResult.getAverageScore()); totalWinningScoreDifference = totalWinningScoreDifference.add( singleBenchmarkResult.getWinningScoreDifference()); totalWorstScoreDifferencePercentage = totalWorstScoreDifferencePercentage.add( singleBenchmarkResult.getWorstScoreDifferencePercentage()); totalScoreCalculationSpeed += singleBenchmarkResult.getScoreCalculationSpeed(); totalMoveEvaluationSpeed += singleBenchmarkResult.getMoveEvaluationSpeed(); totalTimeMillisSpent += singleBenchmarkResult.getTimeMillisSpent(); totalWorstScoreCalculationSpeedDifferencePercentage += singleBenchmarkResult .getWorstScoreCalculationSpeedDifferencePercentage(); } } } if (!firstNonFailure) { int successCount = getSuccessCount(); averageScore = totalScore.divide(successCount); averageWorstScoreDifferencePercentage = totalWorstScoreDifferencePercentage.divide(successCount); averageScoreCalculationSpeed = totalScoreCalculationSpeed / successCount; averageMoveEvaluationSpeed = totalMoveEvaluationSpeed / successCount; averageTimeMillisSpent = totalTimeMillisSpent / successCount; averageWorstScoreCalculationSpeedDifferencePercentage = totalWorstScoreCalculationSpeedDifferencePercentage / successCount; } } // ************************************************************************ // Merger methods // ************************************************************************ protected static Map<SolverBenchmarkResult, SolverBenchmarkResult> createMergeMap( PlannerBenchmarkResult newPlannerBenchmarkResult, List<SingleBenchmarkResult> singleBenchmarkResultList) { // IdentityHashMap because different SolverBenchmarkResult instances are never merged Map<SolverBenchmarkResult, SolverBenchmarkResult> mergeMap = new IdentityHashMap<>(); Map<String, Integer> nameCountMap = new HashMap<>(); for (SingleBenchmarkResult singleBenchmarkResult : singleBenchmarkResultList) { SolverBenchmarkResult oldResult = singleBenchmarkResult.getSolverBenchmarkResult(); if (!mergeMap.containsKey(oldResult)) { SolverBenchmarkResult newResult = new SolverBenchmarkResult(newPlannerBenchmarkResult); Integer nameCount = nameCountMap.get(oldResult.name); if (nameCount == null) { nameCount = 1; } else { nameCount++; } nameCountMap.put(oldResult.name, nameCount); newResult.subSingleCount = oldResult.subSingleCount; newResult.solverConfig = oldResult.solverConfig; newResult.scoreDefinition = oldResult.scoreDefinition; newResult.singleBenchmarkResultList = new ArrayList<>( oldResult.singleBenchmarkResultList.size()); mergeMap.put(oldResult, newResult); newPlannerBenchmarkResult.getSolverBenchmarkResultList().add(newResult); } } // Make name unique for (Map.Entry<SolverBenchmarkResult, SolverBenchmarkResult> entry : mergeMap.entrySet()) { SolverBenchmarkResult oldResult = entry.getKey(); SolverBenchmarkResult newResult = entry.getValue(); if (nameCountMap.get(oldResult.name) > 1) { newResult.name = oldResult.name + " (" + oldResult.getPlannerBenchmarkResult().getName() + ")"; } else { newResult.name = oldResult.name; } } return mergeMap; } @Override public String toString() { return getName(); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/result/SubSingleBenchmarkResult.java
package ai.timefold.solver.benchmark.impl.result; import static ai.timefold.solver.core.impl.util.MathUtils.getSpeed; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlElements; import jakarta.xml.bind.annotation.XmlTransient; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.statistic.ProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.PureSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.StatisticType; import ai.timefold.solver.benchmark.impl.statistic.SubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.subsingle.constraintmatchtotalbestscore.ConstraintMatchTotalBestScoreSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.subsingle.constraintmatchtotalstepscore.ConstraintMatchTotalStepScoreSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.subsingle.pickedmovetypebestscore.PickedMoveTypeBestScoreDiffSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.subsingle.pickedmovetypestepscore.PickedMoveTypeStepScoreDiffSubSingleStatistic; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.solver.Solver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents 1 benchmark run for 1 Single Benchmark configuration for 1 {@link Solver} configuration for 1 problem * instance (data set). */ public class SubSingleBenchmarkResult implements BenchmarkResult { private static final Logger LOGGER = LoggerFactory.getLogger(SubSingleBenchmarkResult.class); @XmlTransient // Bi-directional relationship restored through BenchmarkResultIO private SingleBenchmarkResult singleBenchmarkResult; private int subSingleBenchmarkIndex; @XmlElements({ @XmlElement(name = "constraintMatchTotalBestScoreSubSingleStatistic", type = ConstraintMatchTotalBestScoreSubSingleStatistic.class), @XmlElement(name = "constraintMatchTotalStepScoreSubSingleStatistic", type = ConstraintMatchTotalStepScoreSubSingleStatistic.class), @XmlElement(name = "pickedMoveTypeBestScoreDiffSubSingleStatistic", type = PickedMoveTypeBestScoreDiffSubSingleStatistic.class), @XmlElement(name = "pickedMoveTypeStepScoreDiffSubSingleStatistic", type = PickedMoveTypeStepScoreDiffSubSingleStatistic.class) }) private List<PureSubSingleStatistic> pureSubSingleStatisticList = null; @XmlTransient // Lazily restored when read through ProblemStatistic and CSV files private Map<StatisticType, SubSingleStatistic> effectiveSubSingleStatisticMap; private Long usedMemoryAfterInputSolution = null; private Boolean succeeded = null; private Score<?> score = null; private boolean initialized = false; private long timeMillisSpent = -1L; private long scoreCalculationCount = -1L; private long moveEvaluationCount = -1L; private String scoreExplanationSummary = null; // ************************************************************************ // Report accumulates // ************************************************************************ // Ranking starts from 0 private Integer ranking = null; // ************************************************************************ // Constructors and simple getters/setters // ************************************************************************ private SubSingleBenchmarkResult() { // Required by JAXB } public SubSingleBenchmarkResult(SingleBenchmarkResult singleBenchmarkResult, int subSingleBenchmarkIndex) { this.singleBenchmarkResult = singleBenchmarkResult; this.subSingleBenchmarkIndex = subSingleBenchmarkIndex; } public List<PureSubSingleStatistic> getPureSubSingleStatisticList() { return pureSubSingleStatisticList; } public void setPureSubSingleStatisticList(List<PureSubSingleStatistic> pureSubSingleStatisticList) { this.pureSubSingleStatisticList = pureSubSingleStatisticList; } public void initSubSingleStatisticMap() { List<ProblemStatistic> problemStatisticList = singleBenchmarkResult.getProblemBenchmarkResult().getProblemStatisticList(); effectiveSubSingleStatisticMap = new HashMap<>( problemStatisticList.size() + pureSubSingleStatisticList.size()); for (var problemStatistic : problemStatisticList) { var subSingleStatistic = problemStatistic.createSubSingleStatistic(this); effectiveSubSingleStatisticMap.put(subSingleStatistic.getStatisticType(), subSingleStatistic); } for (var pureSubSingleStatistic : pureSubSingleStatisticList) { effectiveSubSingleStatisticMap.put(pureSubSingleStatistic.getStatisticType(), pureSubSingleStatistic); } } public SingleBenchmarkResult getSingleBenchmarkResult() { return singleBenchmarkResult; } public void setSingleBenchmarkResult(SingleBenchmarkResult singleBenchmarkResult) { this.singleBenchmarkResult = singleBenchmarkResult; } public int getSubSingleBenchmarkIndex() { return subSingleBenchmarkIndex; } public Map<StatisticType, SubSingleStatistic> getEffectiveSubSingleStatisticMap() { return effectiveSubSingleStatisticMap; } /** * @return null if {@link PlannerBenchmarkResult#hasMultipleParallelBenchmarks()} return true */ public Long getUsedMemoryAfterInputSolution() { return usedMemoryAfterInputSolution; } public void setUsedMemoryAfterInputSolution(Long usedMemoryAfterInputSolution) { this.usedMemoryAfterInputSolution = usedMemoryAfterInputSolution; } public Boolean getSucceeded() { return succeeded; } public void setSucceeded(Boolean succeeded) { this.succeeded = succeeded; } public Score<?> getScore() { return score; } public void setScore(Score<?> score, boolean isInitialized) { this.score = score; this.initialized = isInitialized; } public long getTimeMillisSpent() { return timeMillisSpent; } public void setTimeMillisSpent(long timeMillisSpent) { this.timeMillisSpent = timeMillisSpent; } public long getScoreCalculationCount() { return scoreCalculationCount; } public void setScoreCalculationCount(long scoreCalculationCount) { this.scoreCalculationCount = scoreCalculationCount; } public long getMoveEvaluationCount() { return moveEvaluationCount; } public void setMoveEvaluationCount(long moveEvaluationCount) { this.moveEvaluationCount = moveEvaluationCount; } public String getScoreExplanationSummary() { return scoreExplanationSummary; } public void setScoreExplanationSummary(String scoreExplanationSummary) { this.scoreExplanationSummary = scoreExplanationSummary; } public Integer getRanking() { return ranking; } public void setRanking(Integer ranking) { this.ranking = ranking; } // ************************************************************************ // Smart getters // ************************************************************************ /** * @return never null, filename safe */ @Override public String getName() { return singleBenchmarkResult.getName() + "_" + subSingleBenchmarkIndex; } @Override public boolean hasAllSuccess() { return succeeded != null && succeeded; } public boolean isInitialized() { return score != null && initialized; } @Override public boolean hasAnyFailure() { return succeeded != null && !succeeded; } public boolean isScoreFeasible() { return score.isFeasible(); } @SuppressWarnings("unused") // Used by FreeMarker. public Long getScoreCalculationSpeed() { return getSpeed(scoreCalculationCount, this.timeMillisSpent); } @SuppressWarnings("unused") // Used by FreeMarker. public Long getMoveEvaluationSpeed() { return getSpeed(moveEvaluationCount, this.timeMillisSpent); } @SuppressWarnings("unused") // Used by FreeMarker. public boolean isWinner() { return ranking != null && ranking.intValue() == 0; } public SubSingleStatistic getSubSingleStatistic(StatisticType statisticType) { return effectiveSubSingleStatisticMap.get(statisticType); } @Override public Score<?> getAverageScore() { return getScore(); } // ************************************************************************ // Accumulate methods // ************************************************************************ @Override public String getResultDirectoryName() { return "sub" + subSingleBenchmarkIndex; } @Override public File getResultDirectory() { return new File(singleBenchmarkResult.getResultDirectory(), getResultDirectoryName()); } public void makeDirs() { var subSingleReportDirectory = getResultDirectory(); subSingleReportDirectory.mkdirs(); } public void accumulateResults(BenchmarkReport benchmarkReport) { } // ************************************************************************ // Merger methods // ************************************************************************ protected static SubSingleBenchmarkResult createMerge( SingleBenchmarkResult singleBenchmarkResult, SubSingleBenchmarkResult oldResult, int subSingleBenchmarkIndex) { var newResult = new SubSingleBenchmarkResult(singleBenchmarkResult, subSingleBenchmarkIndex); newResult.pureSubSingleStatisticList = new ArrayList<>(oldResult.pureSubSingleStatisticList.size()); for (var oldSubSingleStatistic : oldResult.pureSubSingleStatisticList) { newResult.pureSubSingleStatisticList.add( oldSubSingleStatistic.getStatisticType().buildPureSubSingleStatistic(newResult)); } newResult.initSubSingleStatisticMap(); for (var newSubSingleStatistic : newResult.effectiveSubSingleStatisticMap.values()) { var oldSubSingleStatistic = oldResult .getSubSingleStatistic(newSubSingleStatistic.getStatisticType()); if (!oldSubSingleStatistic.getCsvFile().exists()) { if (oldResult.hasAnyFailure()) { newSubSingleStatistic.initPointList(); LOGGER.debug("Old result ({}) is a failure, skipping merge of its sub single statistic ({}).", oldResult, oldSubSingleStatistic); continue; } else { throw new IllegalStateException("Could not find old result's (" + oldResult + ") sub single statistic's (" + oldSubSingleStatistic + ") CSV file."); } } oldSubSingleStatistic.unhibernatePointList(); newSubSingleStatistic.setPointList(oldSubSingleStatistic.getPointList()); oldSubSingleStatistic.hibernatePointList(); } // Skip oldResult.reportDirectory // Skip oldResult.usedMemoryAfterInputSolution newResult.succeeded = oldResult.succeeded; newResult.score = oldResult.score; newResult.initialized = oldResult.initialized; newResult.timeMillisSpent = oldResult.timeMillisSpent; newResult.scoreCalculationCount = oldResult.scoreCalculationCount; newResult.moveEvaluationCount = oldResult.moveEvaluationCount; singleBenchmarkResult.getSubSingleBenchmarkResultList().add(newResult); return newResult; } @Override public String toString() { return getName(); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/result/package-info.java
@XmlAccessorType(XmlAccessType.FIELD) @XmlJavaTypeAdapters({ @XmlJavaTypeAdapter(value = PolymorphicScoreJaxbAdapter.class, type = Score.class), @XmlJavaTypeAdapter(value = JaxbOffsetDateTimeAdapter.class, type = OffsetDateTime.class) }) package ai.timefold.solver.benchmark.impl.result; import java.time.OffsetDateTime; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapters; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.io.jaxb.adapter.JaxbOffsetDateTimeAdapter; import ai.timefold.solver.jaxb.api.score.PolymorphicScoreJaxbAdapter;
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/ChartProvider.java
package ai.timefold.solver.benchmark.impl.statistic; import java.util.List; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.Chart; public interface ChartProvider<Chart_ extends Chart> { void createChartList(BenchmarkReport benchmarkReport); /** * * @return null unless {@link #createChartList(BenchmarkReport)} was called */ List<Chart_> getChartList(); }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/ConstraintSummary.java
package ai.timefold.solver.benchmark.impl.statistic; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.constraint.ConstraintRef; public record ConstraintSummary<Score_ extends Score<Score_>>(ConstraintRef constraintRef, Score_ score, int count) { }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/ProblemBasedSubSingleStatistic.java
package ai.timefold.solver.benchmark.impl.statistic; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; public abstract class ProblemBasedSubSingleStatistic<Solution_, StatisticPoint_ extends StatisticPoint> extends SubSingleStatistic<Solution_, StatisticPoint_> { protected ProblemStatisticType problemStatisticType; protected ProblemBasedSubSingleStatistic() { // For JAXB. } protected ProblemBasedSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult, ProblemStatisticType problemStatisticType) { super(subSingleBenchmarkResult); this.problemStatisticType = problemStatisticType; } @Override public ProblemStatisticType getStatisticType() { return problemStatisticType; } @Override public String toString() { return subSingleBenchmarkResult + "_" + problemStatisticType; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/ProblemStatistic.java
package ai.timefold.solver.benchmark.impl.statistic; import java.util.ArrayList; import java.util.Collections; import java.util.List; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlSeeAlso; import jakarta.xml.bind.annotation.XmlTransient; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.Chart; import ai.timefold.solver.benchmark.impl.report.ReportHelper; import ai.timefold.solver.benchmark.impl.result.ProblemBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.bestscore.BestScoreProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.bestsolutionmutation.BestSolutionMutationProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.memoryuse.MemoryUseProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.movecountperstep.MoveCountPerStepProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.moveevaluationspeed.MoveEvaluationSpeedProblemStatisticTime; import ai.timefold.solver.benchmark.impl.statistic.scorecalculationspeed.ScoreCalculationSpeedProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.stepscore.StepScoreProblemStatistic; /** * 1 statistic of {@link ProblemBenchmarkResult}. */ @XmlAccessorType(XmlAccessType.FIELD) @XmlSeeAlso({ BestScoreProblemStatistic.class, StepScoreProblemStatistic.class, ScoreCalculationSpeedProblemStatistic.class, MoveEvaluationSpeedProblemStatisticTime.class, BestSolutionMutationProblemStatistic.class, MoveCountPerStepProblemStatistic.class, MemoryUseProblemStatistic.class }) public abstract class ProblemStatistic<Chart_ extends Chart> implements ChartProvider<Chart_> { @XmlTransient // Bi-directional relationship restored through BenchmarkResultIO protected ProblemBenchmarkResult<Object> problemBenchmarkResult; @XmlTransient protected List<Chart_> chartList; protected ProblemStatisticType problemStatisticType; // ************************************************************************ // Report accumulates // ************************************************************************ protected ProblemStatistic() { // For JAXB. } protected ProblemStatistic(ProblemBenchmarkResult problemBenchmarkResult, ProblemStatisticType problemStatisticType) { this.problemBenchmarkResult = problemBenchmarkResult; this.problemStatisticType = problemStatisticType; } public ProblemBenchmarkResult getProblemBenchmarkResult() { return problemBenchmarkResult; } public void setProblemBenchmarkResult(ProblemBenchmarkResult problemBenchmarkResult) { this.problemBenchmarkResult = problemBenchmarkResult; } public ProblemStatisticType getProblemStatisticType() { return problemStatisticType; } @SuppressWarnings("unused") // Used by FreeMarker. public String getAnchorId() { return ReportHelper.escapeHtmlId(problemBenchmarkResult.getName() + "_" + problemStatisticType.name()); } @SuppressWarnings("unused") // Used by FreeMarker. public List<SubSingleStatistic> getSubSingleStatisticList() { List<SingleBenchmarkResult> singleBenchmarkResultList = problemBenchmarkResult.getSingleBenchmarkResultList(); List<SubSingleStatistic> subSingleStatisticList = new ArrayList<>(singleBenchmarkResultList.size()); for (SingleBenchmarkResult singleBenchmarkResult : singleBenchmarkResultList) { if (singleBenchmarkResult.getSubSingleBenchmarkResultList().isEmpty()) { continue; } // All subSingles have the same sub single statistics subSingleStatisticList.add(singleBenchmarkResult.getSubSingleBenchmarkResultList().get(0) .getEffectiveSubSingleStatisticMap().get(problemStatisticType)); } return subSingleStatisticList; } public abstract SubSingleStatistic createSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult); // ************************************************************************ // Write methods // ************************************************************************ @Override public final void createChartList(BenchmarkReport benchmarkReport) { this.chartList = generateCharts(benchmarkReport); } protected abstract List<Chart_> generateCharts(BenchmarkReport benchmarkReport); @Override public final List<Chart_> getChartList() { return chartList; } @SuppressWarnings("unused") // Used by FreeMarker. public List<String> getWarningList() { return Collections.emptyList(); } @Override public String toString() { return problemBenchmarkResult + "_" + problemStatisticType; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/PureSubSingleStatistic.java
package ai.timefold.solver.benchmark.impl.statistic; import java.util.ArrayList; import java.util.List; import jakarta.xml.bind.annotation.XmlSeeAlso; import jakarta.xml.bind.annotation.XmlTransient; import ai.timefold.solver.benchmark.config.statistic.SingleStatisticType; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.Chart; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.subsingle.constraintmatchtotalbestscore.ConstraintMatchTotalBestScoreSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.subsingle.constraintmatchtotalstepscore.ConstraintMatchTotalStepScoreSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.subsingle.pickedmovetypebestscore.PickedMoveTypeBestScoreDiffSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.subsingle.pickedmovetypestepscore.PickedMoveTypeStepScoreDiffSubSingleStatistic; /** * 1 statistic of {@link SubSingleBenchmarkResult}. */ @XmlSeeAlso({ ConstraintMatchTotalBestScoreSubSingleStatistic.class, ConstraintMatchTotalStepScoreSubSingleStatistic.class, PickedMoveTypeBestScoreDiffSubSingleStatistic.class, PickedMoveTypeStepScoreDiffSubSingleStatistic.class }) public abstract class PureSubSingleStatistic<Solution_, StatisticPoint_ extends StatisticPoint, Chart_ extends Chart> extends SubSingleStatistic<Solution_, StatisticPoint_> implements ChartProvider<Chart_> { protected SingleStatisticType singleStatisticType; @XmlTransient protected List<Chart_> chartList = new ArrayList<>(); protected PureSubSingleStatistic() { // For JAXB. } protected PureSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult, SingleStatisticType singleStatisticType) { super(subSingleBenchmarkResult); this.singleStatisticType = singleStatisticType; } @Override public SingleStatisticType getStatisticType() { return singleStatisticType; } @Override public final void createChartList(BenchmarkReport benchmarkReport) { this.chartList = generateCharts(benchmarkReport); } protected abstract List<Chart_> generateCharts(BenchmarkReport benchmarkReport); @Override public final List<Chart_> getChartList() { return chartList; } @Override public String toString() { return subSingleBenchmarkResult + "_" + singleStatisticType; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/StatisticPoint.java
package ai.timefold.solver.benchmark.impl.statistic; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Implementations must be immutable. */ public abstract class StatisticPoint { private static final Pattern DOUBLE_QUOTE = Pattern.compile("\"\""); private static final Pattern SINGLE_QUOTE = Pattern.compile("\""); public abstract String toCsvLine(); public static String buildCsvLineWithLongs(long timeMillisSpent, long... values) { Object[] array = Stream.concat(Stream.of(timeMillisSpent), Arrays.stream(values).boxed()) .toArray(Object[]::new); return buildCsvLine(array); } public static String buildCsvLineWithDoubles(long timeMillisSpent, double... values) { Object[] array = Stream.concat(Stream.of(timeMillisSpent), Arrays.stream(values).boxed()) .toArray(Object[]::new); return buildCsvLine(array); } public static String buildCsvLineWithStrings(long timeMillisSpent, String... values) { Object[] array = Stream.concat(Stream.of(timeMillisSpent), Arrays.stream(values)) .toArray(Object[]::new); return buildCsvLine(array); } public static String buildCsvLine(Object... values) { return Arrays.stream(values) .map(s -> { if (s instanceof Boolean bool) { return bool ? "true" : "false"; } else if (s instanceof Integer num) { return Integer.toString(num); } else if (s instanceof Long num) { return Long.toString(num); } else { return '"' + SINGLE_QUOTE.matcher(s.toString()).replaceAll("\"\"") + '"'; } }) .collect(Collectors.joining(",")); } public static List<String> parseCsvLine(String line) { String[] tokens = line.split(","); List<String> csvLine = new ArrayList<>(tokens.length); for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; while (token.startsWith("\"") && !token.endsWith("\"")) { i++; if (i >= tokens.length) { throw new IllegalArgumentException("The CSV line (" + line + ") is not a valid CSV line."); } token += "," + tokens[i]; } if (token.startsWith("\"") && token.endsWith("\"")) { token = token.substring(1, token.length() - 1); token = DOUBLE_QUOTE.matcher(token).replaceAll("\""); } csvLine.add(token); } return csvLine; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/StatisticRegistry.java
package ai.timefold.solver.benchmark.impl.statistic; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.ObjLongConsumer; import java.util.stream.Collectors; import ai.timefold.solver.core.api.score.constraint.ConstraintRef; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleListener; import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import ai.timefold.solver.core.impl.score.director.InnerScore; import ai.timefold.solver.core.impl.solver.monitoring.SolverMetricUtil; import ai.timefold.solver.core.impl.solver.scope.SolverScope; import io.micrometer.core.instrument.Meter; import io.micrometer.core.instrument.Tags; import io.micrometer.core.instrument.search.Search; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; public class StatisticRegistry<Solution_> extends SimpleMeterRegistry implements PhaseLifecycleListener<Solution_> { private static final String CONSTRAINT_PACKAGE_TAG = "constraint.package"; private static final String CONSTRAINT_NAME_TAG = "constraint.name"; List<Consumer<SolverScope<Solution_>>> solverMeterListenerList = new ArrayList<>(); List<BiConsumer<Long, AbstractStepScope<Solution_>>> stepMeterListenerList = new ArrayList<>(); List<BiConsumer<Long, AbstractStepScope<Solution_>>> bestSolutionMeterListenerList = new ArrayList<>(); AbstractStepScope<Solution_> bestSolutionStepScope = null; long bestSolutionChangedTimestamp = Long.MIN_VALUE; boolean lastStepImprovedSolution = false; ScoreDefinition<?> scoreDefinition; final Function<Number, Number> scoreLevelNumberConverter; public StatisticRegistry(ScoreDefinition<?> scoreDefinition) { this.scoreDefinition = scoreDefinition; var zeroScoreLevel0 = scoreDefinition.getZeroScore().toLevelNumbers()[0]; if (zeroScoreLevel0 instanceof BigDecimal) { scoreLevelNumberConverter = number -> BigDecimal.valueOf(number.doubleValue()); } else if (zeroScoreLevel0 instanceof BigInteger) { scoreLevelNumberConverter = number -> BigInteger.valueOf(number.longValue()); } else if (zeroScoreLevel0 instanceof Double) { scoreLevelNumberConverter = Number::doubleValue; } else if (zeroScoreLevel0 instanceof Float) { scoreLevelNumberConverter = Number::floatValue; } else if (zeroScoreLevel0 instanceof Long) { scoreLevelNumberConverter = Number::longValue; } else if (zeroScoreLevel0 instanceof Integer) { scoreLevelNumberConverter = Number::intValue; } else if (zeroScoreLevel0 instanceof Short) { scoreLevelNumberConverter = Number::shortValue; } else if (zeroScoreLevel0 instanceof Byte) { scoreLevelNumberConverter = Number::byteValue; } else { throw new IllegalStateException( "Cannot determine score level type for score definition (" + scoreDefinition.getClass().getName() + ")."); } } public void addListener(SolverMetric metric, Consumer<Long> listener) { addListener(metric, (timestamp, stepScope) -> listener.accept(timestamp)); } public void addListener(SolverMetric metric, BiConsumer<Long, AbstractStepScope<Solution_>> listener) { if (metric.isMetricBestSolutionBased()) { bestSolutionMeterListenerList.add(listener); } else { stepMeterListenerList.add(listener); } } public void addListener(Consumer<SolverScope<Solution_>> listener) { solverMeterListenerList.add(listener); } public Set<Meter.Id> getMeterIds(SolverMetric metric, Tags runId) { return Search.in(this).name(name -> name.startsWith(metric.getMeterId())).tags(runId) .meters().stream().map(Meter::getId) .collect(Collectors.toSet()); } public void extractScoreFromMeters(SolverMetric metric, Tags runId, Consumer<InnerScore<?>> scoreConsumer) { var score = SolverMetricUtil.extractScore(metric, scoreDefinition, id -> { var scoreLevelGauge = this.find(id).tags(runId).gauge(); if (scoreLevelGauge != null && Double.isFinite(scoreLevelGauge.value())) { return scoreLevelNumberConverter.apply(scoreLevelGauge.value()); } else { return null; } }); if (score != null) { scoreConsumer.accept(score); } } @SuppressWarnings({ "rawtypes", "unchecked" }) public void extractConstraintSummariesFromMeters(SolverMetric metric, Tags runId, Consumer<ConstraintSummary<?>> constraintMatchTotalConsumer) { // Add the constraint ids from the meter ids getMeterIds(metric, runId) .stream() .map(meterId -> ConstraintRef.of(meterId.getTag(CONSTRAINT_PACKAGE_TAG), meterId.getTag(CONSTRAINT_NAME_TAG))) .distinct() .forEach(constraintRef -> { var constraintMatchTotalRunId = runId.and(CONSTRAINT_PACKAGE_TAG, constraintRef.packageName()) .and(CONSTRAINT_NAME_TAG, constraintRef.constraintName()); // Get the score from the corresponding constraint package and constraint name meters extractScoreFromMeters(metric, constraintMatchTotalRunId, // Get the count gauge (add constraint package and constraint name to the run tags) score -> { var count = SolverMetricUtil.getGaugeValue(this, SolverMetricUtil.getGaugeName(metric, "count"), constraintMatchTotalRunId); if (count != null) { constraintMatchTotalConsumer .accept(new ConstraintSummary(constraintRef, score.raw(), count.intValue())); } }); }); } public void extractMoveCountPerType(SolverScope<Solution_> solverScope, ObjLongConsumer<String> gaugeConsumer) { solverScope.getMoveCountTypes().forEach(type -> { var gauge = this.find(SolverMetric.MOVE_COUNT_PER_TYPE.getMeterId() + "." + type) .tags(solverScope.getMonitoringTags()).gauge(); if (gauge != null) { gaugeConsumer.accept(type, (long) gauge.value()); } }); } @Override protected TimeUnit getBaseTimeUnit() { return TimeUnit.MILLISECONDS; } @Override public void stepEnded(AbstractStepScope<Solution_> stepScope) { var timestamp = System.currentTimeMillis() - stepScope.getPhaseScope().getSolverScope().getStartingSystemTimeMillis(); stepMeterListenerList.forEach(listener -> listener.accept(timestamp, stepScope)); if (stepScope.getBestScoreImproved()) { // Since best solution metrics are updated in a best solution listener, we need // to delay updating it until after the best solution listeners were processed bestSolutionStepScope = stepScope; bestSolutionChangedTimestamp = timestamp; lastStepImprovedSolution = true; } } @Override public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { // intentional empty } @Override public void stepStarted(AbstractStepScope<Solution_> stepScope) { if (lastStepImprovedSolution) { bestSolutionMeterListenerList .forEach(listener -> listener.accept(bestSolutionChangedTimestamp, bestSolutionStepScope)); lastStepImprovedSolution = false; } } @Override public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { // intentional empty } @Override public void solvingStarted(SolverScope<Solution_> solverScope) { // intentional empty } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { if (lastStepImprovedSolution) { bestSolutionMeterListenerList .forEach(listener -> listener.accept(bestSolutionChangedTimestamp, bestSolutionStepScope)); lastStepImprovedSolution = false; } solverMeterListenerList.forEach(listener -> listener.accept(solverScope)); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/StatisticType.java
package ai.timefold.solver.benchmark.impl.statistic; public interface StatisticType { /** * @return never null */ String name(); /** * @return never null */ default String getLabel() { return name().replace('_', ' '); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/StatisticUtils.java
package ai.timefold.solver.benchmark.impl.statistic; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.List; import java.util.Locale; import ai.timefold.solver.benchmark.impl.result.BenchmarkResult; import ai.timefold.solver.core.api.score.Score; public class StatisticUtils { private StatisticUtils() { // This class is not instantiable } /** * Calculates standard deviation of {@link BenchmarkResult#getAverageScore()}s from {@code averageScore}. * * @param averageScore not null * @return standard deviation double values */ public static double[] determineStandardDeviationDoubles( List<? extends BenchmarkResult> benchmarkResultList, Score averageScore, int successCount) { if (successCount <= 0) { return new double[0]; } if (averageScore == null) { throw new IllegalArgumentException("Average score (" + averageScore + ") cannot be null."); } // averageScore can no longer be null double[] differenceSquaredTotalDoubles = null; for (BenchmarkResult benchmarkResult : benchmarkResultList) { if (benchmarkResult.hasAllSuccess()) { Score difference = benchmarkResult.getAverageScore().subtract(averageScore); // Calculations done on doubles to avoid common overflow when executing with an int score > 500 000 double[] differenceDoubles = difference.toLevelDoubles(); if (differenceSquaredTotalDoubles == null) { differenceSquaredTotalDoubles = new double[differenceDoubles.length]; } for (int i = 0; i < differenceDoubles.length; i++) { differenceSquaredTotalDoubles[i] += Math.pow(differenceDoubles[i], 2.0); } } } if (differenceSquaredTotalDoubles == null) { // no successful benchmarks return new double[0]; } double[] standardDeviationDoubles = new double[differenceSquaredTotalDoubles.length]; for (int i = 0; i < differenceSquaredTotalDoubles.length; i++) { standardDeviationDoubles[i] = Math.pow(differenceSquaredTotalDoubles[i] / successCount, 0.5); } return standardDeviationDoubles; } // TODO Do the locale formatting in benchmarkReport.html.ftl - https://issues.redhat.com/browse/PLANNER-169 public static String getStandardDeviationString(double[] standardDeviationDoubles) { if (standardDeviationDoubles == null) { return null; } StringBuilder standardDeviationString = new StringBuilder(standardDeviationDoubles.length * 9); // Abbreviate to 2 decimals // We don't use a local sensitive DecimalFormat, because other Scores don't use it either (see PLANNER-169) DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.US); DecimalFormat exponentialFormat = new DecimalFormat("0.0#E0", decimalFormatSymbols); DecimalFormat decimalFormat = new DecimalFormat("0.0#", decimalFormatSymbols); boolean first = true; for (double standardDeviationDouble : standardDeviationDoubles) { if (first) { first = false; } else { standardDeviationString.append("/"); } // See http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#toString%28double%29 String abbreviated; if (0.001 <= standardDeviationDouble && standardDeviationDouble <= 10000000.0) { abbreviated = decimalFormat.format(standardDeviationDouble); } else { abbreviated = exponentialFormat.format(standardDeviationDouble); } standardDeviationString.append(abbreviated); } return standardDeviationString.toString(); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/SubSingleStatistic.java
package ai.timefold.solver.benchmark.impl.statistic; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlTransient; import ai.timefold.solver.benchmark.impl.report.ReportHelper; import ai.timefold.solver.benchmark.impl.result.PlannerBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.micrometer.core.instrument.Tags; /** * 1 statistic of {@link SubSingleBenchmarkResult}. */ @XmlAccessorType(XmlAccessType.FIELD) public abstract class SubSingleStatistic<Solution_, StatisticPoint_ extends StatisticPoint> { private static final String FAILED = "Failed"; protected final transient Logger logger = LoggerFactory.getLogger(getClass()); @XmlTransient // Bi-directional relationship restored through BenchmarkResultIO protected SubSingleBenchmarkResult subSingleBenchmarkResult; @XmlTransient protected List<StatisticPoint_> pointList; protected SubSingleStatistic() { // For JAXB. } protected SubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { this.subSingleBenchmarkResult = subSingleBenchmarkResult; } public SubSingleBenchmarkResult getSubSingleBenchmarkResult() { return subSingleBenchmarkResult; } public void setSubSingleBenchmarkResult(SubSingleBenchmarkResult subSingleBenchmarkResult) { this.subSingleBenchmarkResult = subSingleBenchmarkResult; } public abstract StatisticType getStatisticType(); public List<StatisticPoint_> getPointList() { return pointList; } public void setPointList(List<StatisticPoint_> pointList) { this.pointList = pointList; } /** * @return never null, the relative path from {@link PlannerBenchmarkResult#getBenchmarkReportDirectory()}. */ @SuppressWarnings("unused") // Used by FreeMarker. public String getRelativeCsvFilePath() { SingleBenchmarkResult singleBenchmarkResult = subSingleBenchmarkResult.getSingleBenchmarkResult(); return singleBenchmarkResult.getProblemBenchmarkResult().getProblemReportDirectoryName() + "/" + singleBenchmarkResult.getResultDirectoryName() + "/" + subSingleBenchmarkResult.getResultDirectoryName() + "/" + getCsvFileName(); } public String getCsvFileName() { return getStatisticType().name() + ".csv"; } public File getCsvFile() { return new File(subSingleBenchmarkResult.getResultDirectory(), getCsvFileName()); } // ************************************************************************ // Lifecycle methods // ************************************************************************ public abstract void open(StatisticRegistry<Solution_> registry, Tags runTag); public void close(StatisticRegistry<Solution_> registry, Tags runTag) { // Empty by default; SubSingleBenchmarkRunner unregisters the Registry (and thus the listeners) } // ************************************************************************ // Write methods // ************************************************************************ public void initPointList() { pointList = new ArrayList<>(); } protected abstract String getCsvHeader(); private void writeCsvStatisticFile() { File csvFile = getCsvFile(); try (BufferedWriter writer = Files.newBufferedWriter(csvFile.toPath(), StandardCharsets.UTF_8)) { writer.append(getCsvHeader()); writer.newLine(); for (StatisticPoint point : getPointList()) { writer.append(point.toCsvLine()); writer.newLine(); } if (subSingleBenchmarkResult.hasAnyFailure()) { writer.append(FAILED); writer.newLine(); } } catch (IOException e) { throw new IllegalArgumentException("Failed writing csvFile (" + csvFile + ").", e); } } private void readCsvStatisticFile() { File csvFile = getCsvFile(); ScoreDefinition<?> scoreDefinition = subSingleBenchmarkResult.getSingleBenchmarkResult().getSolverBenchmarkResult() .getScoreDefinition(); if (!pointList.isEmpty()) { throw new IllegalStateException("The pointList with size (" + pointList.size() + ") should be empty."); } if (!csvFile.exists()) { if (subSingleBenchmarkResult.hasAnyFailure()) { pointList = Collections.emptyList(); return; } else { throw new IllegalStateException("The csvFile (" + csvFile + ") does not exist."); } } try (BufferedReader reader = Files.newBufferedReader(csvFile.toPath(), StandardCharsets.UTF_8)) { String line = reader.readLine(); if (!getCsvHeader().equals(line)) { throw new IllegalStateException("The read line (" + line + ") is expected to be the header line (" + getCsvHeader() + ") for statisticType (" + getStatisticType() + ")."); } for (line = reader.readLine(); line != null && !line.isEmpty(); line = reader.readLine()) { if (line.equals(FAILED)) { if (subSingleBenchmarkResult.hasAnyFailure()) { continue; } throw new IllegalStateException("SubSingleStatistic (" + this + ") failed even though the " + "corresponding subSingleBenchmarkResult (" + subSingleBenchmarkResult + ") is a success."); } // HACK // Some statistics (such as CONSTRAINT_MATCH_TOTAL_STEP_SCORE) contain the same String many times // During generation those are all the same instance to save memory. // During aggregation this code assures they are the same instance too List<String> csvLine = StatisticPoint.parseCsvLine(line) .stream() .map(String::intern) .collect(Collectors.toList()); pointList.add(createPointFromCsvLine(scoreDefinition, csvLine)); } } catch (IOException e) { throw new IllegalArgumentException("Failed reading csvFile (" + csvFile + ").", e); } } public void unhibernatePointList() { if (!getCsvFile().exists()) { throw new IllegalStateException("The csvFile (" + getCsvFile() + ") of the statistic (" + getStatisticType() + ") of the single benchmark (" + subSingleBenchmarkResult + ") doesn't exist."); } else if (pointList != null) { throw new IllegalStateException("The pointList (" + pointList + ") of the statistic (" + getStatisticType() + ") of the single benchmark (" + subSingleBenchmarkResult + ") should be null when unhibernating."); } initPointList(); readCsvStatisticFile(); } public void hibernatePointList() { writeCsvStatisticFile(); pointList = null; } protected abstract StatisticPoint_ createPointFromCsvLine(ScoreDefinition<?> scoreDefinition, List<String> csvLine); // ************************************************************************ // Report accumulates // ************************************************************************ @SuppressWarnings("unused") // Used by FreeMarker. public String getAnchorId() { return ReportHelper.escapeHtmlId(subSingleBenchmarkResult.getName() + "_" + getStatisticType().name()); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/bestscore/BestScoreProblemStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.bestscore; import java.util.ArrayList; import java.util.List; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.LineChart; import ai.timefold.solver.benchmark.impl.result.ProblemBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.SubSingleStatistic; public class BestScoreProblemStatistic extends ProblemStatistic<LineChart<Long, Double>> { private BestScoreProblemStatistic() { // Required by JAXB } public BestScoreProblemStatistic(ProblemBenchmarkResult problemBenchmarkResult) { super(problemBenchmarkResult, ProblemStatisticType.BEST_SCORE); } @Override public SubSingleStatistic createSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { return new BestScoreSubSingleStatistic<>(subSingleBenchmarkResult); } @Override protected List<LineChart<Long, Double>> generateCharts(BenchmarkReport benchmarkReport) { var builderList = new ArrayList<LineChart.Builder<Long, Double>>(BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE); for (var singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) { // No direct ascending lines between 2 points, but a stepping line instead if (singleBenchmarkResult.hasAllSuccess()) { var solverLabel = singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix(); var subSingleStatistic = singleBenchmarkResult.getSubSingleStatistic(problemStatisticType); List<BestScoreStatisticPoint> points = subSingleStatistic.getPointList(); for (var point : points) { if (!point.isInitialized()) { continue; } var timeMillisSpent = point.getTimeMillisSpent(); var levelValues = point.getScore().toLevelDoubles(); for (var i = 0; i < levelValues.length && i < BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE; i++) { if (i >= builderList.size()) { builderList.add(new LineChart.Builder<>()); } var builder = builderList.get(i); if (singleBenchmarkResult.getSolverBenchmarkResult().isFavorite()) { builder.markFavorite(solverLabel); } builder.add(solverLabel, timeMillisSpent, levelValues[i]); } } // TODO if startingSolution is initialized and no improvement is made, a horizontal line should be shown // Draw a horizontal line from the last new best step to how long the solver actually ran var timeMillisSpent = singleBenchmarkResult.getTimeMillisSpent(); var bestScoreLevels = singleBenchmarkResult.getMedian().getScore().toLevelDoubles(); for (var i = 0; i < bestScoreLevels.length && i < BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE; i++) { if (i >= builderList.size()) { builderList.add(new LineChart.Builder<>()); } var builder = builderList.get(i); if (singleBenchmarkResult.getSolverBenchmarkResult().isFavorite()) { builder.markFavorite(solverLabel); } builder.add(solverLabel, timeMillisSpent, bestScoreLevels[i]); } } } var chartList = new ArrayList<LineChart<Long, Double>>(builderList.size()); for (var scoreLevelIndex = 0; scoreLevelIndex < builderList.size(); scoreLevelIndex++) { var scoreLevelLabel = problemBenchmarkResult.findScoreLevelLabel(scoreLevelIndex); var builder = builderList.get(scoreLevelIndex); var chart = builder.build("bestScoreProblemStatisticChart" + scoreLevelIndex, problemBenchmarkResult.getName() + " best " + scoreLevelLabel + " statistic", "Time spent", "Best " + scoreLevelLabel, true, true, false); chartList.add(chart); } return chartList; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/bestscore/BestScoreStatisticPoint.java
package ai.timefold.solver.benchmark.impl.statistic.bestscore; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; import ai.timefold.solver.core.api.score.Score; public class BestScoreStatisticPoint extends StatisticPoint { private final long timeMillisSpent; private final Score score; private final boolean isInitialized; public BestScoreStatisticPoint(long timeMillisSpent, Score score, boolean isInitialized) { this.timeMillisSpent = timeMillisSpent; this.score = score; this.isInitialized = isInitialized; } public long getTimeMillisSpent() { return timeMillisSpent; } public Score getScore() { return score; } public boolean isInitialized() { return isInitialized; } @Override public String toCsvLine() { return buildCsvLineWithStrings(timeMillisSpent, score.toString(), isInitialized ? "true" : "false"); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/bestscore/BestScoreSubSingleStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.bestscore; import java.util.List; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemBasedSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; import ai.timefold.solver.benchmark.impl.statistic.StatisticRegistry; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import io.micrometer.core.instrument.Tags; public class BestScoreSubSingleStatistic<Solution_> extends ProblemBasedSubSingleStatistic<Solution_, BestScoreStatisticPoint> { BestScoreSubSingleStatistic() { // For JAXB. } public BestScoreSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { super(subSingleBenchmarkResult, ProblemStatisticType.BEST_SCORE); } // ************************************************************************ // Lifecycle methods // ************************************************************************ @Override public void open(StatisticRegistry<Solution_> registry, Tags runTag) { registry.addListener(SolverMetric.BEST_SCORE, timestamp -> registry.extractScoreFromMeters(SolverMetric.BEST_SCORE, runTag, score -> pointList .add(new BestScoreStatisticPoint(timestamp, score.raw(), score.isFullyAssigned())))); } // ************************************************************************ // CSV methods // ************************************************************************ @Override protected String getCsvHeader() { return StatisticPoint.buildCsvLine("timeMillisSpent", "score", "initialized"); } @Override protected BestScoreStatisticPoint createPointFromCsvLine(ScoreDefinition<?> scoreDefinition, List<String> csvLine) { return new BestScoreStatisticPoint(Long.parseLong(csvLine.get(0)), scoreDefinition.parseScore(csvLine.get(1)), Boolean.parseBoolean(csvLine.get(2))); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/bestsolutionmutation/BestSolutionMutationProblemStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.bestsolutionmutation; import static java.util.Collections.singletonList; import java.util.List; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.LineChart; import ai.timefold.solver.benchmark.impl.result.ProblemBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.SubSingleStatistic; public class BestSolutionMutationProblemStatistic extends ProblemStatistic<LineChart<Long, Long>> { private BestSolutionMutationProblemStatistic() { // For JAXB. } public BestSolutionMutationProblemStatistic(ProblemBenchmarkResult problemBenchmarkResult) { super(problemBenchmarkResult, ProblemStatisticType.BEST_SOLUTION_MUTATION); } @Override public SubSingleStatistic createSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { return new BestSolutionMutationSubSingleStatistic(subSingleBenchmarkResult); } @Override protected List<LineChart<Long, Long>> generateCharts(BenchmarkReport benchmarkReport) { LineChart.Builder<Long, Long> builder = new LineChart.Builder<>(); for (SingleBenchmarkResult singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) { String solverLabel = singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix(); if (singleBenchmarkResult.getSolverBenchmarkResult().isFavorite()) { builder.markFavorite(solverLabel); } if (singleBenchmarkResult.hasAllSuccess()) { var subSingleStatistic = singleBenchmarkResult.getSubSingleStatistic(problemStatisticType); List<BestSolutionMutationStatisticPoint> points = subSingleStatistic.getPointList(); for (BestSolutionMutationStatisticPoint point : points) { long timeMillisSpent = point.getTimeMillisSpent(); long mutationCount = point.getMutationCount(); builder.add(solverLabel, timeMillisSpent, mutationCount); builder.add(solverLabel, timeMillisSpent + 1, 0L); // Drop back to zero. } } } return singletonList(builder.build("bestSolutionMutationProblemStatisticChart", problemBenchmarkResult.getName() + " best solution mutation statistic", "Time spent", "Best solution mutation count", true, true, false)); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/bestsolutionmutation/BestSolutionMutationStatisticPoint.java
package ai.timefold.solver.benchmark.impl.statistic.bestsolutionmutation; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; public class BestSolutionMutationStatisticPoint extends StatisticPoint { private final long timeMillisSpent; private final int mutationCount; public BestSolutionMutationStatisticPoint(long timeMillisSpent, int mutationCount) { this.timeMillisSpent = timeMillisSpent; this.mutationCount = mutationCount; } public long getTimeMillisSpent() { return timeMillisSpent; } public int getMutationCount() { return mutationCount; } @Override public String toCsvLine() { return buildCsvLineWithLongs(timeMillisSpent, mutationCount); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/bestsolutionmutation/BestSolutionMutationSubSingleStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.bestsolutionmutation; import java.util.List; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemBasedSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; import ai.timefold.solver.benchmark.impl.statistic.StatisticRegistry; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import ai.timefold.solver.core.impl.solver.monitoring.SolverMetricUtil; import io.micrometer.core.instrument.Tags; public class BestSolutionMutationSubSingleStatistic<Solution_> extends ProblemBasedSubSingleStatistic<Solution_, BestSolutionMutationStatisticPoint> { private BestSolutionMutationSubSingleStatistic() { // For JAXB. } public BestSolutionMutationSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { super(subSingleBenchmarkResult, ProblemStatisticType.BEST_SOLUTION_MUTATION); } // ************************************************************************ // Lifecycle methods // ************************************************************************ @Override public void open(StatisticRegistry<Solution_> registry, Tags runTag) { registry.addListener(SolverMetric.BEST_SOLUTION_MUTATION, timestamp -> { var mutationCount = SolverMetricUtil.getGaugeValue(registry, SolverMetric.BEST_SOLUTION_MUTATION, runTag); if (mutationCount != null) { pointList.add(new BestSolutionMutationStatisticPoint(timestamp, mutationCount.intValue())); } }); } // ************************************************************************ // CSV methods // ************************************************************************ @Override protected String getCsvHeader() { return StatisticPoint.buildCsvLine("timeMillisSpent", "mutationCount"); } @Override protected BestSolutionMutationStatisticPoint createPointFromCsvLine(ScoreDefinition<?> scoreDefinition, List<String> csvLine) { return new BestSolutionMutationStatisticPoint(Long.parseLong(csvLine.get(0)), Integer.parseInt(csvLine.get(1))); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/common/AbstractCalculationSpeedSubSingleStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.common; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemBasedSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.StatisticRegistry; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import ai.timefold.solver.core.impl.solver.monitoring.SolverMetricUtil; import io.micrometer.core.instrument.Tags; public abstract class AbstractCalculationSpeedSubSingleStatistic<Solution_> extends ProblemBasedSubSingleStatistic<Solution_, LongStatisticPoint> { private final SolverMetric solverMetric; private final long timeMillisThresholdInterval; protected AbstractCalculationSpeedSubSingleStatistic(SolverMetric solverMetric, ProblemStatisticType statisticType, SubSingleBenchmarkResult benchmarkResult, long timeMillisThresholdInterval) { super(benchmarkResult, statisticType); if (timeMillisThresholdInterval <= 0L) { throw new IllegalArgumentException("The timeMillisThresholdInterval (" + timeMillisThresholdInterval + ") must be bigger than 0."); } this.solverMetric = solverMetric; this.timeMillisThresholdInterval = timeMillisThresholdInterval; } // ************************************************************************ // Lifecycle methods // ************************************************************************ @Override public void open(StatisticRegistry<Solution_> registry, Tags runTag) { registry.addListener(solverMetric, new Consumer<>() { long nextTimeMillisThreshold = timeMillisThresholdInterval; long lastTimeMillisSpent = 0L; final AtomicLong lastCalculationCount = new AtomicLong(0); @Override public void accept(Long timeMillisSpent) { if (timeMillisSpent >= nextTimeMillisThreshold) { var countNumber = SolverMetricUtil.getGaugeValue(registry, solverMetric, runTag); if (countNumber != null) { var moveEvaluationCount = countNumber.longValue(); var countInterval = moveEvaluationCount - lastCalculationCount.get(); var timeMillisSpentInterval = timeMillisSpent - lastTimeMillisSpent; if (timeMillisSpentInterval == 0L) { // Avoid divide by zero exception on a fast CPU timeMillisSpentInterval = 1L; } var speed = countInterval * 1000L / timeMillisSpentInterval; pointList.add(new LongStatisticPoint(timeMillisSpent, speed)); lastCalculationCount.set(moveEvaluationCount); } lastTimeMillisSpent = timeMillisSpent; nextTimeMillisThreshold += timeMillisThresholdInterval; if (nextTimeMillisThreshold < timeMillisSpent) { nextTimeMillisThreshold = timeMillisSpent; } } } }); } // ************************************************************************ // CSV methods // ************************************************************************ @Override protected LongStatisticPoint createPointFromCsvLine(ScoreDefinition<?> scoreDefinition, List<String> csvLine) { return new LongStatisticPoint(Long.parseLong(csvLine.get(0)), Long.parseLong(csvLine.get(1))); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/common/AbstractTimeLineChartProblemStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.common; import static java.util.Collections.singletonList; import java.util.List; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.LineChart; import ai.timefold.solver.benchmark.impl.result.ProblemBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemStatistic; public abstract class AbstractTimeLineChartProblemStatistic extends ProblemStatistic<LineChart<Long, Long>> { private String reportFileName; private String reportTitle; private String yLabel; private ProblemStatisticType statisticType; protected AbstractTimeLineChartProblemStatistic(ProblemStatisticType statisticType) { super(null, statisticType); this.statisticType = statisticType; } protected AbstractTimeLineChartProblemStatistic(ProblemStatisticType statisticType, ProblemBenchmarkResult<?> problemBenchmarkResult, String reportFileName, String reportTitle, String yLabel) { super(problemBenchmarkResult, statisticType); this.statisticType = statisticType; this.reportFileName = reportFileName; this.reportTitle = reportTitle; this.yLabel = yLabel; } /** * @return never null */ @Override protected List<LineChart<Long, Long>> generateCharts(BenchmarkReport benchmarkReport) { var builder = new LineChart.Builder<Long, Long>(); for (var singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) { var solverLabel = singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix(); if (singleBenchmarkResult.hasAllSuccess()) { var subSingleStatistic = singleBenchmarkResult.getSubSingleStatistic(problemStatisticType); List<LongStatisticPoint> points = subSingleStatistic.getPointList(); for (var point : points) { var timeMillisSpent = point.getTimeMillisSpent(); var calculationSpeed = point.getValue(); builder.add(solverLabel, timeMillisSpent, calculationSpeed); } } if (singleBenchmarkResult.getSolverBenchmarkResult().isFavorite()) { builder.markFavorite(solverLabel); } } return singletonList(builder.build(reportFileName, reportTitle, "Time spent", yLabel, false, true, false)); } public void setReportFileName(String reportFileName) { this.reportFileName = reportFileName; } public void setReportTitle(String reportTitle) { this.reportTitle = reportTitle; } public void setyLabel(String yLabel) { this.yLabel = yLabel; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/common/LongStatisticPoint.java
package ai.timefold.solver.benchmark.impl.statistic.common; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; public class LongStatisticPoint extends StatisticPoint { private final long timeMillisSpent; private final long value; public LongStatisticPoint(long timeMillisSpent, long value) { this.timeMillisSpent = timeMillisSpent; this.value = value; } public long getTimeMillisSpent() { return timeMillisSpent; } public long getValue() { return value; } @Override public String toCsvLine() { return buildCsvLineWithLongs(timeMillisSpent, value); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/common/MillisecondsSpentNumberFormat.java
package ai.timefold.solver.benchmark.impl.statistic.common; import java.text.FieldPosition; import java.text.NumberFormat; import java.text.ParsePosition; import java.util.Locale; import ai.timefold.solver.benchmark.impl.report.MillisecondDurationNumberFormatFactory; public final class MillisecondsSpentNumberFormat extends NumberFormat { private final Locale locale; public MillisecondsSpentNumberFormat(Locale locale) { this.locale = locale; } @Override public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) { return format((long) number, toAppendTo, pos); } @Override public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) { return toAppendTo.append(MillisecondDurationNumberFormatFactory.formatMillis(locale, number)); } @Override public Number parse(String source, ParsePosition parsePosition) { throw new UnsupportedOperationException(); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/memoryuse/MemoryUseProblemStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.memoryuse; import static java.util.Collections.singletonList; import java.util.Collections; import java.util.List; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.LineChart; import ai.timefold.solver.benchmark.impl.result.ProblemBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.SubSingleStatistic; public class MemoryUseProblemStatistic extends ProblemStatistic<LineChart<Long, Long>> { private MemoryUseProblemStatistic() { // For JAXB. } public MemoryUseProblemStatistic(ProblemBenchmarkResult problemBenchmarkResult) { super(problemBenchmarkResult, ProblemStatisticType.MEMORY_USE); } @Override public SubSingleStatistic createSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { return new MemoryUseSubSingleStatistic(subSingleBenchmarkResult); } @Override public List<String> getWarningList() { if (problemBenchmarkResult.getPlannerBenchmarkResult().hasMultipleParallelBenchmarks()) { return Collections.singletonList("This memory use statistic shows the sum of the memory of all benchmarks " + "that ran in parallel, due to parallelBenchmarkCount (" + problemBenchmarkResult.getPlannerBenchmarkResult().getParallelBenchmarkCount() + ")."); } else { return Collections.emptyList(); } } @Override protected List<LineChart<Long, Long>> generateCharts(BenchmarkReport benchmarkReport) { LineChart.Builder<Long, Long> builder = new LineChart.Builder<>(); for (SingleBenchmarkResult singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) { String solverLabel = singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix(); if (singleBenchmarkResult.getSolverBenchmarkResult().isFavorite()) { builder.markFavorite(solverLabel); } if (singleBenchmarkResult.hasAllSuccess()) { var subSingleStatistic = singleBenchmarkResult.getSubSingleStatistic(problemStatisticType); List<MemoryUseStatisticPoint> points = subSingleStatistic.getPointList(); for (MemoryUseStatisticPoint point : points) { long timeMillisSpent = point.getTimeMillisSpent(); builder.add(solverLabel, timeMillisSpent, point.getUsedMemory() / 1024 / 1024); } } } return singletonList(builder.build("memoryUseProblemStatisticChart", problemBenchmarkResult.getName() + " memory use statistic", "Time spent", "Memory (MiB)", false, true, false)); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/memoryuse/MemoryUseStatisticPoint.java
package ai.timefold.solver.benchmark.impl.statistic.memoryuse; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; public class MemoryUseStatisticPoint extends StatisticPoint { public static MemoryUseStatisticPoint create(long timeMillisSpent) { Runtime runtime = Runtime.getRuntime(); return new MemoryUseStatisticPoint(timeMillisSpent, runtime.totalMemory() - runtime.freeMemory(), runtime.maxMemory()); } private final long timeMillisSpent; private final long usedMemory; private final long maxMemory; public MemoryUseStatisticPoint(long timeMillisSpent, long usedMemory, long maxMemory) { this.timeMillisSpent = timeMillisSpent; this.usedMemory = usedMemory; this.maxMemory = maxMemory; } public long getTimeMillisSpent() { return timeMillisSpent; } public long getUsedMemory() { return usedMemory; } public long getMaxMemory() { return maxMemory; } @Override public String toCsvLine() { return buildCsvLineWithLongs(timeMillisSpent, usedMemory, maxMemory); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/memoryuse/MemoryUseSubSingleStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.memoryuse; import java.util.List; import java.util.function.Consumer; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemBasedSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; import ai.timefold.solver.benchmark.impl.statistic.StatisticRegistry; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import ai.timefold.solver.core.impl.solver.monitoring.SolverMetricUtil; import io.micrometer.core.instrument.Tags; public class MemoryUseSubSingleStatistic<Solution_> extends ProblemBasedSubSingleStatistic<Solution_, MemoryUseStatisticPoint> { private long timeMillisThresholdInterval; private MemoryUseSubSingleStatistic() { // For JAXB. } public MemoryUseSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { this(subSingleBenchmarkResult, 1000L); } public MemoryUseSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult, long timeMillisThresholdInterval) { super(subSingleBenchmarkResult, ProblemStatisticType.MEMORY_USE); if (timeMillisThresholdInterval <= 0L) { throw new IllegalArgumentException("The timeMillisThresholdInterval (" + timeMillisThresholdInterval + ") must be bigger than 0."); } this.timeMillisThresholdInterval = timeMillisThresholdInterval; } // ************************************************************************ // Lifecycle methods // ************************************************************************ @Override public void open(StatisticRegistry<Solution_> registry, Tags runTag) { registry.addListener(SolverMetric.MEMORY_USE, new MemoryUseSubSingleStatisticListener(registry, runTag)); } private class MemoryUseSubSingleStatisticListener implements Consumer<Long> { private long nextTimeMillisThreshold = timeMillisThresholdInterval; private final StatisticRegistry<?> registry; private final Tags tags; public MemoryUseSubSingleStatisticListener(StatisticRegistry<?> registry, Tags tags) { this.registry = registry; this.tags = tags; } @Override public void accept(Long timeMillisSpent) { if (timeMillisSpent >= nextTimeMillisThreshold) { var memoryUse = SolverMetricUtil.getGaugeValue(registry, SolverMetric.MEMORY_USE, tags); if (memoryUse != null) { var max = SolverMetricUtil.getGaugeValue(registry, "jvm.memory.max", tags); pointList.add(new MemoryUseStatisticPoint(timeMillisSpent, memoryUse.longValue(), max.longValue())); } nextTimeMillisThreshold += timeMillisThresholdInterval; if (nextTimeMillisThreshold < timeMillisSpent) { nextTimeMillisThreshold = timeMillisSpent; } } } } // ************************************************************************ // CSV methods // ************************************************************************ @Override protected String getCsvHeader() { return StatisticPoint.buildCsvLine("timeMillisSpent", "usedMemory", "maxMemory"); } @Override protected MemoryUseStatisticPoint createPointFromCsvLine(ScoreDefinition<?> scoreDefinition, List<String> csvLine) { return new MemoryUseStatisticPoint(Long.parseLong(csvLine.get(0)), Long.parseLong(csvLine.get(1)), Long.parseLong(csvLine.get(2))); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/movecountperstep/MoveCountPerStepProblemStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.movecountperstep; import static java.util.Collections.singletonList; import java.util.List; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.LineChart; import ai.timefold.solver.benchmark.impl.result.ProblemBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.SubSingleStatistic; public class MoveCountPerStepProblemStatistic extends ProblemStatistic<LineChart<Long, Long>> { private MoveCountPerStepProblemStatistic() { // For JAXB. } public MoveCountPerStepProblemStatistic(ProblemBenchmarkResult problemBenchmarkResult) { super(problemBenchmarkResult, ProblemStatisticType.MOVE_COUNT_PER_STEP); } @Override public SubSingleStatistic createSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { return new MoveCountPerStepSubSingleStatistic(subSingleBenchmarkResult); } @Override protected List<LineChart<Long, Long>> generateCharts(BenchmarkReport benchmarkReport) { LineChart.Builder<Long, Long> builder = new LineChart.Builder<>(); for (SingleBenchmarkResult singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) { String acceptedSeriesLabel = singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix() + " accepted"; String selectedSeriesLabel = singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix() + " selected"; if (singleBenchmarkResult.hasAllSuccess()) { var subSingleStatistic = singleBenchmarkResult.getSubSingleStatistic(problemStatisticType); List<MoveCountPerStepStatisticPoint> list = subSingleStatistic.getPointList(); for (MoveCountPerStepStatisticPoint point : list) { long timeMillisSpent = point.getTimeMillisSpent(); builder.add(acceptedSeriesLabel, timeMillisSpent, point.getAcceptedMoveCount()); builder.add(selectedSeriesLabel, timeMillisSpent, point.getSelectedMoveCount()); } } if (singleBenchmarkResult.getSolverBenchmarkResult().isFavorite()) { builder.markFavorite(acceptedSeriesLabel); builder.markFavorite(selectedSeriesLabel); } } return singletonList(builder.build("moveCountPerStepProblemStatisticChart", problemBenchmarkResult.getName() + " move count per step statistic", "Time spent", "Moves per step", true, true, false)); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/movecountperstep/MoveCountPerStepStatisticPoint.java
package ai.timefold.solver.benchmark.impl.statistic.movecountperstep; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; public class MoveCountPerStepStatisticPoint extends StatisticPoint { private final long timeMillisSpent; private final long acceptedMoveCount; private final long selectedMoveCount; public MoveCountPerStepStatisticPoint(long timeMillisSpent, long acceptedMoveCount, long selectedMoveCount) { this.timeMillisSpent = timeMillisSpent; this.acceptedMoveCount = acceptedMoveCount; this.selectedMoveCount = selectedMoveCount; } public long getTimeMillisSpent() { return timeMillisSpent; } public long getAcceptedMoveCount() { return acceptedMoveCount; } public long getSelectedMoveCount() { return selectedMoveCount; } @Override public String toCsvLine() { return buildCsvLineWithLongs(timeMillisSpent, acceptedMoveCount, selectedMoveCount); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/movecountperstep/MoveCountPerStepSubSingleStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.movecountperstep; import java.util.List; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemBasedSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; import ai.timefold.solver.benchmark.impl.statistic.StatisticRegistry; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import ai.timefold.solver.core.impl.solver.monitoring.SolverMetricUtil; import io.micrometer.core.instrument.Tags; public class MoveCountPerStepSubSingleStatistic<Solution_> extends ProblemBasedSubSingleStatistic<Solution_, MoveCountPerStepStatisticPoint> { private MoveCountPerStepSubSingleStatistic() { // For JAXB. } public MoveCountPerStepSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { super(subSingleBenchmarkResult, ProblemStatisticType.MOVE_COUNT_PER_STEP); } // ************************************************************************ // Lifecycle methods // ************************************************************************ @Override public void open(StatisticRegistry<Solution_> registry, Tags runTag) { registry.addListener(SolverMetric.MOVE_COUNT_PER_STEP, timeMillisSpent -> { var accepted = SolverMetricUtil.getGaugeValue(registry, SolverMetric.MOVE_COUNT_PER_STEP.getMeterId() + ".accepted", runTag); if (accepted != null) { var selected = SolverMetricUtil.getGaugeValue(registry, SolverMetric.MOVE_COUNT_PER_STEP.getMeterId() + ".selected", runTag); if (selected != null) { pointList.add(new MoveCountPerStepStatisticPoint(timeMillisSpent, accepted.longValue(), selected.longValue())); } } }); } // ************************************************************************ // CSV methods // ************************************************************************ @Override protected String getCsvHeader() { return StatisticPoint.buildCsvLine("timeMillisSpent", "acceptedMoveCount", "selectedMoveCount"); } @Override protected MoveCountPerStepStatisticPoint createPointFromCsvLine(ScoreDefinition<?> scoreDefinition, List<String> csvLine) { return new MoveCountPerStepStatisticPoint(Long.parseLong(csvLine.get(0)), Long.parseLong(csvLine.get(1)), Long.parseLong(csvLine.get(2))); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/movecountpertype/MoveCountPerTypeProblemStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.movecountpertype; import static java.util.Collections.singletonList; import java.util.List; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.report.BarChart; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.result.ProblemBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.SubSingleStatistic; public class MoveCountPerTypeProblemStatistic extends ProblemStatistic<BarChart<Long>> { private MoveCountPerTypeProblemStatistic() { // Required by JAXB } @SuppressWarnings("rawtypes") public MoveCountPerTypeProblemStatistic(ProblemBenchmarkResult problemBenchmarkResult) { super(problemBenchmarkResult, ProblemStatisticType.MOVE_COUNT_PER_TYPE); } @SuppressWarnings({ "rawtypes" }) @Override public SubSingleStatistic createSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { return new MoveCountPerTypeSubSingleStatistic(subSingleBenchmarkResult); } @Override protected List<BarChart<Long>> generateCharts(BenchmarkReport benchmarkReport) { var builder = new BarChart.Builder<Long>(); for (var singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) { // No direct ascending lines between 2 points, but a stepping line instead if (singleBenchmarkResult.hasAllSuccess()) { var solverLabel = singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix(); var subSingleStatistic = singleBenchmarkResult.getSubSingleStatistic(problemStatisticType); List<MoveCountPerTypeStatisticPoint> points = subSingleStatistic.getPointList(); for (var point : points) { builder.add(solverLabel, point.getMoveType(), point.getCount()); } } } return singletonList(builder.build("moveCountPerTypeProblemStatisticChart", problemBenchmarkResult.getName() + " move count per type statistic", "Type", "Count", false)); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/movecountpertype/MoveCountPerTypeStatisticPoint.java
package ai.timefold.solver.benchmark.impl.statistic.movecountpertype; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; public class MoveCountPerTypeStatisticPoint extends StatisticPoint { private final String moveType; private final long count; public MoveCountPerTypeStatisticPoint(String moveType, long count) { this.moveType = moveType; this.count = count; } public String getMoveType() { return moveType; } public long getCount() { return count; } @Override public String toCsvLine() { return buildCsvLineWithStrings(0L, moveType, String.valueOf(count)); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/movecountpertype/MoveCountPerTypeSubSingleStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.movecountpertype; import java.util.List; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemBasedSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; import ai.timefold.solver.benchmark.impl.statistic.StatisticRegistry; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import io.micrometer.core.instrument.Tags; public class MoveCountPerTypeSubSingleStatistic<Solution_> extends ProblemBasedSubSingleStatistic<Solution_, MoveCountPerTypeStatisticPoint> { MoveCountPerTypeSubSingleStatistic() { // For JAXB. } public MoveCountPerTypeSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { super(subSingleBenchmarkResult, ProblemStatisticType.MOVE_COUNT_PER_TYPE); } // ************************************************************************ // Lifecycle methods // ************************************************************************ @Override public void open(StatisticRegistry<Solution_> registry, Tags runTag) { registry.addListener(solverScope -> registry.extractMoveCountPerType(solverScope, (type, count) -> pointList.add(new MoveCountPerTypeStatisticPoint(type, count)))); } // ************************************************************************ // CSV methods // ************************************************************************ @Override protected String getCsvHeader() { return StatisticPoint.buildCsvLine("_", "type", "count"); } @Override protected MoveCountPerTypeStatisticPoint createPointFromCsvLine(ScoreDefinition<?> scoreDefinition, List<String> csvLine) { return new MoveCountPerTypeStatisticPoint(csvLine.get(1), Long.parseLong(csvLine.get(2))); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/moveevaluationspeed/MoveEvaluationSpeedProblemStatisticTime.java
package ai.timefold.solver.benchmark.impl.statistic.moveevaluationspeed; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.result.ProblemBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.SubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.common.AbstractTimeLineChartProblemStatistic; public class MoveEvaluationSpeedProblemStatisticTime extends AbstractTimeLineChartProblemStatistic { protected MoveEvaluationSpeedProblemStatisticTime() { super(ProblemStatisticType.MOVE_EVALUATION_SPEED); } public MoveEvaluationSpeedProblemStatisticTime(ProblemBenchmarkResult<?> problemBenchmarkResult) { super(ProblemStatisticType.MOVE_EVALUATION_SPEED, problemBenchmarkResult, "moveEvaluationSpeedProblemStatisticChart", problemBenchmarkResult.getName() + " move evaluation speed statistic", "Move evaluation speed per second"); } @Override public SubSingleStatistic<?, ?> createSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { return new MoveEvaluationSpeedSubSingleStatistic<>(subSingleBenchmarkResult); } @Override public void setProblemBenchmarkResult(ProblemBenchmarkResult problemBenchmarkResult) { super.setProblemBenchmarkResult(problemBenchmarkResult); this.setyLabel("Move evaluation speed per second"); this.setReportTitle(problemBenchmarkResult.getName() + " move evaluation speed statistic"); this.setReportFileName("moveEvaluationSpeedProblemStatisticChart"); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/moveevaluationspeed/MoveEvaluationSpeedSubSingleStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.moveevaluationspeed; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; import ai.timefold.solver.benchmark.impl.statistic.common.AbstractCalculationSpeedSubSingleStatistic; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; public class MoveEvaluationSpeedSubSingleStatistic<Solution_> extends AbstractCalculationSpeedSubSingleStatistic<Solution_> { private MoveEvaluationSpeedSubSingleStatistic() { // For JAXB. this(null); } public MoveEvaluationSpeedSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { this(subSingleBenchmarkResult, 1000L); } public MoveEvaluationSpeedSubSingleStatistic(SubSingleBenchmarkResult benchmarkResult, long timeMillisThresholdInterval) { super(SolverMetric.MOVE_EVALUATION_COUNT, ProblemStatisticType.MOVE_EVALUATION_SPEED, benchmarkResult, timeMillisThresholdInterval); } // ************************************************************************ // CSV methods // ************************************************************************ @Override protected String getCsvHeader() { return StatisticPoint.buildCsvLine("timeMillisSpent", "moveEvaluationSpeed"); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/scorecalculationspeed/ScoreCalculationSpeedProblemStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.scorecalculationspeed; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.result.ProblemBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.SubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.common.AbstractTimeLineChartProblemStatistic; public class ScoreCalculationSpeedProblemStatistic extends AbstractTimeLineChartProblemStatistic { protected ScoreCalculationSpeedProblemStatistic() { super(ProblemStatisticType.SCORE_CALCULATION_SPEED); } public ScoreCalculationSpeedProblemStatistic(ProblemBenchmarkResult problemBenchmarkResult) { super(ProblemStatisticType.SCORE_CALCULATION_SPEED, problemBenchmarkResult, "scoreCalculationSpeedProblemStatisticChart", problemBenchmarkResult.getName() + " score calculation speed statistic", "Score calculation speed per second"); } @Override public SubSingleStatistic createSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { return new ScoreCalculationSpeedSubSingleStatistic(subSingleBenchmarkResult); } @Override public void setProblemBenchmarkResult(ProblemBenchmarkResult problemBenchmarkResult) { super.setProblemBenchmarkResult(problemBenchmarkResult); this.setyLabel("Score calculation speed per second"); this.setReportTitle(problemBenchmarkResult.getName() + " score calculation speed statistic"); this.setReportFileName("scoreCalculationSpeedProblemStatisticChart"); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/scorecalculationspeed/ScoreCalculationSpeedSubSingleStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.scorecalculationspeed; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; import ai.timefold.solver.benchmark.impl.statistic.common.AbstractCalculationSpeedSubSingleStatistic; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; public class ScoreCalculationSpeedSubSingleStatistic<Solution_> extends AbstractCalculationSpeedSubSingleStatistic<Solution_> { private ScoreCalculationSpeedSubSingleStatistic() { // For JAXB. this(null); } public ScoreCalculationSpeedSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { this(subSingleBenchmarkResult, 1000L); } public ScoreCalculationSpeedSubSingleStatistic(SubSingleBenchmarkResult benchmarkResult, long timeMillisThresholdInterval) { super(SolverMetric.SCORE_CALCULATION_COUNT, ProblemStatisticType.SCORE_CALCULATION_SPEED, benchmarkResult, timeMillisThresholdInterval); } // ************************************************************************ // CSV methods // ************************************************************************ @Override protected String getCsvHeader() { return StatisticPoint.buildCsvLine("timeMillisSpent", "scoreCalculationSpeed"); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/stepscore/StepScoreProblemStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.stepscore; import java.util.ArrayList; import java.util.List; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.LineChart; import ai.timefold.solver.benchmark.impl.result.ProblemBenchmarkResult; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemStatistic; import ai.timefold.solver.benchmark.impl.statistic.SubSingleStatistic; public class StepScoreProblemStatistic extends ProblemStatistic<LineChart<Long, Double>> { private StepScoreProblemStatistic() { // For JAXB. } public StepScoreProblemStatistic(ProblemBenchmarkResult problemBenchmarkResult) { super(problemBenchmarkResult, ProblemStatisticType.STEP_SCORE); } @Override public SubSingleStatistic createSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { return new StepScoreSubSingleStatistic(subSingleBenchmarkResult); } @Override protected List<LineChart<Long, Double>> generateCharts(BenchmarkReport benchmarkReport) { var builderList = new ArrayList<LineChart.Builder<Long, Double>>(BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE); for (var singleBenchmarkResult : problemBenchmarkResult.getSingleBenchmarkResultList()) { var solverLabel = singleBenchmarkResult.getSolverBenchmarkResult().getNameWithFavoriteSuffix(); // No direct ascending lines between 2 points, but a stepping line instead if (singleBenchmarkResult.hasAllSuccess()) { var subSingleStatistic = singleBenchmarkResult.getSubSingleStatistic(problemStatisticType); List<StepScoreStatisticPoint> points = subSingleStatistic.getPointList(); for (var point : points) { if (!point.isInitialized()) { continue; } var timeMillisSpent = point.getTimeMillisSpent(); var levelValues = point.getScore().toLevelDoubles(); for (var i = 0; i < levelValues.length && i < BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE; i++) { if (i >= builderList.size()) { builderList.add(new LineChart.Builder<>()); } var builder = builderList.get(i); if (singleBenchmarkResult.getSolverBenchmarkResult().isFavorite()) { builder.markFavorite(solverLabel); } builder.add(solverLabel, timeMillisSpent, levelValues[i]); } } } } var chartList = new ArrayList<LineChart<Long, Double>>(BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE); for (var scoreLevelIndex = 0; scoreLevelIndex < builderList.size(); scoreLevelIndex++) { var scoreLevelLabel = problemBenchmarkResult.findScoreLevelLabel(scoreLevelIndex); var chart = builderList.get(scoreLevelIndex).build("stepScoreProblemStatisticChart" + scoreLevelIndex, problemBenchmarkResult.getName() + " step " + scoreLevelLabel + " statistic", "Time spent", "Step " + scoreLevelLabel, true, true, false); chartList.add(chart); } return chartList; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/stepscore/StepScoreStatisticPoint.java
package ai.timefold.solver.benchmark.impl.statistic.stepscore; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; import ai.timefold.solver.core.api.score.Score; public class StepScoreStatisticPoint extends StatisticPoint { private final long timeMillisSpent; private final Score score; private final boolean isInitialized; public StepScoreStatisticPoint(long timeMillisSpent, Score score, boolean isInitialized) { this.timeMillisSpent = timeMillisSpent; this.score = score; this.isInitialized = isInitialized; } public long getTimeMillisSpent() { return timeMillisSpent; } public Score getScore() { return score; } public boolean isInitialized() { return isInitialized; } @Override public String toCsvLine() { return buildCsvLineWithStrings(timeMillisSpent, score.toString(), isInitialized ? "true" : "false"); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/stepscore/StepScoreSubSingleStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.stepscore; import java.util.List; import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.ProblemBasedSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; import ai.timefold.solver.benchmark.impl.statistic.StatisticRegistry; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import io.micrometer.core.instrument.Tags; public class StepScoreSubSingleStatistic<Solution_> extends ProblemBasedSubSingleStatistic<Solution_, StepScoreStatisticPoint> { private StepScoreSubSingleStatistic() { // For JAXB. } public StepScoreSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { super(subSingleBenchmarkResult, ProblemStatisticType.STEP_SCORE); } // ************************************************************************ // Lifecycle methods // ************************************************************************ @Override public void open(StatisticRegistry<Solution_> registry, Tags runTag) { registry.addListener(SolverMetric.STEP_SCORE, timeMillisSpent -> registry.extractScoreFromMeters(SolverMetric.STEP_SCORE, runTag, score -> pointList .add(new StepScoreStatisticPoint(timeMillisSpent, score.raw(), score.isFullyAssigned())))); } // ************************************************************************ // CSV methods // ************************************************************************ @Override protected String getCsvHeader() { return StatisticPoint.buildCsvLine("timeMillisSpent", "score", "initialized"); } @Override protected StepScoreStatisticPoint createPointFromCsvLine(ScoreDefinition<?> scoreDefinition, List<String> csvLine) { return new StepScoreStatisticPoint(Long.parseLong(csvLine.get(0)), scoreDefinition.parseScore(csvLine.get(1)), Boolean.parseBoolean(csvLine.get(2))); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/subsingle
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/subsingle/constraintmatchtotalbestscore/ConstraintMatchTotalBestScoreStatisticPoint.java
package ai.timefold.solver.benchmark.impl.statistic.subsingle.constraintmatchtotalbestscore; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.constraint.ConstraintRef; public class ConstraintMatchTotalBestScoreStatisticPoint extends StatisticPoint { private final long timeMillisSpent; private final ConstraintRef constraintRef; private final int constraintMatchCount; private final Score scoreTotal; public ConstraintMatchTotalBestScoreStatisticPoint(long timeMillisSpent, ConstraintRef constraintRef, int constraintMatchCount, Score scoreTotal) { this.timeMillisSpent = timeMillisSpent; this.constraintRef = constraintRef; this.constraintMatchCount = constraintMatchCount; this.scoreTotal = scoreTotal; } public long getTimeMillisSpent() { return timeMillisSpent; } public ConstraintRef getConstraintRef() { return constraintRef; } public int getConstraintMatchCount() { return constraintMatchCount; } public Score getScoreTotal() { return scoreTotal; } @Override public String toCsvLine() { return buildCsvLineWithStrings(timeMillisSpent, constraintRef.packageName(), constraintRef.constraintName(), Integer.toString(constraintMatchCount), scoreTotal.toString()); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/subsingle
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/subsingle/constraintmatchtotalbestscore/ConstraintMatchTotalBestScoreSubSingleStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.subsingle.constraintmatchtotalbestscore; import java.util.ArrayList; import java.util.List; import ai.timefold.solver.benchmark.config.statistic.SingleStatisticType; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.LineChart; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.PureSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.StatisticRegistry; import ai.timefold.solver.core.api.score.constraint.ConstraintRef; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import io.micrometer.core.instrument.Tags; public class ConstraintMatchTotalBestScoreSubSingleStatistic<Solution_> extends PureSubSingleStatistic<Solution_, ConstraintMatchTotalBestScoreStatisticPoint, LineChart<Long, Double>> { private ConstraintMatchTotalBestScoreSubSingleStatistic() { // For JAXB. } public ConstraintMatchTotalBestScoreSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { super(subSingleBenchmarkResult, SingleStatisticType.CONSTRAINT_MATCH_TOTAL_BEST_SCORE); } @Override public void open(StatisticRegistry<Solution_> registry, Tags runTag) { registry.addListener(SolverMetric.CONSTRAINT_MATCH_TOTAL_BEST_SCORE, timeMillisSpent -> registry.extractConstraintSummariesFromMeters(SolverMetric.CONSTRAINT_MATCH_TOTAL_BEST_SCORE, runTag, constraintSummary -> pointList.add(new ConstraintMatchTotalBestScoreStatisticPoint( timeMillisSpent, constraintSummary.constraintRef(), constraintSummary.count(), constraintSummary.score())))); } @Override protected String getCsvHeader() { return ConstraintMatchTotalBestScoreStatisticPoint.buildCsvLine( "timeMillisSpent", "constraintPackage", "constraintName", "constraintMatchCount", "scoreTotal"); } @Override protected ConstraintMatchTotalBestScoreStatisticPoint createPointFromCsvLine(ScoreDefinition<?> scoreDefinition, List<String> csvLine) { return new ConstraintMatchTotalBestScoreStatisticPoint(Long.parseLong(csvLine.get(0)), ConstraintRef.of(csvLine.get(1), csvLine.get(2)), Integer.parseInt(csvLine.get(3)), scoreDefinition.parseScore(csvLine.get(4))); } @Override protected List<LineChart<Long, Double>> generateCharts(BenchmarkReport benchmarkReport) { List<LineChart.Builder<Long, Double>> builderList = new ArrayList<>(BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE); for (ConstraintMatchTotalBestScoreStatisticPoint point : getPointList()) { long timeMillisSpent = point.getTimeMillisSpent(); double[] levelValues = point.getScoreTotal().toLevelDoubles(); for (int i = 0; i < levelValues.length && i < BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE; i++) { if (i >= builderList.size()) { builderList.add(new LineChart.Builder<>()); } LineChart.Builder<Long, Double> builder = builderList.get(i); String seriesLabel = point.getConstraintRef().constraintName() + " weight"; // Only add changes double lastValue = (builder.count(seriesLabel) == 0) ? 0.0 : builder.getLastValue(seriesLabel); if (levelValues[i] != lastValue) { builder.add(seriesLabel, timeMillisSpent, levelValues[i]); } } } long timeMillisSpent = subSingleBenchmarkResult.getTimeMillisSpent(); for (LineChart.Builder<Long, Double> builder : builderList) { for (String key : builder.keys()) { // Draw a horizontal line from the last new best step to how long the solver actually ran builder.add(key, timeMillisSpent, builder.getLastValue(key)); } } List<LineChart<Long, Double>> chartList = new ArrayList<>(builderList.size()); for (int scoreLevelIndex = 0; scoreLevelIndex < builderList.size(); scoreLevelIndex++) { String scoreLevelLabel = subSingleBenchmarkResult.getSingleBenchmarkResult().getProblemBenchmarkResult() .findScoreLevelLabel(scoreLevelIndex); LineChart.Builder<Long, Double> builder = builderList.get(scoreLevelIndex); LineChart<Long, Double> chart = builder.build("constraintMatchTotalBestScoreSubSingleStatisticChart" + scoreLevelIndex, subSingleBenchmarkResult.getName() + " constraint match total best " + scoreLevelLabel + " diff statistic", "Time spent", "Constraint match total " + scoreLevelLabel, true, true, false); chartList.add(chart); } return chartList; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/subsingle
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/subsingle/constraintmatchtotalstepscore/ConstraintMatchTotalStepScoreStatisticPoint.java
package ai.timefold.solver.benchmark.impl.statistic.subsingle.constraintmatchtotalstepscore; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.api.score.constraint.ConstraintRef; public class ConstraintMatchTotalStepScoreStatisticPoint extends StatisticPoint { private final long timeMillisSpent; private final ConstraintRef constraintRef; private final int constraintMatchCount; private final Score scoreTotal; public ConstraintMatchTotalStepScoreStatisticPoint(long timeMillisSpent, ConstraintRef constraintRef, int constraintMatchCount, Score scoreTotal) { this.timeMillisSpent = timeMillisSpent; this.constraintRef = constraintRef; this.constraintMatchCount = constraintMatchCount; this.scoreTotal = scoreTotal; } public long getTimeMillisSpent() { return timeMillisSpent; } public ConstraintRef getConstraintRef() { return constraintRef; } public int getConstraintMatchCount() { return constraintMatchCount; } public Score getScoreTotal() { return scoreTotal; } @Override public String toCsvLine() { return buildCsvLineWithStrings(timeMillisSpent, constraintRef.packageName(), constraintRef.constraintName(), Integer.toString(constraintMatchCount), scoreTotal.toString()); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/subsingle
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/subsingle/constraintmatchtotalstepscore/ConstraintMatchTotalStepScoreSubSingleStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.subsingle.constraintmatchtotalstepscore; import java.util.ArrayList; import java.util.List; import ai.timefold.solver.benchmark.config.statistic.SingleStatisticType; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.LineChart; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.PureSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.StatisticRegistry; import ai.timefold.solver.core.api.score.constraint.ConstraintRef; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import io.micrometer.core.instrument.Tags; public class ConstraintMatchTotalStepScoreSubSingleStatistic<Solution_> extends PureSubSingleStatistic<Solution_, ConstraintMatchTotalStepScoreStatisticPoint, LineChart<Long, Double>> { private ConstraintMatchTotalStepScoreSubSingleStatistic() { // For JAXB. } public ConstraintMatchTotalStepScoreSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { super(subSingleBenchmarkResult, SingleStatisticType.CONSTRAINT_MATCH_TOTAL_STEP_SCORE); } @Override public void open(StatisticRegistry<Solution_> registry, Tags runTag) { registry.addListener(SolverMetric.CONSTRAINT_MATCH_TOTAL_STEP_SCORE, timeMillisSpent -> registry.extractConstraintSummariesFromMeters(SolverMetric.CONSTRAINT_MATCH_TOTAL_STEP_SCORE, runTag, constraintSummary -> pointList.add(new ConstraintMatchTotalStepScoreStatisticPoint( timeMillisSpent, constraintSummary.constraintRef(), constraintSummary.count(), constraintSummary.score())))); } @Override protected String getCsvHeader() { return ConstraintMatchTotalStepScoreStatisticPoint.buildCsvLine("timeMillisSpent", "constraintPackage", "constraintName", "constraintMatchCount", "scoreTotal"); } @Override protected ConstraintMatchTotalStepScoreStatisticPoint createPointFromCsvLine(ScoreDefinition<?> scoreDefinition, List<String> csvLine) { return new ConstraintMatchTotalStepScoreStatisticPoint(Long.parseLong(csvLine.get(0)), ConstraintRef.of(csvLine.get(1), csvLine.get(2)), Integer.parseInt(csvLine.get(3)), scoreDefinition.parseScore(csvLine.get(4))); } @Override protected List<LineChart<Long, Double>> generateCharts(BenchmarkReport benchmarkReport) { List<LineChart.Builder<Long, Double>> builderList = new ArrayList<>(BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE); for (ConstraintMatchTotalStepScoreStatisticPoint point : getPointList()) { long timeMillisSpent = point.getTimeMillisSpent(); double[] levelValues = point.getScoreTotal().toLevelDoubles(); for (int i = 0; i < levelValues.length && i < BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE; i++) { if (i >= builderList.size()) { builderList.add(new LineChart.Builder<>()); } LineChart.Builder<Long, Double> builder = builderList.get(i); String seriesLabel = point.getConstraintRef().constraintName() + " weight"; // Only add changes double lastValue = (builder.count(seriesLabel) == 0) ? 0.0 : builder.getLastValue(seriesLabel); if (levelValues[i] != lastValue) { builder.add(seriesLabel, timeMillisSpent, levelValues[i]); } } } long timeMillisSpent = subSingleBenchmarkResult.getTimeMillisSpent(); for (LineChart.Builder<Long, Double> builder : builderList) { for (String key : builder.keys()) { // Draw a horizontal line from the last new best step to how long the solver actually ran builder.add(key, timeMillisSpent, builder.getLastValue(key)); } } List<LineChart<Long, Double>> chartList = new ArrayList<>(builderList.size()); for (int scoreLevelIndex = 0; scoreLevelIndex < builderList.size(); scoreLevelIndex++) { String scoreLevelLabel = subSingleBenchmarkResult.getSingleBenchmarkResult().getProblemBenchmarkResult() .findScoreLevelLabel(scoreLevelIndex); LineChart.Builder<Long, Double> builder = builderList.get(scoreLevelIndex); LineChart<Long, Double> chart = builder.build("constraintMatchTotalStepScoreSubSingleStatisticChart" + scoreLevelIndex, subSingleBenchmarkResult.getName() + " constraint match total step " + scoreLevelLabel + " diff statistic", "Time spent", "Constraint match total " + scoreLevelLabel, true, true, false); chartList.add(chart); } return chartList; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/subsingle
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/subsingle/pickedmovetypebestscore/PickedMoveTypeBestScoreDiffStatisticPoint.java
package ai.timefold.solver.benchmark.impl.statistic.subsingle.pickedmovetypebestscore; import ai.timefold.solver.benchmark.impl.aggregator.BenchmarkAggregator; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.heuristic.move.CompositeMove; import ai.timefold.solver.core.impl.heuristic.move.Move; public class PickedMoveTypeBestScoreDiffStatisticPoint extends StatisticPoint { private final long timeMillisSpent; /** * Not a {@link Class}{@code <}{@link Move}{@code >} because {@link CompositeMove}s need to be atomized * and because that {@link Class} might no longer exist when {@link BenchmarkAggregator} aggregates. */ private final String moveType; private final Score bestScoreDiff; public PickedMoveTypeBestScoreDiffStatisticPoint(long timeMillisSpent, String moveType, Score bestScoreDiff) { this.timeMillisSpent = timeMillisSpent; this.moveType = moveType; this.bestScoreDiff = bestScoreDiff; } public long getTimeMillisSpent() { return timeMillisSpent; } public String getMoveType() { return moveType; } public Score getBestScoreDiff() { return bestScoreDiff; } @Override public String toCsvLine() { return buildCsvLineWithStrings(timeMillisSpent, moveType, bestScoreDiff.toString()); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/subsingle
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/subsingle/pickedmovetypebestscore/PickedMoveTypeBestScoreDiffSubSingleStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.subsingle.pickedmovetypebestscore; import java.util.ArrayList; import java.util.List; import ai.timefold.solver.benchmark.config.statistic.SingleStatisticType; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.LineChart; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.PureSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.StatisticRegistry; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Tags; public class PickedMoveTypeBestScoreDiffSubSingleStatistic<Solution_> extends PureSubSingleStatistic<Solution_, PickedMoveTypeBestScoreDiffStatisticPoint, LineChart<Long, Double>> { private PickedMoveTypeBestScoreDiffSubSingleStatistic() { // For JAXB. } public PickedMoveTypeBestScoreDiffSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { super(subSingleBenchmarkResult, SingleStatisticType.PICKED_MOVE_TYPE_BEST_SCORE_DIFF); } @Override public void open(StatisticRegistry<Solution_> registry, Tags runTag) { registry.addListener(SolverMetric.PICKED_MOVE_TYPE_BEST_SCORE_DIFF, (timeMillisSpent, stepScope) -> { if (stepScope instanceof LocalSearchStepScope) { String moveType = ((LocalSearchStepScope<Solution_>) stepScope).getStep().describe(); registry.extractScoreFromMeters(SolverMetric.PICKED_MOVE_TYPE_BEST_SCORE_DIFF, runTag.and(Tag.of("move.type", moveType)), score -> pointList.add(new PickedMoveTypeBestScoreDiffStatisticPoint( timeMillisSpent, moveType, score.raw()))); } }); } @Override protected String getCsvHeader() { return PickedMoveTypeBestScoreDiffStatisticPoint.buildCsvLine("timeMillisSpent", "moveType", "bestScoreDiff"); } @Override protected PickedMoveTypeBestScoreDiffStatisticPoint createPointFromCsvLine(ScoreDefinition<?> scoreDefinition, List<String> csvLine) { return new PickedMoveTypeBestScoreDiffStatisticPoint(Long.parseLong(csvLine.get(0)), csvLine.get(1), scoreDefinition.parseScore(csvLine.get(2))); } @Override protected List<LineChart<Long, Double>> generateCharts(BenchmarkReport benchmarkReport) { List<LineChart.Builder<Long, Double>> builderList = new ArrayList<>(BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE); for (PickedMoveTypeBestScoreDiffStatisticPoint point : getPointList()) { long timeMillisSpent = point.getTimeMillisSpent(); String moveType = point.getMoveType(); double[] levelValues = point.getBestScoreDiff().toLevelDoubles(); for (int i = 0; i < levelValues.length && i < BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE; i++) { if (i >= builderList.size()) { builderList.add(new LineChart.Builder<>()); } LineChart.Builder<Long, Double> builder = builderList.get(i); builder.add(moveType, timeMillisSpent, levelValues[i]); } } List<LineChart<Long, Double>> chartList = new ArrayList<>(builderList.size()); for (int scoreLevelIndex = 0; scoreLevelIndex < builderList.size(); scoreLevelIndex++) { String scoreLevelLabel = subSingleBenchmarkResult.getSingleBenchmarkResult().getProblemBenchmarkResult() .findScoreLevelLabel(scoreLevelIndex); LineChart.Builder<Long, Double> builder = builderList.get(scoreLevelIndex); LineChart<Long, Double> chart = builder.build( "pickedMoveTypeBestScoreDiffSubSingleStatisticChart" + scoreLevelIndex, subSingleBenchmarkResult.getName() + " picked move type best " + scoreLevelLabel + " diff statistic", "Time spent", "Best " + scoreLevelLabel + " diff", true, true, false); chartList.add(chart); } return chartList; } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/subsingle
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/subsingle/pickedmovetypestepscore/PickedMoveTypeStepScoreDiffStatisticPoint.java
package ai.timefold.solver.benchmark.impl.statistic.subsingle.pickedmovetypestepscore; import ai.timefold.solver.benchmark.impl.aggregator.BenchmarkAggregator; import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint; import ai.timefold.solver.core.api.score.Score; import ai.timefold.solver.core.impl.heuristic.move.CompositeMove; import ai.timefold.solver.core.impl.heuristic.move.Move; public class PickedMoveTypeStepScoreDiffStatisticPoint extends StatisticPoint { private final long timeMillisSpent; /** * Not a {@link Class}{@code <}{@link Move}{@code >} because {@link CompositeMove}s need to be atomized * and because that {@link Class} might no longer exist when {@link BenchmarkAggregator} aggregates. */ private final String moveType; private final Score stepScoreDiff; public PickedMoveTypeStepScoreDiffStatisticPoint(long timeMillisSpent, String moveType, Score stepScoreDiff) { this.timeMillisSpent = timeMillisSpent; this.moveType = moveType; this.stepScoreDiff = stepScoreDiff; } public long getTimeMillisSpent() { return timeMillisSpent; } public String getMoveType() { return moveType; } public Score getStepScoreDiff() { return stepScoreDiff; } @Override public String toCsvLine() { return buildCsvLineWithStrings(timeMillisSpent, moveType, stepScoreDiff.toString()); } }
0
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/subsingle
java-sources/ai/timefold/solver/timefold-solver-benchmark/1.26.1/ai/timefold/solver/benchmark/impl/statistic/subsingle/pickedmovetypestepscore/PickedMoveTypeStepScoreDiffSubSingleStatistic.java
package ai.timefold.solver.benchmark.impl.statistic.subsingle.pickedmovetypestepscore; import java.util.ArrayList; import java.util.List; import ai.timefold.solver.benchmark.config.statistic.SingleStatisticType; import ai.timefold.solver.benchmark.impl.report.BenchmarkReport; import ai.timefold.solver.benchmark.impl.report.LineChart; import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult; import ai.timefold.solver.benchmark.impl.statistic.PureSubSingleStatistic; import ai.timefold.solver.benchmark.impl.statistic.StatisticRegistry; import ai.timefold.solver.core.config.solver.monitoring.SolverMetric; import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope; import ai.timefold.solver.core.impl.score.definition.ScoreDefinition; import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Tags; public class PickedMoveTypeStepScoreDiffSubSingleStatistic<Solution_> extends PureSubSingleStatistic<Solution_, PickedMoveTypeStepScoreDiffStatisticPoint, LineChart<Long, Double>> { private PickedMoveTypeStepScoreDiffSubSingleStatistic() { // For JAXB. } public PickedMoveTypeStepScoreDiffSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { super(subSingleBenchmarkResult, SingleStatisticType.PICKED_MOVE_TYPE_STEP_SCORE_DIFF); } @Override public void open(StatisticRegistry<Solution_> registry, Tags runTag) { registry.addListener(SolverMetric.PICKED_MOVE_TYPE_STEP_SCORE_DIFF, (timeMillisSpent, stepScope) -> { if (stepScope instanceof LocalSearchStepScope) { String moveType = ((LocalSearchStepScope<Solution_>) stepScope).getStep().describe(); registry.extractScoreFromMeters(SolverMetric.PICKED_MOVE_TYPE_STEP_SCORE_DIFF, runTag.and(Tag.of("move.type", moveType)), score -> pointList.add(new PickedMoveTypeStepScoreDiffStatisticPoint( timeMillisSpent, moveType, score.raw()))); } }); } @Override protected String getCsvHeader() { return PickedMoveTypeStepScoreDiffStatisticPoint.buildCsvLine("timeMillisSpent", "moveType", "stepScoreDiff"); } @Override protected PickedMoveTypeStepScoreDiffStatisticPoint createPointFromCsvLine(ScoreDefinition<?> scoreDefinition, List<String> csvLine) { return new PickedMoveTypeStepScoreDiffStatisticPoint(Long.parseLong(csvLine.get(0)), csvLine.get(1), scoreDefinition.parseScore(csvLine.get(2))); } @Override protected List<LineChart<Long, Double>> generateCharts(BenchmarkReport benchmarkReport) { List<LineChart.Builder<Long, Double>> builderList = new ArrayList<>(BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE); for (PickedMoveTypeStepScoreDiffStatisticPoint point : getPointList()) { long timeMillisSpent = point.getTimeMillisSpent(); String moveType = point.getMoveType(); double[] levelValues = point.getStepScoreDiff().toLevelDoubles(); for (int i = 0; i < levelValues.length && i < BenchmarkReport.CHARTED_SCORE_LEVEL_SIZE; i++) { if (i >= builderList.size()) { builderList.add(new LineChart.Builder<>()); } LineChart.Builder<Long, Double> builder = builderList.get(i); builder.add(moveType, timeMillisSpent, levelValues[i]); } } List<LineChart<Long, Double>> chartList = new ArrayList<>(builderList.size()); for (int scoreLevelIndex = 0; scoreLevelIndex < builderList.size(); scoreLevelIndex++) { String scoreLevelLabel = subSingleBenchmarkResult.getSingleBenchmarkResult().getProblemBenchmarkResult() .findScoreLevelLabel(scoreLevelIndex); LineChart.Builder<Long, Double> builder = builderList.get(scoreLevelIndex); LineChart<Long, Double> chart = builder.build( "pickedMoveTypeStepScoreDiffSubSingleStatisticChart" + scoreLevelIndex, subSingleBenchmarkResult.getName() + " picked move type step " + scoreLevelLabel + " diff statistic", "Time spent", "Step " + scoreLevelLabel + " diff", true, true, false); chartList.add(chart); } return chartList; } }