org.optaplanner.examples.common.business.SolutionBusiness Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of optaplanner-examples Show documentation
Show all versions of optaplanner-examples Show documentation
OptaPlanner solves planning problems.
This lightweight, embeddable planning engine implements powerful and scalable algorithms
to optimize business resource scheduling and planning.
This module contains the examples which demonstrate how to use it in a normal Java application.
/*
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.examples.common.business;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import javax.swing.SwingUtilities;
import org.apache.commons.io.FileUtils;
import org.optaplanner.core.api.domain.solution.PlanningSolution;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.api.score.constraint.ConstraintMatchTotal;
import org.optaplanner.core.api.score.constraint.Indictment;
import org.optaplanner.core.api.solver.Solver;
import org.optaplanner.core.impl.domain.entity.descriptor.EntityDescriptor;
import org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor;
import org.optaplanner.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import org.optaplanner.core.impl.domain.variable.inverserelation.SingletonInverseVariableDemand;
import org.optaplanner.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import org.optaplanner.core.impl.domain.variable.supply.SupplyManager;
import org.optaplanner.core.impl.heuristic.move.Move;
import org.optaplanner.core.impl.heuristic.selector.move.generic.ChangeMove;
import org.optaplanner.core.impl.heuristic.selector.move.generic.SwapMove;
import org.optaplanner.core.impl.heuristic.selector.move.generic.chained.ChainedChangeMove;
import org.optaplanner.core.impl.heuristic.selector.move.generic.chained.ChainedSwapMove;
import org.optaplanner.core.impl.score.director.InnerScoreDirector;
import org.optaplanner.core.impl.score.director.ScoreDirector;
import org.optaplanner.core.impl.solver.ProblemFactChange;
import org.optaplanner.examples.common.app.CommonApp;
import org.optaplanner.examples.common.persistence.AbstractSolutionExporter;
import org.optaplanner.examples.common.persistence.AbstractSolutionImporter;
import org.optaplanner.examples.common.swingui.SolverAndPersistenceFrame;
import org.optaplanner.persistence.common.api.domain.solution.SolutionFileIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @param the solution type, the class with the {@link PlanningSolution} annotation
*/
public class SolutionBusiness {
private static final ProblemFileComparator FILE_COMPARATOR = new ProblemFileComparator();
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
private final CommonApp app;
private File dataDir;
private SolutionFileIO solutionFileIO;
private AbstractSolutionImporter[] importers;
private AbstractSolutionExporter exporter;
private File importDataDir;
private File unsolvedDataDir;
private File solvedDataDir;
private File exportDataDir;
// volatile because the solve method doesn't come from the event thread (like every other method call)
private volatile Solver solver;
private String solutionFileName = null;
private ScoreDirector guiScoreDirector;
private final AtomicReference skipToBestSolutionRef = new AtomicReference<>();
public SolutionBusiness(CommonApp app) {
this.app = app;
}
public String getAppName() {
return app.getName();
}
public String getAppDescription() {
return app.getDescription();
}
public String getAppIconResource() {
return app.getIconResource();
}
public File getDataDir() {
return dataDir;
}
public void setDataDir(File dataDir) {
this.dataDir = dataDir;
}
public SolutionFileIO getSolutionFileIO() {
return solutionFileIO;
}
public void setSolutionFileIO(SolutionFileIO solutionFileIO) {
this.solutionFileIO = solutionFileIO;
}
public AbstractSolutionImporter[] getImporters() {
return importers;
}
public void setImporters(AbstractSolutionImporter[] importers) {
this.importers = importers;
}
public void setExporter(AbstractSolutionExporter exporter) {
this.exporter = exporter;
}
public boolean hasImporter() {
return importers.length > 0;
}
public boolean hasExporter() {
return exporter != null;
}
public void updateDataDirs() {
if (hasImporter()) {
importDataDir = new File(dataDir, "import");
if (!importDataDir.exists()) {
throw new IllegalStateException("The directory importDataDir (" + importDataDir.getAbsolutePath()
+ ") does not exist.");
}
}
unsolvedDataDir = new File(dataDir, "unsolved");
if (!unsolvedDataDir.exists()) {
throw new IllegalStateException("The directory unsolvedDataDir (" + unsolvedDataDir.getAbsolutePath()
+ ") does not exist.");
}
solvedDataDir = new File(dataDir, "solved");
if (!solvedDataDir.exists() && !solvedDataDir.mkdir()) {
throw new IllegalStateException("The directory solvedDataDir (" + solvedDataDir.getAbsolutePath()
+ ") does not exist and could not be created.");
}
if (hasExporter()) {
exportDataDir = new File(dataDir, "export");
if (!exportDataDir.exists() && !exportDataDir.mkdir()) {
throw new IllegalStateException("The directory exportDataDir (" + exportDataDir.getAbsolutePath()
+ ") does not exist and could not be created.");
}
}
}
public File getImportDataDir() {
return importDataDir;
}
public File getUnsolvedDataDir() {
return unsolvedDataDir;
}
public File getSolvedDataDir() {
return solvedDataDir;
}
public File getExportDataDir() {
return exportDataDir;
}
public String getExportFileSuffix() {
return exporter.getOutputFileSuffix();
}
public void setSolver(Solver solver) {
this.solver = solver;
}
public void setGuiScoreDirector(ScoreDirector guiScoreDirector) {
this.guiScoreDirector = guiScoreDirector;
}
public List getUnsolvedFileList() {
List fileList = new ArrayList<>(
FileUtils.listFiles(unsolvedDataDir, new String[] { solutionFileIO.getInputFileExtension() }, true));
Collections.sort(fileList, FILE_COMPARATOR);
return fileList;
}
public List getSolvedFileList() {
List fileList = new ArrayList<>(
FileUtils.listFiles(solvedDataDir, new String[] { solutionFileIO.getOutputFileExtension() }, true));
Collections.sort(fileList, FILE_COMPARATOR);
return fileList;
}
public Solution_ getSolution() {
return guiScoreDirector.getWorkingSolution();
}
public void setSolution(Solution_ solution) {
guiScoreDirector.setWorkingSolution(solution);
}
public String getSolutionFileName() {
return solutionFileName;
}
public void setSolutionFileName(String solutionFileName) {
this.solutionFileName = solutionFileName;
}
public Score getScore() {
return guiScoreDirector.calculateScore();
}
public boolean isSolving() {
return solver.isSolving();
}
public void registerForBestSolutionChanges(final SolverAndPersistenceFrame solverAndPersistenceFrame) {
solver.addEventListener(event -> {
// Called on the Solver thread, so not on the Swing Event thread
/*
* Avoid ConcurrentModificationException when there is an unprocessed ProblemFactChange
* because the paint method uses the same problem facts instances as the Solver's workingSolution
* unlike the planning entities of the bestSolution which are cloned from the Solver's workingSolution
*/
if (solver.isEveryProblemFactChangeProcessed()) {
// The final is also needed for thread visibility
final Solution_ newBestSolution = event.getNewBestSolution();
skipToBestSolutionRef.set(newBestSolution);
SwingUtilities.invokeLater(() -> {
// Called on the Swing Event thread
Solution_ skipToBestSolution = skipToBestSolutionRef.get();
// Skip this event if a newer one arrived meanwhile to avoid flooding the Swing Event thread
if (newBestSolution != skipToBestSolution) {
return;
}
guiScoreDirector.setWorkingSolution(newBestSolution);
solverAndPersistenceFrame.bestSolutionChanged();
});
}
});
}
public boolean isConstraintMatchEnabled() {
return guiScoreDirector.isConstraintMatchEnabled();
}
public List getConstraintMatchTotalList() {
List constraintMatchTotalList = new ArrayList<>(
guiScoreDirector.getConstraintMatchTotals());
Collections.sort(constraintMatchTotalList);
return constraintMatchTotalList;
}
public Map