use of org.cpsolver.ifs.solver.Solver in project cpsolver by UniTime.
the class Test method main.
/**
* Main program
*
* @param args
* problem property file, input file (optional, may be set by
* General.Input property), output file (optional, may be set by
* General.OutputFile property)
*/
public static void main(String[] args) {
try {
DataProperties cfg = new DataProperties();
cfg.setProperty("Termination.StopWhenComplete", "false");
cfg.setProperty("Termination.TimeOut", "1800");
cfg.setProperty("General.SaveBestUnassigned", "-1");
cfg.setProperty("Neighbour.Class", "org.cpsolver.exam.heuristics.ExamNeighbourSelection");
if (args.length >= 1) {
cfg.load(new FileInputStream(args[0]));
cfg.setProperty("General.Config", new File(args[0]).getName());
}
cfg.putAll(System.getProperties());
File inputFile = new File("c:\\test\\exam\\exam1070.xml");
if (args.length >= 2) {
inputFile = new File(args[1]);
}
ToolBox.setSeed(cfg.getPropertyLong("General.Seed", Math.round(Long.MAX_VALUE * Math.random())));
cfg.setProperty("General.Input", inputFile.toString());
String outName = inputFile.getName();
if (outName.indexOf('.') >= 0)
outName = outName.substring(0, outName.lastIndexOf('.')) + "s.xml";
File outFile = new File(inputFile.getParentFile(), outName);
if (args.length >= 3) {
outFile = new File(args[2]);
if (outFile.exists() && outFile.isDirectory())
outFile = new File(outFile, outName);
if (!outFile.exists() && !outFile.getName().endsWith(".xml"))
outFile = new File(outFile, outName);
}
if (outFile.getParentFile() != null)
outFile.getParentFile().mkdirs();
cfg.setProperty("General.OutputFile", outFile.toString());
cfg.setProperty("General.Output", outFile.getParent());
String logName = outFile.getName();
if (logName.indexOf('.') >= 0)
logName = logName.substring(0, logName.lastIndexOf('.')) + ".log";
ToolBox.setupLogging(new File(outFile.getParent(), logName), "true".equals(System.getProperty("debug", "false")));
ExamModel model = new ExamModel(cfg);
Document document = (new SAXReader()).read(new File(cfg.getProperty("General.Input")));
int nrSolvers = cfg.getPropertyInt("Parallel.NrSolvers", 1);
Assignment<Exam, ExamPlacement> assignment = (nrSolvers <= 1 ? new DefaultSingleAssignment<Exam, ExamPlacement>() : new DefaultParallelAssignment<Exam, ExamPlacement>());
model.load(document, assignment);
Solver<Exam, ExamPlacement> solver = (nrSolvers == 1 ? new Solver<Exam, ExamPlacement>(cfg) : new ParallelSolver<Exam, ExamPlacement>(cfg));
solver.setInitalSolution(new Solution<Exam, ExamPlacement>(model, assignment));
solver.currentSolution().addSolutionListener(new SolutionListener<Exam, ExamPlacement>() {
@Override
public void solutionUpdated(Solution<Exam, ExamPlacement> solution) {
}
@Override
public void getInfo(Solution<Exam, ExamPlacement> solution, Map<String, String> info) {
}
@Override
public void getInfo(Solution<Exam, ExamPlacement> solution, Map<String, String> info, Collection<Exam> variables) {
}
@Override
public void bestCleared(Solution<Exam, ExamPlacement> solution) {
}
@Override
public void bestSaved(Solution<Exam, ExamPlacement> solution) {
ExamModel m = (ExamModel) solution.getModel();
Assignment<Exam, ExamPlacement> a = solution.getAssignment();
if (sLog.isInfoEnabled()) {
sLog.info("**BEST[" + solution.getIteration() + "]** " + (m.variables().size() > a.nrAssignedVariables() ? "V:" + a.nrAssignedVariables() + "/" + m.variables().size() + " - " : "") + "T:" + new DecimalFormat("0.00").format(m.getTotalValue(a)) + " " + m.toString(a) + (solution.getFailedIterations() > 0 ? ", F:" + sDoubleFormat.format(100.0 * solution.getFailedIterations() / solution.getIteration()) + "%" : ""));
}
}
@Override
public void bestRestored(Solution<Exam, ExamPlacement> solution) {
}
});
Runtime.getRuntime().addShutdownHook(new ShutdownHook(solver));
solver.start();
try {
solver.getSolverThread().join();
} catch (InterruptedException e) {
}
} catch (Exception e) {
e.printStackTrace();
}
}
use of org.cpsolver.ifs.solver.Solver in project cpsolver by UniTime.
the class Test method testMPP.
private static void testMPP(DataProperties properties) {
try {
FileInputStream fis = new FileInputStream(properties.getProperty("General.Input") + ".pl");
List<PrologFile.Term> v1 = PrologFile.readTermsFromStream(fis, "objects");
fis.close();
fis = new FileInputStream(properties.getProperty("General.Input") + ".solution");
List<PrologFile.Term> v2 = PrologFile.readTermsFromStream(fis, "assigned");
fis.close();
fis = new FileInputStream(properties.getProperty("General.Input") + ".mpp");
List<PrologFile.Term> v3 = PrologFile.readTermsFromStream(fis, "perturbation");
fis.close();
PrintWriter res = new PrintWriter(new FileWriter(properties.getProperty("General.Output") + File.separator + "result.pl"));
PrintWriter stat = new PrintWriter(new FileWriter(properties.getProperty("General.Output") + File.separator + "stat.pl"));
PrintWriter txt = new PrintWriter(new FileWriter(properties.getProperty("General.Output") + File.separator + "stat.csv"));
txt.println("pert;time[s];timeRMS;assigned;assignedRMS;perturbations;perturbationsRMS;iters;itersRMS");
java.text.DecimalFormat nf = new java.text.DecimalFormat("0.000", new java.text.DecimalFormatSymbols(Locale.US));
// gen80_22_initial().getRectangles().size();
int size = -1;
int tests = properties.getPropertyInt("Rpp.NrTests", 10);
int step = properties.getPropertyInt("Rpp.Step", 4);
int min = properties.getPropertyInt("Rpp.Min", 0);
int max = properties.getPropertyInt("Rpp.Max", -1);
for (int i = min; size == -1 || i <= (max > 0 ? Math.min(max, size) : size); i += step) {
double time = 0;
long assigned = 0;
long perturbation = 0;
long iters = 0;
double time2 = 0;
long assigned2 = 0;
long perturbation2 = 0;
long iters2 = 0;
for (int t = 1; t <= tests; t++) {
RPPModel m = loadModel(properties.getPropertyInt("Rpp.ProblemWidth", 40), properties.getPropertyInt("Rpp.ProblemHeight", 14), v1, v2, v3, i, t);
if (size < 0)
size = m.variables().size();
Solver<Rectangle, Location> s = new Solver<Rectangle, Location>(properties);
s.setInitalSolution(m);
s.start();
s.getSolverThread().join();
Solution<Rectangle, Location> best = s.currentSolution();
best.restoreBest();
res.println("result(" + t + "," + i + "," + nf.format(best.getBestTime()) + "," + (best.getModel().variables().size() - best.getModel().getBestUnassignedVariables()) + "," + best.getBestIteration() + ",");
Collection<Rectangle> notPlaced = best.getModel().bestUnassignedVariables(best.getAssignment());
if (notPlaced == null)
notPlaced = new ArrayList<Rectangle>();
res.print(" unassigned(" + (2 * notPlaced.size()) + "/[");
for (Iterator<Rectangle> it = notPlaced.iterator(); it.hasNext(); ) {
Rectangle rect = it.next();
res.print(rect.getName() + "X," + rect.getName() + "Y" + (it.hasNext() ? "," : ""));
}
res.println("]),");
StringBuffer sb = new StringBuffer();
int perts = 0;
for (Rectangle rect : ((RPPModel) best.getModel()).variables()) {
if (rect.getBestAssignment() != null && (rect.getInitialAssignment() == null || !rect.getBestAssignment().equals(rect.getInitialAssignment()))) {
sb.append(sb.length() == 0 ? "" : ",");
sb.append(rect.getName() + "X-" + (rect.getBestAssignment()).getX());
sb.append(sb.length() == 0 ? "" : ",");
sb.append(rect.getName() + "Y-" + (rect.getBestAssignment()).getY());
perts++;
}
if (rect.getBestAssignment() == null) {
perts++;
}
}
res.println(" perturbations(" + (2 * perts) + "/[" + sb + "])");
res.println(").");
res.flush();
iters += best.getBestIteration();
iters2 += (best.getBestIteration() * best.getBestIteration());
time += best.getBestTime();
time2 += (best.getBestTime() * best.getBestTime());
assigned += (best.getModel().variables().size() - best.getModel().getBestUnassignedVariables());
assigned2 += (best.getModel().variables().size() - best.getModel().getBestUnassignedVariables()) * (best.getModel().variables().size() - best.getModel().getBestUnassignedVariables());
perturbation += perts;
perturbation2 += perts * perts;
}
txt.println(i + ";" + nf.format(time / tests) + ";" + nf.format(ToolBox.rms(tests, time, time2)) + ";" + nf.format(((double) assigned) / tests) + ";" + nf.format(ToolBox.rms(tests, assigned, assigned2)) + ";" + nf.format(((double) perturbation) / tests) + ";" + nf.format(ToolBox.rms(tests, perturbation, perturbation2)) + ";" + nf.format(((double) iters) / tests) + ";" + nf.format(ToolBox.rms(tests, iters, iters2)));
txt.flush();
stat.println("averages( initperturbations( " + i + " ), time( " + nf.format(time / tests) + " ), assigned( " + nf.format(((double) assigned) / tests) + " ), perturbations( " + nf.format(((double) perturbation) / tests) + " ) ).");
stat.println("deviations( initperturbations( " + i + " ), time( " + nf.format(ToolBox.rms(tests, time, time2)) + " ), assigned( " + nf.format(ToolBox.rms(tests, assigned, assigned2)) + " ), perturbations( " + nf.format(ToolBox.rms(tests, perturbation, perturbation2)) + " ) ).");
stat.flush();
}
res.close();
txt.close();
stat.close();
} catch (Exception e) {
e.printStackTrace();
}
}
use of org.cpsolver.ifs.solver.Solver in project cpsolver by UniTime.
the class Test method test.
private static void test(DataProperties properties) {
try {
int tests = properties.getPropertyInt("Rpp.NrTests", 10);
int min = properties.getPropertyInt("Rpp.Min", 0);
int max = properties.getPropertyInt("Rpp.Max", -1);
PrintWriter res = new PrintWriter(new FileWriter(properties.getProperty("General.Output") + File.separator + "result.pl"));
PrintWriter stat = new PrintWriter(new FileWriter(properties.getProperty("General.Output") + File.separator + "stat.pl"));
PrintWriter txt = new PrintWriter(new FileWriter(properties.getProperty("General.Output") + File.separator + "stat.csv"));
txt.println("gen;time[s];timeRMS;assigned;assignedRMS;iters;itersRMS");
java.text.DecimalFormat nf = new java.text.DecimalFormat("0.000", new java.text.DecimalFormatSymbols(Locale.US));
for (int genNr = min; genNr <= max; genNr++) {
FileInputStream fis = new FileInputStream(properties.getProperty("General.Input") + File.separator + "gen" + genNr + ".pl");
List<PrologFile.Term> v1 = PrologFile.readTermsFromStream(fis, "objects");
fis.close();
double time = 0;
long assigned = 0;
long iters = 0;
double time2 = 0;
long assigned2 = 0;
long iters2 = 0;
for (int t = 1; t <= tests; t++) {
RPPModel m = loadModel(properties.getPropertyInt("Rpp.ProblemWidth", 40), properties.getPropertyInt("Rpp.ProblemHeight", 14), v1);
Solver<Rectangle, Location> s = new Solver<Rectangle, Location>(properties);
s.setInitalSolution(m);
s.start();
s.getSolverThread().join();
Solution<Rectangle, Location> best = s.currentSolution();
best.restoreBest();
iters += best.getBestIteration();
iters2 += (best.getBestIteration() * best.getBestIteration());
time += best.getBestTime();
time2 += (best.getBestTime() * best.getBestTime());
assigned += (best.getModel().variables().size() - best.getModel().getBestUnassignedVariables());
assigned2 += (best.getModel().variables().size() - best.getModel().getBestUnassignedVariables()) * (best.getModel().variables().size() - best.getModel().getBestUnassignedVariables());
res.println("result(" + genNr + "," + t + "," + nf.format(best.getBestTime()) + "," + (best.getModel().variables().size() - best.getModel().getBestUnassignedVariables()) + "," + best.getBestIteration() + ",");
Collection<Rectangle> notPlaced = best.getModel().bestUnassignedVariables(best.getAssignment());
if (notPlaced == null)
notPlaced = new ArrayList<Rectangle>();
res.print(" unassigned(" + (2 * notPlaced.size()) + "/[");
for (Iterator<Rectangle> it = notPlaced.iterator(); it.hasNext(); ) {
Rectangle rect = it.next();
res.print(rect.getName() + "X," + rect.getName() + "Y" + (it.hasNext() ? "," : ""));
}
res.println("]),");
int perts = 0;
StringBuffer sb = new StringBuffer();
for (Rectangle rect : ((RPPModel) best.getModel()).variables()) {
if (rect.getBestAssignment() != null) {
sb.append(sb.length() == 0 ? "" : ",");
sb.append(rect.getName() + "X-" + (rect.getBestAssignment()).getX());
sb.append(sb.length() == 0 ? "" : ",");
sb.append(rect.getName() + "Y-" + (rect.getBestAssignment()).getY());
perts++;
}
}
res.println(" assigned(" + (2 * perts) + "/[" + sb + "])");
res.println(").");
res.flush();
}
txt.println(genNr + ";" + nf.format(time / tests) + ";" + nf.format(ToolBox.rms(tests, time, time2)) + ";" + nf.format(((double) assigned) / tests) + ";" + nf.format(ToolBox.rms(tests, assigned, assigned2)) + ";" + nf.format(((double) iters) / tests) + ";" + nf.format(ToolBox.rms(tests, iters, iters2)));
txt.flush();
stat.println("averages( problem( " + genNr + " ), time( " + nf.format(time / tests) + " ), assigned( " + nf.format(((double) assigned) / tests) + " ) ).");
stat.println("deviations( problem( " + genNr + " ), time( " + nf.format(ToolBox.rms(tests, time, time2)) + " ), assigned( " + nf.format(ToolBox.rms(tests, assigned, assigned2)) + " ) ).");
stat.flush();
}
res.close();
txt.close();
stat.close();
} catch (Exception e) {
e.printStackTrace();
}
}
use of org.cpsolver.ifs.solver.Solver in project cpsolver by UniTime.
the class Test method test2.
public static void test2(DataProperties properties) throws Exception {
int nrTests = properties.getPropertyInt("Test.NrTests", 1);
PrintWriter logStat = new PrintWriter(new FileWriter(properties.getProperty("General.Output") + File.separator + "output.csv"));
PrintWriter logAvgStat = new PrintWriter(new FileWriter(properties.getProperty("General.Output") + File.separator + "avg_stat.csv"));
logStat.println("fillFact;nrResources;testNr;time[s];iters;speed[it/s];assigned;assigned[%];value;totalValue");
logAvgStat.println("fillFact;nrResources;time[s];RMStime[s];iters;RMSiters;speed[it/s];assigned;RMSassigned;assigned[%];value;RMSvalue");
int nrResourcesMin = properties.getPropertyInt("Test.NrResourcesMin", -1);
int nrResourcesMax = properties.getPropertyInt("Test.NrResourcesMax", -1);
int nrResourcesStep = properties.getPropertyInt("Test.NrResourcesStep", 1);
double fillFactorMin = properties.getPropertyDouble("Test.FillFactorMin", -1.0);
double fillFactorMax = properties.getPropertyDouble("Test.FillFactorMax", -1.0);
double fillFactorStep = properties.getPropertyDouble("Test.FillFactorStep", 0.01);
boolean saveInit = properties.getPropertyBoolean("General.SaveInitialXML", true);
boolean saveSol = properties.getPropertyBoolean("General.SaveSolutionXML", true);
for (int nrResources = nrResourcesMin; nrResources <= nrResourcesMax; nrResources += nrResourcesStep) {
for (double fillFactor = fillFactorMin; fillFactor <= fillFactorMax; fillFactor += fillFactorStep) {
double sumTime = 0;
double sumTime2 = 0;
int sumIters = 0;
int sumIters2 = 0;
int sumAssign = 0;
int sumAssign2 = 0;
int sumVal = 0;
int sumVal2 = 0;
int sumVar = 0;
for (int test = 1; test <= nrTests; test++) {
if (nrResources >= 0) {
properties.setProperty("Generator.NrRooms", String.valueOf(nrResources));
properties.setProperty("Generator.NrClasses", String.valueOf(nrResources));
properties.setProperty("Generator.NrInstructors", String.valueOf(nrResources));
}
if (fillFactor >= 0.0) {
properties.setProperty("Generator.FillFactor", String.valueOf(fillFactor));
}
Assignment<Activity, Location> assignment = new DefaultSingleAssignment<Activity, Location>();
TimetableModel m = TimetableModel.generate(properties, assignment);
Solver<Activity, Location> s = new Solver<Activity, Location>(properties);
if (saveInit)
m.saveAsXML(properties, true, null, assignment, new File(properties.getProperty("General.Output") + File.separator + "SimpleTT(" + (nrResources < 0 ? properties.getPropertyInt("Generator.NrRooms", 20) : nrResources) + "," + ((int) (100.0 * (fillFactor < 0.0 ? properties.getPropertyDouble("Generator.FillFactor", 0.8) : fillFactor) + 0.5)) + "," + properties.getPropertyInt("Generator.NrDependencies", 50) + ")_" + test + ".xml"));
s.setInitalSolution(new Solution<Activity, Location>(m, assignment));
s.currentSolution().clearBest();
s.start();
try {
s.getSolverThread().join();
} catch (NullPointerException npe) {
}
if (s.lastSolution().getBestInfo() == null)
sLogger.error("No solution found :-(");
sLogger.debug("Last solution:" + s.lastSolution().getInfo());
Solution<Activity, Location> best = s.lastSolution();
sLogger.debug("Best solution:" + s.lastSolution().getBestInfo());
best.restoreBest();
int val = 0;
for (Activity var : ((TimetableModel) best.getModel()).assignedVariables(best.getAssignment())) val += (int) var.getAssignment(best.getAssignment()).toDouble();
if (saveSol)
m.saveAsXML(properties, true, best, best.getAssignment(), new File(properties.getProperty("General.Output") + File.separator + "SimpleTT(" + (nrResources < 0 ? properties.getPropertyInt("Generator.NrRooms", 20) : nrResources) + "," + ((int) (100.0 * (fillFactor < 0.0 ? properties.getPropertyDouble("Generator.FillFactor", 0.8) : fillFactor) + 0.5)) + "," + properties.getPropertyInt("Generator.NrDependencies", 50) + ")_" + test + "_sol.xml"));
sLogger.debug("Last solution:" + best.getInfo());
logStat.println(sDoubleFormat.format(properties.getPropertyDouble("Generator.FillFactor", 0.0)) + ";" + sDoubleFormat.format(properties.getPropertyInt("Generator.NrRooms", 0)) + ";" + test + ";" + sDoubleFormat.format(best.getTime()) + ";" + best.getIteration() + ";" + sDoubleFormat.format((best.getIteration()) / best.getTime()) + ";" + best.getModel().assignedVariables(best.getAssignment()).size() + ";" + sDoubleFormat.format(100.0 * best.getModel().assignedVariables(best.getAssignment()).size() / best.getModel().variables().size()) + ";" + val);
sLogger.debug(" time: " + sDoubleFormat.format(best.getTime()) + " s");
sLogger.debug(" iteration: " + best.getIteration());
sLogger.debug(" speed: " + sDoubleFormat.format((best.getIteration()) / best.getTime()) + " it/s");
sLogger.debug(" assigned: " + best.getModel().assignedVariables(best.getAssignment()).size() + " (" + sDoubleFormat.format(100.0 * best.getModel().assignedVariables(best.getAssignment()).size() / best.getModel().variables().size()) + "%)");
sLogger.debug(" value: " + val);
sumTime += best.getTime();
sumTime2 += best.getTime() * best.getTime();
sumIters += best.getIteration();
sumIters2 += best.getIteration() * best.getIteration();
sumAssign += best.getModel().assignedVariables(best.getAssignment()).size();
sumAssign2 += best.getModel().assignedVariables(best.getAssignment()).size() * best.getModel().assignedVariables(best.getAssignment()).size();
sumVal += val;
sumVal2 += val * val;
sumVar += m.variables().size();
logStat.flush();
}
logAvgStat.println(sDoubleFormat.format(properties.getPropertyDouble("Generator.FillFactor", 0.0)) + ";" + sDoubleFormat.format(properties.getPropertyInt("Generator.NrRooms", 0)) + ";" + sDoubleFormat.format(sumTime / nrTests) + ";" + sDoubleFormat.format(ToolBox.rms(nrTests, sumTime, sumTime2)) + ";" + sDoubleFormat.format(((double) sumIters) / nrTests) + ";" + sDoubleFormat.format(ToolBox.rms(nrTests, sumIters, sumIters2)) + ";" + sDoubleFormat.format((sumIters) / sumTime) + ";" + sDoubleFormat.format(((double) sumAssign) / nrTests) + ";" + sDoubleFormat.format(ToolBox.rms(nrTests, sumAssign, sumAssign2)) + ";" + sDoubleFormat.format(100.0 * (sumAssign) / sumVar) + ";" + sDoubleFormat.format(((double) sumVal) / nrTests) + ";" + sDoubleFormat.format(ToolBox.rms(nrTests, sumVal, sumVal2)));
logAvgStat.flush();
}
}
logStat.close();
logAvgStat.close();
}
use of org.cpsolver.ifs.solver.Solver in project cpsolver by UniTime.
the class Test method combineStudents.
/**
* Combine students from the provided two files
* @param cfg solver configuration
* @param lastLikeStudentData a file containing last-like student data
* @param realStudentData a file containing real student data
* @return combined solution
*/
public static Solution<Request, Enrollment> combineStudents(DataProperties cfg, File lastLikeStudentData, File realStudentData) {
try {
RandomStudentFilter rnd = new RandomStudentFilter(1.0);
StudentSectioningModel model = null;
Assignment<Request, Enrollment> assignment = new DefaultSingleAssignment<Request, Enrollment>();
for (StringTokenizer stk = new StringTokenizer(cfg.getProperty("Test.CombineAcceptProb", "1.0"), ","); stk.hasMoreTokens(); ) {
double acceptProb = Double.parseDouble(stk.nextToken());
sLog.info("Test.CombineAcceptProb=" + acceptProb);
rnd.setProbability(acceptProb);
StudentFilter batchFilter = new CombinedStudentFilter(new ReverseStudentFilter(new FreshmanStudentFilter()), rnd, CombinedStudentFilter.OP_AND);
model = new StudentSectioningModel(cfg);
StudentSectioningXMLLoader loader = new StudentSectioningXMLLoader(model, assignment);
loader.setLoadStudents(false);
loader.load();
StudentSectioningXMLLoader lastLikeLoader = new StudentSectioningXMLLoader(model, assignment);
lastLikeLoader.setInputFile(lastLikeStudentData);
lastLikeLoader.setLoadOfferings(false);
lastLikeLoader.setLoadStudents(true);
lastLikeLoader.load();
StudentSectioningXMLLoader realLoader = new StudentSectioningXMLLoader(model, assignment);
realLoader.setInputFile(realStudentData);
realLoader.setLoadOfferings(false);
realLoader.setLoadStudents(true);
realLoader.setStudentFilter(batchFilter);
realLoader.load();
fixWeights(model);
fixPriorities(model);
Solver<Request, Enrollment> solver = new Solver<Request, Enrollment>(model.getProperties());
solver.setInitalSolution(model);
new StudentSectioningXMLSaver(solver).save(new File(new File(model.getProperties().getProperty("General.Output", ".")), "solution-r" + ((int) (100.0 * acceptProb)) + ".xml"));
}
return model == null ? null : new Solution<Request, Enrollment>(model, assignment);
} catch (Exception e) {
sLog.error("Unable to combine students, reason: " + e.getMessage(), e);
return null;
}
}
Aggregations