[jboss-svn-commits] JBL Code SVN: r32026 - in labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples: curriculumcourse/persistence and 8 other directories.
jboss-svn-commits at lists.jboss.org
jboss-svn-commits at lists.jboss.org
Wed Mar 10 15:23:04 EST 2010
Author: ge0ffrey
Date: 2010-03-10 15:23:01 -0500 (Wed, 10 Mar 2010)
New Revision: 32026
Added:
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractInputConverter.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractOutputConverter.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractTxtInputConverter.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractTxtOutputConverter.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractXmlInputConverter.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseInputConverter.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseOutputConverter.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationInputConverter.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationOutputConverter.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/manners2009/persistence/Manners2009InputConverter.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/nurserostering/domain/NurseAssignment.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/nurserostering/domain/NurseRoster.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/nurserostering/persistence/NurseRosteringDaoImpl.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/nurserostering/persistence/NurseRosteringInputConverter.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleInputConverter.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleOutputConverter.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/TravelingTournamentInputConverter.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/simple/SimpleTravelingTournamentInputConverter.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentInputConverter.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentOutputConverter.java
Removed:
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractInputConvertor.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractOutputConvertor.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseInputConvertor.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseOutputConvertor.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationInputConvertor.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationOutputConvertor.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/manners2009/persistence/Manners2009InputConvertor.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleInputConvertor.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleOutputConvertor.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/TravelingTournamentInputConvertor.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/simple/SimpleTravelingTournamentInputConvertor.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentInputConvertor.java
labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentOutputConvertor.java
Log:
nurse rostering competition: xml input converter
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractInputConverter.java (from rev 32019, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractInputConvertor.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractInputConverter.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractInputConverter.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,60 @@
+package org.drools.planner.examples.common.persistence;
+
+import java.io.File;
+import java.util.Arrays;
+
+import org.drools.planner.core.solution.Solution;
+import org.drools.planner.examples.common.app.LoggingMain;
+
+/**
+ * @author Geoffrey De Smet
+ */
+public abstract class AbstractInputConverter extends LoggingMain {
+
+ protected static final String DEFAULT_OUTPUT_FILE_SUFFIX = ".xml";
+
+ protected SolutionDao solutionDao;
+
+ public AbstractInputConverter(SolutionDao solutionDao) {
+ this.solutionDao = solutionDao;
+ }
+
+ protected File getInputDir() {
+ return new File(solutionDao.getDataDir(), "input");
+ }
+
+ protected abstract String getInputFileSuffix();
+
+ protected File getOutputDir() {
+ return new File(solutionDao.getDataDir(), "unsolved");
+ }
+
+ protected String getOutputFileSuffix() {
+ return DEFAULT_OUTPUT_FILE_SUFFIX;
+ }
+
+ public void convertAll() {
+ File inputDir = getInputDir();
+ File outputDir = getOutputDir();
+ File[] inputFiles = inputDir.listFiles();
+ if (inputFiles == null) {
+ throw new IllegalArgumentException(
+ "Your working dir should be drools-planner-examples and contain: " + inputDir);
+ }
+ Arrays.sort(inputFiles);
+ for (File inputFile : inputFiles) {
+ String inputFileName = inputFile.getName();
+ if (inputFileName.endsWith(getInputFileSuffix())) {
+ Solution solution = readSolution(inputFile);
+ String outputFileName = inputFileName.substring(0,
+ inputFileName.length() - getInputFileSuffix().length())
+ + getOutputFileSuffix();
+ File outputFile = new File(outputDir, outputFileName);
+ solutionDao.writeSolution(solution, outputFile);
+ }
+ }
+ }
+
+ public abstract Solution readSolution(File inputFile);
+
+}
Deleted: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractInputConvertor.java
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractInputConvertor.java 2010-03-10 20:15:05 UTC (rev 32025)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractInputConvertor.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -1,141 +0,0 @@
-package org.drools.planner.examples.common.persistence;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.Arrays;
-
-import org.apache.commons.io.IOUtils;
-import org.drools.planner.examples.common.app.LoggingMain;
-import org.drools.planner.examples.common.persistence.XstreamSolutionDaoImpl;
-import org.drools.planner.core.solution.Solution;
-
-/**
- * @author Geoffrey De Smet
- */
-public abstract class AbstractInputConvertor extends LoggingMain {
-
- private static final String DEFAULT_INPUT_FILE_SUFFIX = ".txt";
- protected static final String DEFAULT_OUTPUT_FILE_SUFFIX = ".xml";
-
- protected SolutionDao solutionDao;
-
- protected AbstractInputConvertor(SolutionDao solutionDao) {
- this.solutionDao = solutionDao;
- }
-
- protected File getInputDir() {
- return new File(solutionDao.getDataDir(), "input");
- }
-
- protected File getOutputDir() {
- return new File(solutionDao.getDataDir(), "unsolved");
- }
-
- protected String getInputFileSuffix() {
- return DEFAULT_INPUT_FILE_SUFFIX;
- }
-
- protected String getOutputFileSuffix() {
- return DEFAULT_OUTPUT_FILE_SUFFIX;
- }
-
- public void convertAll() {
- File inputDir = getInputDir();
- File outputDir = getOutputDir();
- File[] inputFiles = inputDir.listFiles();
- if (inputFiles == null) {
- throw new IllegalArgumentException(
- "Your working dir should be drools-planner-examples and contain: " + inputDir);
- }
- Arrays.sort(inputFiles);
- for (File inputFile : inputFiles) {
- String inputFileName = inputFile.getName();
- if (inputFileName.endsWith(getInputFileSuffix())) {
- Solution solution = readSolution(inputFile);
- String outputFileName = inputFileName.substring(0,
- inputFileName.length() - getInputFileSuffix().length())
- + getOutputFileSuffix();
- File outputFile = new File(outputDir, outputFileName);
- solutionDao.writeSolution(solution, outputFile);
- }
- }
- }
-
- public abstract InputBuilder createInputBuilder();
-
- public Solution readSolution(File inputFile) {
- BufferedReader bufferedReader = null;
- try {
- bufferedReader = new BufferedReader(new FileReader(inputFile));
- InputBuilder inputBuilder = createInputBuilder();
- inputBuilder.setBufferedReader(bufferedReader);
- return inputBuilder.readSolution();
- } catch (IOException e) {
- throw new IllegalArgumentException(e);
- } finally {
- IOUtils.closeQuietly(bufferedReader);
- }
- }
-
- public abstract class InputBuilder {
-
- protected BufferedReader bufferedReader;
-
- public void setBufferedReader(BufferedReader bufferedReader) {
- this.bufferedReader = bufferedReader;
- }
-
- public abstract Solution readSolution() throws IOException;
-
- // ************************************************************************
- // Helper methods
- // ************************************************************************
-
- public void readEmptyLine() throws IOException {
- readConstantLine("");
- }
-
- public void readConstantLine(String constantValue) throws IOException {
- String line = bufferedReader.readLine();
- String value = line.trim();
- if (!value.equals(constantValue)) {
- throw new IllegalArgumentException("Read line (" + line + ") is expected to be a constant value ("
- + constantValue + ").");
- }
- }
-
- public int readIntegerValue() throws IOException {
- return readIntegerValue("");
- }
-
- public int readIntegerValue(String prefix) throws IOException {
- return readIntegerValue(prefix, "");
- }
-
- public int readIntegerValue(String prefix, String suffix) throws IOException {
- String line = bufferedReader.readLine();
- String value = line.trim();
- if (!value.startsWith(prefix)) {
- throw new IllegalArgumentException("Read line (" + line + ") is expected to start with prefix ("
- + prefix + ").");
- }
- value = value.substring(prefix.length());
- if (!value.endsWith(suffix)) {
- throw new IllegalArgumentException("Read line (" + line + ") is expected to end with suffix ("
- + suffix + ").");
- }
- value = value.substring(0, value.length() - suffix.length());
- value = value.trim();
- try {
- return Integer.parseInt(value);
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException("Read line (" + line + ") is expected to contain an integer value ("
- + value + ").", e);
- }
- }
-
- }
-
-}
\ No newline at end of file
Added: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractOutputConverter.java
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractOutputConverter.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractOutputConverter.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,58 @@
+package org.drools.planner.examples.common.persistence;
+
+import java.io.File;
+import java.util.Arrays;
+
+import org.drools.planner.core.solution.Solution;
+import org.drools.planner.examples.common.app.LoggingMain;
+
+/**
+ * @author Geoffrey De Smet
+ */
+public abstract class AbstractOutputConverter extends LoggingMain {
+
+ private static final String DEFAULT_INPUT_FILE_SUFFIX = ".xml";
+ protected SolutionDao solutionDao;
+
+ public AbstractOutputConverter(SolutionDao solutionDao) {
+ this.solutionDao = solutionDao;
+ }
+
+ protected File getInputDir() {
+ return new File(solutionDao.getDataDir(), "solved");
+ }
+
+ protected File getOutputDir() {
+ return new File(solutionDao.getDataDir(), "output");
+ }
+
+ protected String getInputFileSuffix() {
+ return DEFAULT_INPUT_FILE_SUFFIX;
+ }
+
+ protected abstract String getOutputFileSuffix();
+
+ public void convertAll() {
+ File inputDir = getInputDir();
+ File outputDir = getOutputDir();
+ File[] inputFiles = inputDir.listFiles();
+ Arrays.sort(inputFiles);
+ if (inputFiles == null) {
+ throw new IllegalArgumentException(
+ "Your working dir should be drools-planner-examples and contain: " + inputDir);
+ }
+ for (File inputFile : inputFiles) {
+ String inputFileName = inputFile.getName();
+ if (inputFileName.endsWith(getInputFileSuffix())) {
+ Solution solution = solutionDao.readSolution(inputFile);
+ String outputFileName = inputFileName.substring(0,
+ inputFileName.length() - getInputFileSuffix().length())
+ + getOutputFileSuffix();
+ File outputFile = new File(outputDir, outputFileName);
+ writeSolution(solution, outputFile);
+ }
+ }
+ }
+
+ public abstract void writeSolution(Solution solution, File outputFile);
+}
Deleted: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractOutputConvertor.java
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractOutputConvertor.java 2010-03-10 20:15:05 UTC (rev 32025)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractOutputConvertor.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -1,101 +0,0 @@
-package org.drools.planner.examples.common.persistence;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.BufferedWriter;
-import java.io.FileWriter;
-import java.util.Arrays;
-
-import org.apache.commons.io.IOUtils;
-import org.drools.planner.examples.common.app.LoggingMain;
-import org.drools.planner.examples.common.persistence.XstreamSolutionDaoImpl;
-import org.drools.planner.core.solution.Solution;
-
-/**
- * @author Geoffrey De Smet
- */
-public abstract class AbstractOutputConvertor extends LoggingMain {
-
- private static final String DEFAULT_INPUT_FILE_SUFFIX = ".xml";
- protected static final String DEFAULT_OUTPUT_FILE_SUFFIX = ".txt";
-
- protected SolutionDao solutionDao;
-
- protected AbstractOutputConvertor(SolutionDao solutionDao) {
- this.solutionDao = solutionDao;
- }
-
- protected File getInputDir() {
- return new File(solutionDao.getDataDir(), "solved");
- }
-
- protected File getOutputDir() {
- return new File(solutionDao.getDataDir(), "output");
- }
-
- protected String getInputFileSuffix() {
- return DEFAULT_INPUT_FILE_SUFFIX;
- }
-
- protected String getOutputFileSuffix() {
- return DEFAULT_OUTPUT_FILE_SUFFIX;
- }
-
- public void convertAll() {
- File inputDir = getInputDir();
- File outputDir = getOutputDir();
- File[] inputFiles = inputDir.listFiles();
- Arrays.sort(inputFiles);
- if (inputFiles == null) {
- throw new IllegalArgumentException(
- "Your working dir should be drools-planner-examples and contain: " + inputDir);
- }
- for (File inputFile : inputFiles) {
- String inputFileName = inputFile.getName();
- if (inputFileName.endsWith(getInputFileSuffix())) {
- Solution solution = solutionDao.readSolution(inputFile);
- String outputFileName = inputFileName.substring(0,
- inputFileName.length() - getInputFileSuffix().length())
- + getOutputFileSuffix();
- File outputFile = new File(outputDir, outputFileName);
- writeSolution(solution, outputFile);
- }
- }
- }
-
- public abstract OutputBuilder createOutputBuilder();
-
- public void writeSolution(Solution solution, File outputFile) {
- BufferedWriter bufferedWriter = null;
- try {
- bufferedWriter = new BufferedWriter(new FileWriter(outputFile));
- OutputBuilder outputBuilder = createOutputBuilder();
- outputBuilder.setBufferedWriter(bufferedWriter);
- outputBuilder.setSolution(solution);
- outputBuilder.writeSolution();
- } catch (IOException e) {
- throw new IllegalArgumentException(e);
- } finally {
- IOUtils.closeQuietly(bufferedWriter);
- }
- }
-
- public abstract class OutputBuilder {
-
- protected BufferedWriter bufferedWriter;
-
- public void setBufferedWriter(BufferedWriter bufferedWriter) {
- this.bufferedWriter = bufferedWriter;
- }
-
- public abstract void setSolution(Solution solution);
-
- public abstract void writeSolution() throws IOException;
-
- // ************************************************************************
- // Helper methods
- // ************************************************************************
-
- }
-
-}
\ No newline at end of file
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractTxtInputConverter.java (from rev 32019, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractInputConvertor.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractTxtInputConverter.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractTxtInputConverter.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,101 @@
+package org.drools.planner.examples.common.persistence;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+
+import org.apache.commons.io.IOUtils;
+import org.drools.planner.core.solution.Solution;
+
+/**
+ * @author Geoffrey De Smet
+ */
+public abstract class AbstractTxtInputConverter extends AbstractInputConverter {
+
+ private static final String DEFAULT_INPUT_FILE_SUFFIX = ".txt";
+
+ protected AbstractTxtInputConverter(SolutionDao solutionDao) {
+ super(solutionDao);
+ }
+
+ protected String getInputFileSuffix() {
+ return DEFAULT_INPUT_FILE_SUFFIX;
+ }
+
+ public abstract TxtInputBuilder createTxtInputBuilder();
+
+ public Solution readSolution(File inputFile) {
+ BufferedReader bufferedReader = null;
+ try {
+ bufferedReader = new BufferedReader(new FileReader(inputFile));
+ TxtInputBuilder txtInputBuilder = createTxtInputBuilder();
+ txtInputBuilder.setBufferedReader(bufferedReader);
+ return txtInputBuilder.readSolution();
+ } catch (IOException e) {
+ throw new IllegalArgumentException(e);
+ } finally {
+ IOUtils.closeQuietly(bufferedReader);
+ }
+ }
+
+ public abstract class TxtInputBuilder {
+
+ protected BufferedReader bufferedReader;
+
+ public void setBufferedReader(BufferedReader bufferedReader) {
+ this.bufferedReader = bufferedReader;
+ }
+
+ public abstract Solution readSolution() throws IOException;
+
+ // ************************************************************************
+ // Helper methods
+ // ************************************************************************
+
+ public void readEmptyLine() throws IOException {
+ readConstantLine("");
+ }
+
+ public void readConstantLine(String constantValue) throws IOException {
+ String line = bufferedReader.readLine();
+ String value = line.trim();
+ if (!value.equals(constantValue)) {
+ throw new IllegalArgumentException("Read line (" + line + ") is expected to be a constant value ("
+ + constantValue + ").");
+ }
+ }
+
+ public int readIntegerValue() throws IOException {
+ return readIntegerValue("");
+ }
+
+ public int readIntegerValue(String prefix) throws IOException {
+ return readIntegerValue(prefix, "");
+ }
+
+ public int readIntegerValue(String prefix, String suffix) throws IOException {
+ String line = bufferedReader.readLine();
+ String value = line.trim();
+ if (!value.startsWith(prefix)) {
+ throw new IllegalArgumentException("Read line (" + line + ") is expected to start with prefix ("
+ + prefix + ").");
+ }
+ value = value.substring(prefix.length());
+ if (!value.endsWith(suffix)) {
+ throw new IllegalArgumentException("Read line (" + line + ") is expected to end with suffix ("
+ + suffix + ").");
+ }
+ value = value.substring(0, value.length() - suffix.length());
+ value = value.trim();
+ try {
+ return Integer.parseInt(value);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Read line (" + line + ") is expected to contain an integer value ("
+ + value + ").", e);
+ }
+ }
+
+ }
+
+}
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractTxtOutputConverter.java (from rev 32019, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractOutputConvertor.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractTxtOutputConverter.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractTxtOutputConverter.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,61 @@
+package org.drools.planner.examples.common.persistence;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.BufferedWriter;
+import java.io.FileWriter;
+
+import org.apache.commons.io.IOUtils;
+import org.drools.planner.core.solution.Solution;
+
+/**
+ * @author Geoffrey De Smet
+ */
+public abstract class AbstractTxtOutputConverter extends AbstractOutputConverter {
+
+ protected static final String DEFAULT_OUTPUT_FILE_SUFFIX = ".txt";
+
+ protected AbstractTxtOutputConverter(SolutionDao solutionDao) {
+ super(solutionDao);
+ }
+
+ protected String getOutputFileSuffix() {
+ return DEFAULT_OUTPUT_FILE_SUFFIX;
+ }
+
+ public abstract TxtOutputBuilder createTxtOutputBuilder();
+
+ public void writeSolution(Solution solution, File outputFile) {
+ BufferedWriter bufferedWriter = null;
+ try {
+ bufferedWriter = new BufferedWriter(new FileWriter(outputFile));
+ TxtOutputBuilder txtOutputBuilder = createTxtOutputBuilder();
+ txtOutputBuilder.setBufferedWriter(bufferedWriter);
+ txtOutputBuilder.setSolution(solution);
+ txtOutputBuilder.writeSolution();
+ } catch (IOException e) {
+ throw new IllegalArgumentException(e);
+ } finally {
+ IOUtils.closeQuietly(bufferedWriter);
+ }
+ }
+
+ public abstract class TxtOutputBuilder {
+
+ protected BufferedWriter bufferedWriter;
+
+ public void setBufferedWriter(BufferedWriter bufferedWriter) {
+ this.bufferedWriter = bufferedWriter;
+ }
+
+ public abstract void setSolution(Solution solution);
+
+ public abstract void writeSolution() throws IOException;
+
+ // ************************************************************************
+ // Helper methods
+ // ************************************************************************
+
+ }
+
+}
Added: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractXmlInputConverter.java
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractXmlInputConverter.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractXmlInputConverter.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,80 @@
+package org.drools.planner.examples.common.persistence;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.apache.commons.io.IOUtils;
+import org.drools.planner.core.solution.Solution;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.xml.sax.SAXException;
+
+/**
+ * @author Geoffrey De Smet
+ */
+public abstract class AbstractXmlInputConverter extends AbstractInputConverter {
+
+ private static final String DEFAULT_INPUT_FILE_SUFFIX = ".xml";
+
+ protected AbstractXmlInputConverter(SolutionDao solutionDao) {
+ super(solutionDao);
+ }
+
+ protected String getInputFileSuffix() {
+ return DEFAULT_INPUT_FILE_SUFFIX;
+ }
+
+ public abstract XmlInputBuilder createXmlInputBuilder();
+
+ public Solution readSolution(File inputFile) {
+ InputStream in = null;
+ try {
+ in = new FileInputStream(inputFile);
+ DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
+ Document document = documentBuilder.parse(in);
+ XmlInputBuilder txtInputBuilder = createXmlInputBuilder();
+ txtInputBuilder.setDocument(document);
+ return txtInputBuilder.readSolution();
+ } catch (IOException e) {
+ throw new IllegalArgumentException(e);
+ } catch (ParserConfigurationException e) {
+ throw new IllegalArgumentException(e);
+ } catch (SAXException e) {
+ throw new IllegalArgumentException(e);
+ } finally {
+ IOUtils.closeQuietly(in);
+ }
+ }
+
+ public abstract class XmlInputBuilder {
+
+ protected Document document;
+
+ public void setDocument(Document document) {
+ this.document = document;
+ }
+
+ public abstract Solution readSolution() throws IOException;
+
+ // ************************************************************************
+ // Helper methods
+ // ************************************************************************
+
+ protected void assertNodeName(Node node, String nodeName) {
+ if (!node.getNodeName().equals(nodeName)) {
+ throw new IllegalArgumentException("The node name (" + node.getNodeName()
+ + ") is expected to be " + nodeName + ".");
+ }
+ }
+
+ }
+
+}
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseInputConverter.java (from rev 32019, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseInputConvertor.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseInputConverter.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseInputConverter.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,275 @@
+package org.drools.planner.examples.curriculumcourse.persistence;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.drools.planner.examples.common.persistence.AbstractTxtInputConverter;
+import org.drools.planner.examples.curriculumcourse.domain.Course;
+import org.drools.planner.examples.curriculumcourse.domain.Curriculum;
+import org.drools.planner.examples.curriculumcourse.domain.CurriculumCourseSchedule;
+import org.drools.planner.examples.curriculumcourse.domain.Day;
+import org.drools.planner.examples.curriculumcourse.domain.Period;
+import org.drools.planner.examples.curriculumcourse.domain.Room;
+import org.drools.planner.examples.curriculumcourse.domain.Teacher;
+import org.drools.planner.examples.curriculumcourse.domain.Timeslot;
+import org.drools.planner.examples.curriculumcourse.domain.UnavailablePeriodConstraint;
+import org.drools.planner.core.solution.Solution;
+
+/**
+ * @author Geoffrey De Smet
+ */
+public class CurriculumCourseInputConverter extends AbstractTxtInputConverter {
+
+ private static final String INPUT_FILE_SUFFIX = ".ctt";
+ private static final String SPLIT_REGEX = "[\\ \\t]+";
+
+ public static void main(String[] args) {
+ new CurriculumCourseInputConverter().convertAll();
+ }
+
+ public CurriculumCourseInputConverter() {
+ super(new CurriculumCourseDaoImpl());
+ }
+
+ @Override
+ protected String getInputFileSuffix() {
+ return INPUT_FILE_SUFFIX;
+ }
+
+ public TxtInputBuilder createTxtInputBuilder() {
+ return new CurriculumCourseInputBuilder();
+ }
+
+ public class CurriculumCourseInputBuilder extends TxtInputBuilder {
+
+ public Solution readSolution() throws IOException {
+ CurriculumCourseSchedule schedule = new CurriculumCourseSchedule();
+ schedule.setId(0L);
+ // Name: ToyExample
+ schedule.setName(readParam("Name:"));
+ // Courses: 4
+ int courseListSize = Integer.parseInt(readParam("Courses:"));
+ // Rooms: 2
+ int roomListSize = Integer.parseInt(readParam("Rooms:"));
+ // Days: 5
+ int dayListSize = Integer.parseInt(readParam("Days:"));
+ // Periods_per_day: 4
+ int timeslotListSize = Integer.parseInt(readParam("Periods_per_day:"));
+ // Curricula: 2
+ int curriculumListSize = Integer.parseInt(readParam("Curricula:"));
+ // Constraints: 8
+ int unavailablePeriodConstraintListSize = Integer.parseInt(readParam("Constraints:"));
+
+ Map<String, Course> courseMap = readCourseListAndTeacherList(
+ schedule, courseListSize);
+ readRoomList(
+ schedule, roomListSize);
+ Map<List<Integer>, Period> periodMap = createPeriodListAndDayListAndTimeslotList(
+ schedule, dayListSize, timeslotListSize);
+ readCurriculumList(
+ schedule, courseMap, curriculumListSize);
+ readUnavailablePeriodConstraintList(
+ schedule, courseMap, periodMap, unavailablePeriodConstraintListSize);
+ readHeader("END.");
+
+ logger.info("CurriculumCourseSchedule with {} teachers, {} curricula, {} courses, {} periods, {} rooms" +
+ " and {} unavailable period constraints.",
+ new Object[]{schedule.getTeacherList().size(),
+ schedule.getCurriculumList().size(),
+ schedule.getCourseList().size(),
+ schedule.getPeriodList().size(),
+ schedule.getRoomList().size(),
+ schedule.getUnavailablePeriodConstraintList().size()});
+
+ // Note: lectureList stays null, that's work for the StartingSolutionInitializer
+ return schedule;
+ }
+
+ private Map<String, Course> readCourseListAndTeacherList(
+ CurriculumCourseSchedule schedule, int courseListSize) throws IOException {
+ Map<String, Course> courseMap = new HashMap<String, Course>(courseListSize);
+ Map<String, Teacher> teacherMap = new HashMap<String, Teacher>();
+ List<Course> courseList = new ArrayList<Course>(courseListSize);
+ readHeader("COURSES:");
+ for (int i = 0; i < courseListSize; i++) {
+ Course course = new Course();
+ course.setId((long) i);
+ // Courses: <CourseID> <Teacher> <# Lectures> <MinWorkingDays> <# Students>
+ String line = bufferedReader.readLine();
+ String[] lineTokens = line.split(SPLIT_REGEX);
+ if (lineTokens.length != 5) {
+ throw new IllegalArgumentException("Read line (" + line + ") is expected to contain 4 tokens.");
+ }
+ course.setCode(lineTokens[0]);
+ course.setTeacher(findOrCreateTeacher(teacherMap, lineTokens[1]));
+ course.setLectureSize(Integer.parseInt(lineTokens[2]));
+ course.setMinWorkingDaySize(Integer.parseInt(lineTokens[3]));
+ course.setCurriculumList(new ArrayList<Curriculum>());
+ course.setStudentSize(Integer.parseInt(lineTokens[4]));
+ courseList.add(course);
+ courseMap.put(course.getCode(), course);
+ }
+ schedule.setCourseList(courseList);
+ List<Teacher> teacherList = new ArrayList<Teacher>(teacherMap.values());
+ schedule.setTeacherList(teacherList);
+ return courseMap;
+ }
+
+ private Teacher findOrCreateTeacher(Map<String, Teacher> teacherMap, String code) {
+ Teacher teacher = teacherMap.get(code);
+ if (teacher == null) {
+ teacher = new Teacher();
+ int id = teacherMap.size();
+ teacher.setId((long) id);
+ teacher.setCode(code);
+ teacherMap.put(code, teacher);
+ }
+ return teacher;
+ }
+
+ private void readRoomList(CurriculumCourseSchedule schedule, int roomListSize)
+ throws IOException {
+ readHeader("ROOMS:");
+ List<Room> roomList = new ArrayList<Room>(roomListSize);
+ for (int i = 0; i < roomListSize; i++) {
+ Room room = new Room();
+ room.setId((long) i);
+ // Rooms: <RoomID> <Capacity>
+ String line = bufferedReader.readLine();
+ String[] lineTokens = line.split(SPLIT_REGEX);
+ if (lineTokens.length != 2) {
+ throw new IllegalArgumentException("Read line (" + line + ") is expected to contain 2 tokens.");
+ }
+ room.setCode(lineTokens[0]);
+ room.setCapacity(Integer.parseInt(lineTokens[1]));
+ roomList.add(room);
+ }
+ schedule.setRoomList(roomList);
+ }
+
+ private Map<List<Integer>, Period> createPeriodListAndDayListAndTimeslotList(
+ CurriculumCourseSchedule schedule, int dayListSize, int timeslotListSize) throws IOException {
+ int periodListSize = dayListSize * timeslotListSize;
+ Map<List<Integer>, Period> periodMap = new HashMap<List<Integer>, Period>(periodListSize);
+ List<Day> dayList = new ArrayList<Day>(dayListSize);
+ for (int i = 0; i < dayListSize; i++) {
+ Day day = new Day();
+ day.setId((long) i);
+ day.setDayIndex(i);
+ dayList.add(day);
+ }
+ schedule.setDayList(dayList);
+ List<Timeslot> timeslotList = new ArrayList<Timeslot>(timeslotListSize);
+ for (int i = 0; i < timeslotListSize; i++) {
+ Timeslot timeslot = new Timeslot();
+ timeslot.setId((long) i);
+ timeslot.setTimeslotIndex(i);
+ timeslotList.add(timeslot);
+ }
+ schedule.setTimeslotList(timeslotList);
+ List<Period> periodList = new ArrayList<Period>(periodListSize);
+ for (int i = 0; i < dayListSize; i++) {
+ for (int j = 0; j < timeslotListSize; j++) {
+ Period period = new Period();
+ period.setId((long) (i * timeslotListSize + j));
+ period.setDay(dayList.get(i));
+ period.setTimeslot(timeslotList.get(j));
+ periodList.add(period);
+ periodMap.put(Arrays.asList(i, j), period);
+ }
+ }
+ schedule.setPeriodList(periodList);
+ return periodMap;
+ }
+
+ private void readCurriculumList(CurriculumCourseSchedule schedule,
+ Map<String, Course> courseMap, int curriculumListSize) throws IOException {
+ readHeader("CURRICULA:");
+ List<Curriculum> curriculumList = new ArrayList<Curriculum>(curriculumListSize);
+ for (int i = 0; i < curriculumListSize; i++) {
+ Curriculum curriculum = new Curriculum();
+ curriculum.setId((long) i);
+ // Curricula: <CurriculumID> <# Courses> <MemberID> ... <MemberID>
+ String line = bufferedReader.readLine();
+ String[] lineTokens = line.split(SPLIT_REGEX);
+ if (lineTokens.length < 2) {
+ throw new IllegalArgumentException("Read line (" + line
+ + ") is expected to contain at least 2 tokens.");
+ }
+ curriculum.setCode(lineTokens[0]);
+ int coursesInCurriculum = Integer.parseInt(lineTokens[1]);
+ if (lineTokens.length != (coursesInCurriculum + 2)) {
+ throw new IllegalArgumentException("Read line (" + line + ") is expected to contain "
+ + (coursesInCurriculum + 2) + " tokens.");
+ }
+ for (int j = 2; j < lineTokens.length; j++) {
+ Course course = courseMap.get(lineTokens[j]);
+ if (course == null) {
+ throw new IllegalArgumentException("Read line (" + line + ") uses an unexisting course("
+ + lineTokens[j] + ").");
+ }
+ course.getCurriculumList().add(curriculum);
+ }
+ curriculumList.add(curriculum);
+ }
+ schedule.setCurriculumList(curriculumList);
+ }
+
+ private void readUnavailablePeriodConstraintList(CurriculumCourseSchedule schedule,
+ Map<String, Course> courseMap, Map<List<Integer>, Period> periodMap, int unavailablePeriodConstraintListSize)
+ throws IOException {
+ readHeader("UNAVAILABILITY_CONSTRAINTS:");
+ List<UnavailablePeriodConstraint> constraintList = new ArrayList<UnavailablePeriodConstraint>(
+ unavailablePeriodConstraintListSize);
+ for (int i = 0; i < unavailablePeriodConstraintListSize; i++) {
+ UnavailablePeriodConstraint constraint = new UnavailablePeriodConstraint();
+ constraint.setId((long) i);
+ // Unavailability_Constraints: <CourseID> <Day> <Day_Period>
+ String line = bufferedReader.readLine();
+ String[] lineTokens = line.split(SPLIT_REGEX);
+ if (lineTokens.length != 3) {
+ throw new IllegalArgumentException("Read line (" + line + ") is expected to contain 3 tokens.");
+ }
+ constraint.setCourse(courseMap.get(lineTokens[0]));
+ int dayIndex = Integer.parseInt(lineTokens[1]);
+ int timeslotIndex = Integer.parseInt(lineTokens[2]);
+ Period period = periodMap.get(Arrays.asList(dayIndex, timeslotIndex));
+ if (period == null) {
+ throw new IllegalArgumentException("Read line (" + line + ") uses an unexisting period("
+ + dayIndex + " " + timeslotIndex + ").");
+ }
+ constraint.setPeriod(period);
+ constraintList.add(constraint);
+ }
+ schedule.setUnavailablePeriodConstraintList(constraintList);
+ }
+
+ private String readParam(String key) throws IOException {
+ String line = bufferedReader.readLine();
+ String[] lineTokens = line.split(SPLIT_REGEX);
+ if (lineTokens.length != 2 || !lineTokens[0].equals(key)) {
+ throw new IllegalArgumentException("Read line (" + line + ") is expected to contain 2 tokens"
+ + " and start with \"" + key + "\".");
+ }
+ return lineTokens[1];
+ }
+
+ private void readHeader(String header) throws IOException {
+ String line = bufferedReader.readLine();
+ if (line.length() != 0) {
+ throw new IllegalArgumentException("Read line (" + line + ") is expected to be empty"
+ + " and be followed with a line \"" + header + "\".");
+ }
+ line = bufferedReader.readLine();
+ if (!line.equals(header)) {
+ throw new IllegalArgumentException("Read line (" + line + ") is expected to be \"" + header + "\".");
+ }
+ }
+
+ }
+
+}
Deleted: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseInputConvertor.java
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseInputConvertor.java 2010-03-10 20:15:05 UTC (rev 32025)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseInputConvertor.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -1,275 +0,0 @@
-package org.drools.planner.examples.curriculumcourse.persistence;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.drools.planner.examples.common.persistence.AbstractInputConvertor;
-import org.drools.planner.examples.curriculumcourse.domain.Course;
-import org.drools.planner.examples.curriculumcourse.domain.Curriculum;
-import org.drools.planner.examples.curriculumcourse.domain.CurriculumCourseSchedule;
-import org.drools.planner.examples.curriculumcourse.domain.Day;
-import org.drools.planner.examples.curriculumcourse.domain.Period;
-import org.drools.planner.examples.curriculumcourse.domain.Room;
-import org.drools.planner.examples.curriculumcourse.domain.Teacher;
-import org.drools.planner.examples.curriculumcourse.domain.Timeslot;
-import org.drools.planner.examples.curriculumcourse.domain.UnavailablePeriodConstraint;
-import org.drools.planner.core.solution.Solution;
-
-/**
- * @author Geoffrey De Smet
- */
-public class CurriculumCourseInputConvertor extends AbstractInputConvertor {
-
- private static final String INPUT_FILE_SUFFIX = ".ctt";
- private static final String SPLIT_REGEX = "[\\ \\t]+";
-
- public static void main(String[] args) {
- new CurriculumCourseInputConvertor().convertAll();
- }
-
- public CurriculumCourseInputConvertor() {
- super(new CurriculumCourseDaoImpl());
- }
-
- @Override
- protected String getInputFileSuffix() {
- return INPUT_FILE_SUFFIX;
- }
-
- public InputBuilder createInputBuilder() {
- return new CurriculumCourseInputBuilder();
- }
-
- public class CurriculumCourseInputBuilder extends InputBuilder {
-
- public Solution readSolution() throws IOException {
- CurriculumCourseSchedule schedule = new CurriculumCourseSchedule();
- schedule.setId(0L);
- // Name: ToyExample
- schedule.setName(readParam("Name:"));
- // Courses: 4
- int courseListSize = Integer.parseInt(readParam("Courses:"));
- // Rooms: 2
- int roomListSize = Integer.parseInt(readParam("Rooms:"));
- // Days: 5
- int dayListSize = Integer.parseInt(readParam("Days:"));
- // Periods_per_day: 4
- int timeslotListSize = Integer.parseInt(readParam("Periods_per_day:"));
- // Curricula: 2
- int curriculumListSize = Integer.parseInt(readParam("Curricula:"));
- // Constraints: 8
- int unavailablePeriodConstraintListSize = Integer.parseInt(readParam("Constraints:"));
-
- Map<String, Course> courseMap = readCourseListAndTeacherList(
- schedule, courseListSize);
- readRoomList(
- schedule, roomListSize);
- Map<List<Integer>, Period> periodMap = createPeriodListAndDayListAndTimeslotList(
- schedule, dayListSize, timeslotListSize);
- readCurriculumList(
- schedule, courseMap, curriculumListSize);
- readUnavailablePeriodConstraintList(
- schedule, courseMap, periodMap, unavailablePeriodConstraintListSize);
- readHeader("END.");
-
- logger.info("CurriculumCourseSchedule with {} teachers, {} curricula, {} courses, {} periods, {} rooms" +
- " and {} unavailable period constraints.",
- new Object[]{schedule.getTeacherList().size(),
- schedule.getCurriculumList().size(),
- schedule.getCourseList().size(),
- schedule.getPeriodList().size(),
- schedule.getRoomList().size(),
- schedule.getUnavailablePeriodConstraintList().size()});
-
- // Note: lectureList stays null, that's work for the StartingSolutionInitializer
- return schedule;
- }
-
- private Map<String, Course> readCourseListAndTeacherList(
- CurriculumCourseSchedule schedule, int courseListSize) throws IOException {
- Map<String, Course> courseMap = new HashMap<String, Course>(courseListSize);
- Map<String, Teacher> teacherMap = new HashMap<String, Teacher>();
- List<Course> courseList = new ArrayList<Course>(courseListSize);
- readHeader("COURSES:");
- for (int i = 0; i < courseListSize; i++) {
- Course course = new Course();
- course.setId((long) i);
- // Courses: <CourseID> <Teacher> <# Lectures> <MinWorkingDays> <# Students>
- String line = bufferedReader.readLine();
- String[] lineTokens = line.split(SPLIT_REGEX);
- if (lineTokens.length != 5) {
- throw new IllegalArgumentException("Read line (" + line + ") is expected to contain 4 tokens.");
- }
- course.setCode(lineTokens[0]);
- course.setTeacher(findOrCreateTeacher(teacherMap, lineTokens[1]));
- course.setLectureSize(Integer.parseInt(lineTokens[2]));
- course.setMinWorkingDaySize(Integer.parseInt(lineTokens[3]));
- course.setCurriculumList(new ArrayList<Curriculum>());
- course.setStudentSize(Integer.parseInt(lineTokens[4]));
- courseList.add(course);
- courseMap.put(course.getCode(), course);
- }
- schedule.setCourseList(courseList);
- List<Teacher> teacherList = new ArrayList<Teacher>(teacherMap.values());
- schedule.setTeacherList(teacherList);
- return courseMap;
- }
-
- private Teacher findOrCreateTeacher(Map<String, Teacher> teacherMap, String code) {
- Teacher teacher = teacherMap.get(code);
- if (teacher == null) {
- teacher = new Teacher();
- int id = teacherMap.size();
- teacher.setId((long) id);
- teacher.setCode(code);
- teacherMap.put(code, teacher);
- }
- return teacher;
- }
-
- private void readRoomList(CurriculumCourseSchedule schedule, int roomListSize)
- throws IOException {
- readHeader("ROOMS:");
- List<Room> roomList = new ArrayList<Room>(roomListSize);
- for (int i = 0; i < roomListSize; i++) {
- Room room = new Room();
- room.setId((long) i);
- // Rooms: <RoomID> <Capacity>
- String line = bufferedReader.readLine();
- String[] lineTokens = line.split(SPLIT_REGEX);
- if (lineTokens.length != 2) {
- throw new IllegalArgumentException("Read line (" + line + ") is expected to contain 2 tokens.");
- }
- room.setCode(lineTokens[0]);
- room.setCapacity(Integer.parseInt(lineTokens[1]));
- roomList.add(room);
- }
- schedule.setRoomList(roomList);
- }
-
- private Map<List<Integer>, Period> createPeriodListAndDayListAndTimeslotList(
- CurriculumCourseSchedule schedule, int dayListSize, int timeslotListSize) throws IOException {
- int periodListSize = dayListSize * timeslotListSize;
- Map<List<Integer>, Period> periodMap = new HashMap<List<Integer>, Period>(periodListSize);
- List<Day> dayList = new ArrayList<Day>(dayListSize);
- for (int i = 0; i < dayListSize; i++) {
- Day day = new Day();
- day.setId((long) i);
- day.setDayIndex(i);
- dayList.add(day);
- }
- schedule.setDayList(dayList);
- List<Timeslot> timeslotList = new ArrayList<Timeslot>(timeslotListSize);
- for (int i = 0; i < timeslotListSize; i++) {
- Timeslot timeslot = new Timeslot();
- timeslot.setId((long) i);
- timeslot.setTimeslotIndex(i);
- timeslotList.add(timeslot);
- }
- schedule.setTimeslotList(timeslotList);
- List<Period> periodList = new ArrayList<Period>(periodListSize);
- for (int i = 0; i < dayListSize; i++) {
- for (int j = 0; j < timeslotListSize; j++) {
- Period period = new Period();
- period.setId((long) (i * timeslotListSize + j));
- period.setDay(dayList.get(i));
- period.setTimeslot(timeslotList.get(j));
- periodList.add(period);
- periodMap.put(Arrays.asList(i, j), period);
- }
- }
- schedule.setPeriodList(periodList);
- return periodMap;
- }
-
- private void readCurriculumList(CurriculumCourseSchedule schedule,
- Map<String, Course> courseMap, int curriculumListSize) throws IOException {
- readHeader("CURRICULA:");
- List<Curriculum> curriculumList = new ArrayList<Curriculum>(curriculumListSize);
- for (int i = 0; i < curriculumListSize; i++) {
- Curriculum curriculum = new Curriculum();
- curriculum.setId((long) i);
- // Curricula: <CurriculumID> <# Courses> <MemberID> ... <MemberID>
- String line = bufferedReader.readLine();
- String[] lineTokens = line.split(SPLIT_REGEX);
- if (lineTokens.length < 2) {
- throw new IllegalArgumentException("Read line (" + line
- + ") is expected to contain at least 2 tokens.");
- }
- curriculum.setCode(lineTokens[0]);
- int coursesInCurriculum = Integer.parseInt(lineTokens[1]);
- if (lineTokens.length != (coursesInCurriculum + 2)) {
- throw new IllegalArgumentException("Read line (" + line + ") is expected to contain "
- + (coursesInCurriculum + 2) + " tokens.");
- }
- for (int j = 2; j < lineTokens.length; j++) {
- Course course = courseMap.get(lineTokens[j]);
- if (course == null) {
- throw new IllegalArgumentException("Read line (" + line + ") uses an unexisting course("
- + lineTokens[j] + ").");
- }
- course.getCurriculumList().add(curriculum);
- }
- curriculumList.add(curriculum);
- }
- schedule.setCurriculumList(curriculumList);
- }
-
- private void readUnavailablePeriodConstraintList(CurriculumCourseSchedule schedule,
- Map<String, Course> courseMap, Map<List<Integer>, Period> periodMap, int unavailablePeriodConstraintListSize)
- throws IOException {
- readHeader("UNAVAILABILITY_CONSTRAINTS:");
- List<UnavailablePeriodConstraint> constraintList = new ArrayList<UnavailablePeriodConstraint>(
- unavailablePeriodConstraintListSize);
- for (int i = 0; i < unavailablePeriodConstraintListSize; i++) {
- UnavailablePeriodConstraint constraint = new UnavailablePeriodConstraint();
- constraint.setId((long) i);
- // Unavailability_Constraints: <CourseID> <Day> <Day_Period>
- String line = bufferedReader.readLine();
- String[] lineTokens = line.split(SPLIT_REGEX);
- if (lineTokens.length != 3) {
- throw new IllegalArgumentException("Read line (" + line + ") is expected to contain 3 tokens.");
- }
- constraint.setCourse(courseMap.get(lineTokens[0]));
- int dayIndex = Integer.parseInt(lineTokens[1]);
- int timeslotIndex = Integer.parseInt(lineTokens[2]);
- Period period = periodMap.get(Arrays.asList(dayIndex, timeslotIndex));
- if (period == null) {
- throw new IllegalArgumentException("Read line (" + line + ") uses an unexisting period("
- + dayIndex + " " + timeslotIndex + ").");
- }
- constraint.setPeriod(period);
- constraintList.add(constraint);
- }
- schedule.setUnavailablePeriodConstraintList(constraintList);
- }
-
- private String readParam(String key) throws IOException {
- String line = bufferedReader.readLine();
- String[] lineTokens = line.split(SPLIT_REGEX);
- if (lineTokens.length != 2 || !lineTokens[0].equals(key)) {
- throw new IllegalArgumentException("Read line (" + line + ") is expected to contain 2 tokens"
- + " and start with \"" + key + "\".");
- }
- return lineTokens[1];
- }
-
- private void readHeader(String header) throws IOException {
- String line = bufferedReader.readLine();
- if (line.length() != 0) {
- throw new IllegalArgumentException("Read line (" + line + ") is expected to be empty"
- + " and be followed with a line \"" + header + "\".");
- }
- line = bufferedReader.readLine();
- if (!line.equals(header)) {
- throw new IllegalArgumentException("Read line (" + line + ") is expected to be \"" + header + "\".");
- }
- }
-
- }
-
-}
\ No newline at end of file
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseOutputConverter.java (from rev 32019, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseOutputConvertor.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseOutputConverter.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseOutputConverter.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,52 @@
+package org.drools.planner.examples.curriculumcourse.persistence;
+
+import java.io.IOException;
+
+import org.drools.planner.examples.common.persistence.AbstractTxtOutputConverter;
+import org.drools.planner.examples.curriculumcourse.domain.CurriculumCourseSchedule;
+import org.drools.planner.examples.curriculumcourse.domain.Lecture;
+import org.drools.planner.core.solution.Solution;
+
+/**
+ * @author Geoffrey De Smet
+ */
+public class CurriculumCourseOutputConverter extends AbstractTxtOutputConverter {
+
+ private static final String OUTPUT_FILE_SUFFIX = ".sol";
+
+ public static void main(String[] args) {
+ new CurriculumCourseOutputConverter().convertAll();
+ }
+
+ public CurriculumCourseOutputConverter() {
+ super(new CurriculumCourseDaoImpl());
+ }
+
+ @Override
+ protected String getOutputFileSuffix() {
+ return OUTPUT_FILE_SUFFIX;
+ }
+
+ public TxtOutputBuilder createTxtOutputBuilder() {
+ return new CurriculumCourseOutputBuilder();
+ }
+
+ public class CurriculumCourseOutputBuilder extends TxtOutputBuilder {
+
+ private CurriculumCourseSchedule schedule;
+
+ public void setSolution(Solution solution) {
+ schedule = (CurriculumCourseSchedule) solution;
+ }
+
+ public void writeSolution() throws IOException {
+ for (Lecture lecture : schedule.getLectureList()) {
+ bufferedWriter.write(lecture.getCourse().getCode()
+ + " r" + lecture.getRoom().getCode()
+ + " " + lecture.getPeriod().getDay().getDayIndex()
+ + " " + lecture.getPeriod().getTimeslot().getTimeslotIndex() + "\r\n");
+ }
+ }
+ }
+
+}
Deleted: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseOutputConvertor.java
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseOutputConvertor.java 2010-03-10 20:15:05 UTC (rev 32025)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseOutputConvertor.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -1,52 +0,0 @@
-package org.drools.planner.examples.curriculumcourse.persistence;
-
-import java.io.IOException;
-
-import org.drools.planner.examples.common.persistence.AbstractOutputConvertor;
-import org.drools.planner.examples.curriculumcourse.domain.CurriculumCourseSchedule;
-import org.drools.planner.examples.curriculumcourse.domain.Lecture;
-import org.drools.planner.core.solution.Solution;
-
-/**
- * @author Geoffrey De Smet
- */
-public class CurriculumCourseOutputConvertor extends AbstractOutputConvertor {
-
- private static final String OUTPUT_FILE_SUFFIX = ".sol";
-
- public static void main(String[] args) {
- new CurriculumCourseOutputConvertor().convertAll();
- }
-
- public CurriculumCourseOutputConvertor() {
- super(new CurriculumCourseDaoImpl());
- }
-
- @Override
- protected String getOutputFileSuffix() {
- return OUTPUT_FILE_SUFFIX;
- }
-
- public OutputBuilder createOutputBuilder() {
- return new CurriculumCourseOutputBuilder();
- }
-
- public class CurriculumCourseOutputBuilder extends OutputBuilder {
-
- private CurriculumCourseSchedule schedule;
-
- public void setSolution(Solution solution) {
- schedule = (CurriculumCourseSchedule) solution;
- }
-
- public void writeSolution() throws IOException {
- for (Lecture lecture : schedule.getLectureList()) {
- bufferedWriter.write(lecture.getCourse().getCode()
- + " r" + lecture.getRoom().getCode()
- + " " + lecture.getPeriod().getDay().getDayIndex()
- + " " + lecture.getPeriod().getTimeslot().getTimeslotIndex() + "\r\n");
- }
- }
- }
-
-}
\ No newline at end of file
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationInputConverter.java (from rev 32019, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationInputConvertor.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationInputConverter.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationInputConverter.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,331 @@
+package org.drools.planner.examples.examination.persistence;
+
+import java.io.IOException;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.lang.builder.CompareToBuilder;
+import org.drools.planner.core.solution.Solution;
+import org.drools.planner.examples.common.persistence.AbstractTxtInputConverter;
+import org.drools.planner.examples.examination.domain.Examination;
+import org.drools.planner.examples.examination.domain.InstitutionalWeighting;
+import org.drools.planner.examples.examination.domain.Period;
+import org.drools.planner.examples.examination.domain.PeriodHardConstraint;
+import org.drools.planner.examples.examination.domain.PeriodHardConstraintType;
+import org.drools.planner.examples.examination.domain.Room;
+import org.drools.planner.examples.examination.domain.RoomHardConstraint;
+import org.drools.planner.examples.examination.domain.RoomHardConstraintType;
+import org.drools.planner.examples.examination.domain.Student;
+import org.drools.planner.examples.examination.domain.Topic;
+
+/**
+ * @author Geoffrey De Smet
+ */
+public class ExaminationInputConverter extends AbstractTxtInputConverter {
+
+ private static final String INPUT_FILE_SUFFIX = ".exam";
+ private static final String SPLIT_REGEX = "\\,\\ ?";
+
+ public static void main(String[] args) {
+ new ExaminationInputConverter().convertAll();
+ }
+
+ public ExaminationInputConverter() {
+ super(new ExaminationDaoImpl());
+ }
+
+ @Override
+ protected String getInputFileSuffix() {
+ return INPUT_FILE_SUFFIX;
+ }
+
+ public TxtInputBuilder createTxtInputBuilder() {
+ return new ExaminationInputBuilder();
+ }
+
+ public class ExaminationInputBuilder extends TxtInputBuilder {
+
+ public Solution readSolution() throws IOException {
+ Examination examination = new Examination();
+ examination.setId(0L);
+
+ readTopicListAndStudentList(examination);
+ readPeriodList(examination);
+ readRoomList(examination);
+
+ String line = bufferedReader.readLine();
+ if (!line.equals("[PeriodHardConstraints]")) {
+ throw new IllegalStateException("Read line (" + line
+ + " is not the expected header ([PeriodHardConstraints])");
+ }
+ readPeriodHardConstraintList(examination);
+ readRoomHardConstraintList(examination);
+ readInstitutionalWeighting(examination);
+ tagFrontLoadLargeTopics(examination);
+ tagFrontLoadLastPeriods(examination);
+
+ logger.info("Examination with {} students, {} topics/exams, {} periods, {} rooms, {} period constraints" +
+ " and {} room constraints.",
+ new Object[]{examination.getStudentList().size(), examination.getTopicList().size(),
+ examination.getPeriodList().size(), examination.getRoomList().size(),
+ examination.getPeriodHardConstraintList().size(),
+ examination.getRoomHardConstraintList().size()});
+
+ // Note: examList stays null, that's work for the StartingSolutionInitializer
+ return examination;
+ }
+
+ private void readTopicListAndStudentList(Examination examination) throws IOException {
+ Map<Integer, Student> studentMap = new HashMap<Integer, Student>();
+ int examSize = readHeaderWithNumber("Exams");
+ List<Topic> topicList = new ArrayList<Topic>(examSize);
+ for (int i = 0; i < examSize; i++) {
+ Topic topic = new Topic();
+ topic.setId((long) i);
+ String line = bufferedReader.readLine();
+ String[] lineTokens = line.split(SPLIT_REGEX);
+ topic.setDuration(Integer.parseInt(lineTokens[0]));
+ List<Student> topicStudentList = new ArrayList<Student>(lineTokens.length - 1);
+ for (int j = 1; j < lineTokens.length; j++) {
+ topicStudentList.add(findOrCreateStudent(studentMap, Integer.parseInt(lineTokens[j])));
+ }
+ topic.setStudentList(topicStudentList);
+ topic.setFrontLoadLarge(false);
+ topicList.add(topic);
+ }
+ examination.setTopicList(topicList);
+ List<Student> studentList = new ArrayList<Student>(studentMap.values());
+ examination.setStudentList(studentList);
+ }
+
+ private Student findOrCreateStudent(Map<Integer, Student> studentMap, int id) {
+ Student student = studentMap.get(id);
+ if (student == null) {
+ student = new Student();
+ student.setId((long) id);
+ studentMap.put(id, student);
+ }
+ return student;
+ }
+
+ private void readPeriodList(Examination examination) throws IOException {
+ int periodSize = readHeaderWithNumber("Periods");
+ List<Period> periodList = new ArrayList<Period>(periodSize);
+ // Everything is in the default timezone and the default locale.
+ Calendar calendar = Calendar.getInstance();
+ final DateFormat DATE_FORMAT = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss");
+ int referenceDayOfYear = -1;
+ int referenceYear = -1;
+ for (int i = 0; i < periodSize; i++) {
+ Period period = new Period();
+ period.setId((long) i);
+ String line = bufferedReader.readLine();
+ String[] lineTokens = line.split(SPLIT_REGEX);
+ if (lineTokens.length != 4) {
+ throw new IllegalArgumentException("Read line (" + line + ") is expected to contain 4 tokens.");
+ }
+ String startDateTimeString = lineTokens[0] + " " + lineTokens[1];
+ period.setStartDateTimeString(startDateTimeString);
+ period.setPeriodIndex(i);
+ int dayOfYear;
+ int year;
+ try {
+ calendar.setTime(DATE_FORMAT.parse(startDateTimeString));
+ calendar.get(Calendar.DAY_OF_YEAR);
+ dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
+ year = calendar.get(Calendar.YEAR);
+ } catch (ParseException e) {
+ throw new IllegalArgumentException("Illegal startDateTimeString (" + startDateTimeString + ").", e);
+ }
+ if (referenceDayOfYear < 0) {
+ referenceDayOfYear = dayOfYear;
+ referenceYear = year;
+ }
+ if (year != referenceYear) {
+ // Because the Calendar API in JSE sucks... (java 7 will fix that FINALLY)
+ throw new IllegalStateException("Not yet implemented to handle periods spread over different years...");
+ }
+ int dayIndex = dayOfYear - referenceDayOfYear;
+ if (dayIndex < 0) {
+ throw new IllegalStateException("The periods should be in ascending order.");
+ }
+ period.setDayIndex(dayIndex);
+ period.setDuration(Integer.parseInt(lineTokens[2]));
+ period.setPenalty(Integer.parseInt(lineTokens[3]));
+ periodList.add(period);
+ }
+ examination.setPeriodList(periodList);
+ }
+
+ private void readRoomList(Examination examination) throws IOException {
+ int roomSize = readHeaderWithNumber("Rooms");
+ List<Room> roomList = new ArrayList<Room>(roomSize);
+ for (int i = 0; i < roomSize; i++) {
+ Room room = new Room();
+ room.setId((long) i);
+ String line = bufferedReader.readLine();
+ String[] lineTokens = line.split(SPLIT_REGEX);
+ if (lineTokens.length != 2) {
+ throw new IllegalArgumentException("Read line (" + line + ") is expected to contain 2 tokens.");
+ }
+ room.setCapacity(Integer.parseInt(lineTokens[0]));
+ room.setPenalty(Integer.parseInt(lineTokens[1]));
+ roomList.add(room);
+ }
+ examination.setRoomList(roomList);
+ }
+
+ private void readPeriodHardConstraintList(Examination examination)
+ throws IOException {
+ List<Topic> topicList = examination.getTopicList();
+ List<PeriodHardConstraint> periodHardConstraintList = new ArrayList<PeriodHardConstraint>();
+ String line = bufferedReader.readLine();
+ int id = 0;
+ while (!line.equals("[RoomHardConstraints]")) {
+ String[] lineTokens = line.split(SPLIT_REGEX);
+ PeriodHardConstraint periodHardConstraint = new PeriodHardConstraint();
+ periodHardConstraint.setId((long) id);
+ if (lineTokens.length != 3) {
+ throw new IllegalArgumentException("Read line (" + line + ") is expected to contain 3 tokens.");
+ }
+ Topic leftTopic = topicList.get(Integer.parseInt(lineTokens[0]));
+ periodHardConstraint.setLeftSideTopic(leftTopic);
+ PeriodHardConstraintType periodHardConstraintType = PeriodHardConstraintType.valueOf(lineTokens[1]);
+ periodHardConstraint.setPeriodHardConstraintType(periodHardConstraintType);
+ Topic rightTopic = topicList.get(Integer.parseInt(lineTokens[2]));
+ periodHardConstraint.setRightSideTopic(rightTopic);
+ if (periodHardConstraintType == PeriodHardConstraintType.EXAM_COINCIDENCE) {
+ // It's not specified what happens
+ // when A coincidences with B and B coincidences with C
+ // and when A and C share students (but don't directly coincidence)
+ if (!Collections.disjoint(leftTopic.getStudentList(), rightTopic.getStudentList())) {
+ logger.warn("Filtering out periodHardConstraint (" + periodHardConstraint
+ + ") because the left and right topic share students.");
+ } else {
+ periodHardConstraintList.add(periodHardConstraint);
+ }
+ } else {
+ periodHardConstraintList.add(periodHardConstraint);
+ }
+ line = bufferedReader.readLine();
+ id++;
+ }
+ examination.setPeriodHardConstraintList(periodHardConstraintList);
+ }
+
+ private void readRoomHardConstraintList(Examination examination)
+ throws IOException {
+ List<Topic> topicList = examination.getTopicList();
+ List<RoomHardConstraint> roomHardConstraintList = new ArrayList<RoomHardConstraint>();
+ String line = bufferedReader.readLine();
+ int id = 0;
+ while (!line.equals("[InstitutionalWeightings]")) {
+ String[] lineTokens = line.split(SPLIT_REGEX);
+ RoomHardConstraint roomHardConstraint = new RoomHardConstraint();
+ roomHardConstraint.setId((long) id);
+ if (lineTokens.length != 2) {
+ throw new IllegalArgumentException("Read line (" + line + ") is expected to contain 3 tokens.");
+ }
+ roomHardConstraint.setTopic(topicList.get(Integer.parseInt(lineTokens[0])));
+ roomHardConstraint.setRoomHardConstraintType(RoomHardConstraintType.valueOf(lineTokens[1]));
+ roomHardConstraintList.add(roomHardConstraint);
+ line = bufferedReader.readLine();
+ id++;
+ }
+ examination.setRoomHardConstraintList(roomHardConstraintList);
+ }
+
+ private int readHeaderWithNumber(String header) throws IOException {
+ String line = bufferedReader.readLine();
+ if (!line.startsWith("[" + header + ":") || !line.endsWith("]")) {
+ throw new IllegalStateException("Read line (" + line + " is not the expected header (["
+ + header + ":number])");
+ }
+ return Integer.parseInt(line.substring(header.length() + 2, line.length() - 1));
+ }
+
+ private void readInstitutionalWeighting(Examination examination) throws IOException {
+ InstitutionalWeighting institutionalWeighting = new InstitutionalWeighting();
+ institutionalWeighting.setId(0L);
+ String[] lineTokens;
+ lineTokens = readInstitutionalWeightingProperty("TWOINAROW", 2);
+ institutionalWeighting.setTwoInARowPenality(Integer.parseInt(lineTokens[1]));
+ lineTokens = readInstitutionalWeightingProperty("TWOINADAY", 2);
+ institutionalWeighting.setTwoInADayPenality(Integer.parseInt(lineTokens[1]));
+ lineTokens = readInstitutionalWeightingProperty("PERIODSPREAD", 2);
+ institutionalWeighting.setPeriodSpreadLength(Integer.parseInt(lineTokens[1]));
+ institutionalWeighting.setPeriodSpreadPenality(1); // constant
+ lineTokens = readInstitutionalWeightingProperty("NONMIXEDDURATIONS", 2);
+ institutionalWeighting.setMixedDurationPenality(Integer.parseInt(lineTokens[1]));
+ lineTokens = readInstitutionalWeightingProperty("FRONTLOAD", 4);
+ institutionalWeighting.setFrontLoadLargeTopicSize(Integer.parseInt(lineTokens[1]));
+ institutionalWeighting.setFrontLoadLastPeriodSize(Integer.parseInt(lineTokens[2]));
+ institutionalWeighting.setFrontLoadPenality(Integer.parseInt(lineTokens[3]));
+ examination.setInstitutionalWeighting(institutionalWeighting);
+ }
+
+ private String[] readInstitutionalWeightingProperty(String property,
+ int propertySize) throws IOException {
+ String[] lineTokens;
+ lineTokens = bufferedReader.readLine().split(SPLIT_REGEX);
+ if (!lineTokens[0].equals(property) || lineTokens.length != propertySize) {
+ throw new IllegalArgumentException("Read line (" + Arrays.toString(lineTokens)
+ + ") is expected to contain " + propertySize + " tokens and start with " + property + ".");
+ }
+ return lineTokens;
+ }
+
+ private void tagFrontLoadLargeTopics(Examination examination) {
+ List<Topic> sortedTopicList = new ArrayList<Topic>(examination.getTopicList());
+ Collections.sort(sortedTopicList, new Comparator<Topic>() {
+ public int compare(Topic a, Topic b) {
+ return new CompareToBuilder()
+ .append(a.getStudentSize(), b.getStudentSize()) // Ascending
+ .append(b.getId(), a.getId()) // Descending (according to spec)
+ .toComparison();
+ }
+ });
+ int frontLoadLargeTopicSize = examination.getInstitutionalWeighting().getFrontLoadLargeTopicSize();
+ if (frontLoadLargeTopicSize == 0) {
+ return;
+ }
+ int minimumTopicId = sortedTopicList.size() - frontLoadLargeTopicSize;
+ if (minimumTopicId < 0) {
+ logger.warn("The frontLoadLargeTopicSize (" + frontLoadLargeTopicSize + ") is bigger than topicListSize ("
+ + sortedTopicList.size() + "). Tagging all topic as frontLoadLarge...");
+ minimumTopicId = 0;
+ }
+ for (Topic topic : sortedTopicList.subList(minimumTopicId, sortedTopicList.size())) {
+ topic.setFrontLoadLarge(true);
+ }
+ }
+
+ private void tagFrontLoadLastPeriods(Examination examination) {
+ List<Period> periodList = examination.getPeriodList();
+ int frontLoadLastPeriodSize = examination.getInstitutionalWeighting().getFrontLoadLastPeriodSize();
+ if (frontLoadLastPeriodSize == 0) {
+ return;
+ }
+ int minimumPeriodId = periodList.size() - frontLoadLastPeriodSize;
+ if (minimumPeriodId < 0) {
+ logger.warn("The frontLoadLastPeriodSize (" + frontLoadLastPeriodSize + ") is bigger than periodListSize ("
+ + periodList.size() + "). Tagging all periods as frontLoadLast...");
+ minimumPeriodId = 0;
+ }
+ for (Period period : periodList.subList(minimumPeriodId, periodList.size())) {
+ period.setFrontLoadLast(true);
+ }
+ }
+
+ }
+
+}
Deleted: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationInputConvertor.java
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationInputConvertor.java 2010-03-10 20:15:05 UTC (rev 32025)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationInputConvertor.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -1,331 +0,0 @@
-package org.drools.planner.examples.examination.persistence;
-
-import java.io.IOException;
-import java.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.lang.builder.CompareToBuilder;
-import org.drools.planner.core.solution.Solution;
-import org.drools.planner.examples.common.persistence.AbstractInputConvertor;
-import org.drools.planner.examples.examination.domain.Examination;
-import org.drools.planner.examples.examination.domain.InstitutionalWeighting;
-import org.drools.planner.examples.examination.domain.Period;
-import org.drools.planner.examples.examination.domain.PeriodHardConstraint;
-import org.drools.planner.examples.examination.domain.PeriodHardConstraintType;
-import org.drools.planner.examples.examination.domain.Room;
-import org.drools.planner.examples.examination.domain.RoomHardConstraint;
-import org.drools.planner.examples.examination.domain.RoomHardConstraintType;
-import org.drools.planner.examples.examination.domain.Student;
-import org.drools.planner.examples.examination.domain.Topic;
-
-/**
- * @author Geoffrey De Smet
- */
-public class ExaminationInputConvertor extends AbstractInputConvertor {
-
- private static final String INPUT_FILE_SUFFIX = ".exam";
- private static final String SPLIT_REGEX = "\\,\\ ?";
-
- public static void main(String[] args) {
- new ExaminationInputConvertor().convertAll();
- }
-
- public ExaminationInputConvertor() {
- super(new ExaminationDaoImpl());
- }
-
- @Override
- protected String getInputFileSuffix() {
- return INPUT_FILE_SUFFIX;
- }
-
- public InputBuilder createInputBuilder() {
- return new ExaminationInputBuilder();
- }
-
- public class ExaminationInputBuilder extends InputBuilder {
-
- public Solution readSolution() throws IOException {
- Examination examination = new Examination();
- examination.setId(0L);
-
- readTopicListAndStudentList(examination);
- readPeriodList(examination);
- readRoomList(examination);
-
- String line = bufferedReader.readLine();
- if (!line.equals("[PeriodHardConstraints]")) {
- throw new IllegalStateException("Read line (" + line
- + " is not the expected header ([PeriodHardConstraints])");
- }
- readPeriodHardConstraintList(examination);
- readRoomHardConstraintList(examination);
- readInstitutionalWeighting(examination);
- tagFrontLoadLargeTopics(examination);
- tagFrontLoadLastPeriods(examination);
-
- logger.info("Examination with {} students, {} topics/exams, {} periods, {} rooms, {} period constraints" +
- " and {} room constraints.",
- new Object[]{examination.getStudentList().size(), examination.getTopicList().size(),
- examination.getPeriodList().size(), examination.getRoomList().size(),
- examination.getPeriodHardConstraintList().size(),
- examination.getRoomHardConstraintList().size()});
-
- // Note: examList stays null, that's work for the StartingSolutionInitializer
- return examination;
- }
-
- private void readTopicListAndStudentList(Examination examination) throws IOException {
- Map<Integer, Student> studentMap = new HashMap<Integer, Student>();
- int examSize = readHeaderWithNumber("Exams");
- List<Topic> topicList = new ArrayList<Topic>(examSize);
- for (int i = 0; i < examSize; i++) {
- Topic topic = new Topic();
- topic.setId((long) i);
- String line = bufferedReader.readLine();
- String[] lineTokens = line.split(SPLIT_REGEX);
- topic.setDuration(Integer.parseInt(lineTokens[0]));
- List<Student> topicStudentList = new ArrayList<Student>(lineTokens.length - 1);
- for (int j = 1; j < lineTokens.length; j++) {
- topicStudentList.add(findOrCreateStudent(studentMap, Integer.parseInt(lineTokens[j])));
- }
- topic.setStudentList(topicStudentList);
- topic.setFrontLoadLarge(false);
- topicList.add(topic);
- }
- examination.setTopicList(topicList);
- List<Student> studentList = new ArrayList<Student>(studentMap.values());
- examination.setStudentList(studentList);
- }
-
- private Student findOrCreateStudent(Map<Integer, Student> studentMap, int id) {
- Student student = studentMap.get(id);
- if (student == null) {
- student = new Student();
- student.setId((long) id);
- studentMap.put(id, student);
- }
- return student;
- }
-
- private void readPeriodList(Examination examination) throws IOException {
- int periodSize = readHeaderWithNumber("Periods");
- List<Period> periodList = new ArrayList<Period>(periodSize);
- // Everything is in the default timezone and the default locale.
- Calendar calendar = Calendar.getInstance();
- final DateFormat DATE_FORMAT = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss");
- int referenceDayOfYear = -1;
- int referenceYear = -1;
- for (int i = 0; i < periodSize; i++) {
- Period period = new Period();
- period.setId((long) i);
- String line = bufferedReader.readLine();
- String[] lineTokens = line.split(SPLIT_REGEX);
- if (lineTokens.length != 4) {
- throw new IllegalArgumentException("Read line (" + line + ") is expected to contain 4 tokens.");
- }
- String startDateTimeString = lineTokens[0] + " " + lineTokens[1];
- period.setStartDateTimeString(startDateTimeString);
- period.setPeriodIndex(i);
- int dayOfYear;
- int year;
- try {
- calendar.setTime(DATE_FORMAT.parse(startDateTimeString));
- calendar.get(Calendar.DAY_OF_YEAR);
- dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
- year = calendar.get(Calendar.YEAR);
- } catch (ParseException e) {
- throw new IllegalArgumentException("Illegal startDateTimeString (" + startDateTimeString + ").", e);
- }
- if (referenceDayOfYear < 0) {
- referenceDayOfYear = dayOfYear;
- referenceYear = year;
- }
- if (year != referenceYear) {
- // Because the Calendar API in JSE sucks... (java 7 will fix that FINALLY)
- throw new IllegalStateException("Not yet implemented to handle periods spread over different years...");
- }
- int dayIndex = dayOfYear - referenceDayOfYear;
- if (dayIndex < 0) {
- throw new IllegalStateException("The periods should be in ascending order.");
- }
- period.setDayIndex(dayIndex);
- period.setDuration(Integer.parseInt(lineTokens[2]));
- period.setPenalty(Integer.parseInt(lineTokens[3]));
- periodList.add(period);
- }
- examination.setPeriodList(periodList);
- }
-
- private void readRoomList(Examination examination) throws IOException {
- int roomSize = readHeaderWithNumber("Rooms");
- List<Room> roomList = new ArrayList<Room>(roomSize);
- for (int i = 0; i < roomSize; i++) {
- Room room = new Room();
- room.setId((long) i);
- String line = bufferedReader.readLine();
- String[] lineTokens = line.split(SPLIT_REGEX);
- if (lineTokens.length != 2) {
- throw new IllegalArgumentException("Read line (" + line + ") is expected to contain 2 tokens.");
- }
- room.setCapacity(Integer.parseInt(lineTokens[0]));
- room.setPenalty(Integer.parseInt(lineTokens[1]));
- roomList.add(room);
- }
- examination.setRoomList(roomList);
- }
-
- private void readPeriodHardConstraintList(Examination examination)
- throws IOException {
- List<Topic> topicList = examination.getTopicList();
- List<PeriodHardConstraint> periodHardConstraintList = new ArrayList<PeriodHardConstraint>();
- String line = bufferedReader.readLine();
- int id = 0;
- while (!line.equals("[RoomHardConstraints]")) {
- String[] lineTokens = line.split(SPLIT_REGEX);
- PeriodHardConstraint periodHardConstraint = new PeriodHardConstraint();
- periodHardConstraint.setId((long) id);
- if (lineTokens.length != 3) {
- throw new IllegalArgumentException("Read line (" + line + ") is expected to contain 3 tokens.");
- }
- Topic leftTopic = topicList.get(Integer.parseInt(lineTokens[0]));
- periodHardConstraint.setLeftSideTopic(leftTopic);
- PeriodHardConstraintType periodHardConstraintType = PeriodHardConstraintType.valueOf(lineTokens[1]);
- periodHardConstraint.setPeriodHardConstraintType(periodHardConstraintType);
- Topic rightTopic = topicList.get(Integer.parseInt(lineTokens[2]));
- periodHardConstraint.setRightSideTopic(rightTopic);
- if (periodHardConstraintType == PeriodHardConstraintType.EXAM_COINCIDENCE) {
- // It's not specified what happens
- // when A coincidences with B and B coincidences with C
- // and when A and C share students (but don't directly coincidence)
- if (!Collections.disjoint(leftTopic.getStudentList(), rightTopic.getStudentList())) {
- logger.warn("Filtering out periodHardConstraint (" + periodHardConstraint
- + ") because the left and right topic share students.");
- } else {
- periodHardConstraintList.add(periodHardConstraint);
- }
- } else {
- periodHardConstraintList.add(periodHardConstraint);
- }
- line = bufferedReader.readLine();
- id++;
- }
- examination.setPeriodHardConstraintList(periodHardConstraintList);
- }
-
- private void readRoomHardConstraintList(Examination examination)
- throws IOException {
- List<Topic> topicList = examination.getTopicList();
- List<RoomHardConstraint> roomHardConstraintList = new ArrayList<RoomHardConstraint>();
- String line = bufferedReader.readLine();
- int id = 0;
- while (!line.equals("[InstitutionalWeightings]")) {
- String[] lineTokens = line.split(SPLIT_REGEX);
- RoomHardConstraint roomHardConstraint = new RoomHardConstraint();
- roomHardConstraint.setId((long) id);
- if (lineTokens.length != 2) {
- throw new IllegalArgumentException("Read line (" + line + ") is expected to contain 3 tokens.");
- }
- roomHardConstraint.setTopic(topicList.get(Integer.parseInt(lineTokens[0])));
- roomHardConstraint.setRoomHardConstraintType(RoomHardConstraintType.valueOf(lineTokens[1]));
- roomHardConstraintList.add(roomHardConstraint);
- line = bufferedReader.readLine();
- id++;
- }
- examination.setRoomHardConstraintList(roomHardConstraintList);
- }
-
- private int readHeaderWithNumber(String header) throws IOException {
- String line = bufferedReader.readLine();
- if (!line.startsWith("[" + header + ":") || !line.endsWith("]")) {
- throw new IllegalStateException("Read line (" + line + " is not the expected header (["
- + header + ":number])");
- }
- return Integer.parseInt(line.substring(header.length() + 2, line.length() - 1));
- }
-
- private void readInstitutionalWeighting(Examination examination) throws IOException {
- InstitutionalWeighting institutionalWeighting = new InstitutionalWeighting();
- institutionalWeighting.setId(0L);
- String[] lineTokens;
- lineTokens = readInstitutionalWeightingProperty("TWOINAROW", 2);
- institutionalWeighting.setTwoInARowPenality(Integer.parseInt(lineTokens[1]));
- lineTokens = readInstitutionalWeightingProperty("TWOINADAY", 2);
- institutionalWeighting.setTwoInADayPenality(Integer.parseInt(lineTokens[1]));
- lineTokens = readInstitutionalWeightingProperty("PERIODSPREAD", 2);
- institutionalWeighting.setPeriodSpreadLength(Integer.parseInt(lineTokens[1]));
- institutionalWeighting.setPeriodSpreadPenality(1); // constant
- lineTokens = readInstitutionalWeightingProperty("NONMIXEDDURATIONS", 2);
- institutionalWeighting.setMixedDurationPenality(Integer.parseInt(lineTokens[1]));
- lineTokens = readInstitutionalWeightingProperty("FRONTLOAD", 4);
- institutionalWeighting.setFrontLoadLargeTopicSize(Integer.parseInt(lineTokens[1]));
- institutionalWeighting.setFrontLoadLastPeriodSize(Integer.parseInt(lineTokens[2]));
- institutionalWeighting.setFrontLoadPenality(Integer.parseInt(lineTokens[3]));
- examination.setInstitutionalWeighting(institutionalWeighting);
- }
-
- private String[] readInstitutionalWeightingProperty(String property,
- int propertySize) throws IOException {
- String[] lineTokens;
- lineTokens = bufferedReader.readLine().split(SPLIT_REGEX);
- if (!lineTokens[0].equals(property) || lineTokens.length != propertySize) {
- throw new IllegalArgumentException("Read line (" + Arrays.toString(lineTokens)
- + ") is expected to contain " + propertySize + " tokens and start with " + property + ".");
- }
- return lineTokens;
- }
-
- private void tagFrontLoadLargeTopics(Examination examination) {
- List<Topic> sortedTopicList = new ArrayList<Topic>(examination.getTopicList());
- Collections.sort(sortedTopicList, new Comparator<Topic>() {
- public int compare(Topic a, Topic b) {
- return new CompareToBuilder()
- .append(a.getStudentSize(), b.getStudentSize()) // Ascending
- .append(b.getId(), a.getId()) // Descending (according to spec)
- .toComparison();
- }
- });
- int frontLoadLargeTopicSize = examination.getInstitutionalWeighting().getFrontLoadLargeTopicSize();
- if (frontLoadLargeTopicSize == 0) {
- return;
- }
- int minimumTopicId = sortedTopicList.size() - frontLoadLargeTopicSize;
- if (minimumTopicId < 0) {
- logger.warn("The frontLoadLargeTopicSize (" + frontLoadLargeTopicSize + ") is bigger than topicListSize ("
- + sortedTopicList.size() + "). Tagging all topic as frontLoadLarge...");
- minimumTopicId = 0;
- }
- for (Topic topic : sortedTopicList.subList(minimumTopicId, sortedTopicList.size())) {
- topic.setFrontLoadLarge(true);
- }
- }
-
- private void tagFrontLoadLastPeriods(Examination examination) {
- List<Period> periodList = examination.getPeriodList();
- int frontLoadLastPeriodSize = examination.getInstitutionalWeighting().getFrontLoadLastPeriodSize();
- if (frontLoadLastPeriodSize == 0) {
- return;
- }
- int minimumPeriodId = periodList.size() - frontLoadLastPeriodSize;
- if (minimumPeriodId < 0) {
- logger.warn("The frontLoadLastPeriodSize (" + frontLoadLastPeriodSize + ") is bigger than periodListSize ("
- + periodList.size() + "). Tagging all periods as frontLoadLast...");
- minimumPeriodId = 0;
- }
- for (Period period : periodList.subList(minimumPeriodId, periodList.size())) {
- period.setFrontLoadLast(true);
- }
- }
-
- }
-
-}
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationOutputConverter.java (from rev 32019, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationOutputConvertor.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationOutputConverter.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationOutputConverter.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,53 @@
+package org.drools.planner.examples.examination.persistence;
+
+import java.io.IOException;
+import java.util.Collections;
+
+import org.drools.planner.examples.common.domain.PersistableIdComparator;
+import org.drools.planner.examples.common.persistence.AbstractTxtOutputConverter;
+import org.drools.planner.examples.examination.domain.Exam;
+import org.drools.planner.examples.examination.domain.Examination;
+import org.drools.planner.core.solution.Solution;
+
+/**
+ * @author Geoffrey De Smet
+ */
+public class ExaminationOutputConverter extends AbstractTxtOutputConverter {
+
+ private static final String OUTPUT_FILE_SUFFIX = ".sln";
+
+ public static void main(String[] args) {
+ new ExaminationOutputConverter().convertAll();
+ }
+
+ public ExaminationOutputConverter() {
+ super(new ExaminationDaoImpl());
+ }
+
+ @Override
+ protected String getOutputFileSuffix() {
+ return OUTPUT_FILE_SUFFIX;
+ }
+
+ public TxtOutputBuilder createTxtOutputBuilder() {
+ return new ExaminationOutputBuilder();
+ }
+
+ public class ExaminationOutputBuilder extends TxtOutputBuilder {
+
+ private Examination examination;
+
+ public void setSolution(Solution solution) {
+ examination = (Examination) solution;
+ }
+
+ public void writeSolution() throws IOException {
+ Collections.sort(examination.getExamList(), new PersistableIdComparator()); // TODO remove me when obsolete
+ for (Exam exam : examination.getExamList()) {
+ bufferedWriter.write(exam.getPeriod().getId() + ", " + exam.getRoom().getId() + "\r\n");
+ }
+ }
+
+ }
+
+}
Deleted: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationOutputConvertor.java
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationOutputConvertor.java 2010-03-10 20:15:05 UTC (rev 32025)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/persistence/ExaminationOutputConvertor.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -1,53 +0,0 @@
-package org.drools.planner.examples.examination.persistence;
-
-import java.io.IOException;
-import java.util.Collections;
-
-import org.drools.planner.examples.common.domain.PersistableIdComparator;
-import org.drools.planner.examples.common.persistence.AbstractOutputConvertor;
-import org.drools.planner.examples.examination.domain.Exam;
-import org.drools.planner.examples.examination.domain.Examination;
-import org.drools.planner.core.solution.Solution;
-
-/**
- * @author Geoffrey De Smet
- */
-public class ExaminationOutputConvertor extends AbstractOutputConvertor {
-
- private static final String OUTPUT_FILE_SUFFIX = ".sln";
-
- public static void main(String[] args) {
- new ExaminationOutputConvertor().convertAll();
- }
-
- public ExaminationOutputConvertor() {
- super(new ExaminationDaoImpl());
- }
-
- @Override
- protected String getOutputFileSuffix() {
- return OUTPUT_FILE_SUFFIX;
- }
-
- public OutputBuilder createOutputBuilder() {
- return new ExaminationOutputBuilder();
- }
-
- public class ExaminationOutputBuilder extends OutputBuilder {
-
- private Examination examination;
-
- public void setSolution(Solution solution) {
- examination = (Examination) solution;
- }
-
- public void writeSolution() throws IOException {
- Collections.sort(examination.getExamList(), new PersistableIdComparator()); // TODO remove me when obsolete
- for (Exam exam : examination.getExamList()) {
- bufferedWriter.write(exam.getPeriod().getId() + ", " + exam.getRoom().getId() + "\r\n");
- }
- }
-
- }
-
-}
\ No newline at end of file
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/manners2009/persistence/Manners2009InputConverter.java (from rev 32019, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/manners2009/persistence/Manners2009InputConvertor.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/manners2009/persistence/Manners2009InputConverter.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/manners2009/persistence/Manners2009InputConverter.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,150 @@
+package org.drools.planner.examples.manners2009.persistence;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.drools.planner.core.solution.Solution;
+import org.drools.planner.examples.common.persistence.AbstractTxtInputConverter;
+import org.drools.planner.examples.manners2009.domain.Gender;
+import org.drools.planner.examples.manners2009.domain.Guest;
+import org.drools.planner.examples.manners2009.domain.Hobby;
+import org.drools.planner.examples.manners2009.domain.HobbyPractician;
+import org.drools.planner.examples.manners2009.domain.Job;
+import org.drools.planner.examples.manners2009.domain.JobType;
+import org.drools.planner.examples.manners2009.domain.Manners2009;
+import org.drools.planner.examples.manners2009.domain.Seat;
+import org.drools.planner.examples.manners2009.domain.Table;
+
+/**
+ * @author Geoffrey De Smet
+ */
+public class Manners2009InputConverter extends AbstractTxtInputConverter {
+
+ public static void main(String[] args) {
+ new Manners2009InputConverter().convertAll();
+ }
+
+ public Manners2009InputConverter() {
+ super(new Manners2009DaoImpl());
+ }
+
+ public TxtInputBuilder createTxtInputBuilder() {
+ return new Manners2009InputBuilder();
+ }
+
+ public class Manners2009InputBuilder extends TxtInputBuilder {
+
+ public Solution readSolution() throws IOException {
+ Manners2009 manners2009 = new Manners2009();
+ manners2009.setId(0L);
+
+ readTableListAndSeatList(manners2009);
+ readJobListGuestListAndHobbyPracticianList(manners2009);
+
+ logger.info("Manners2009 with {} jobs, {} guests, {} hobby practicians, {} tables and {} seats.",
+ new Object[]{manners2009.getJobList().size(),
+ manners2009.getGuestList().size(),
+ manners2009.getHobbyPracticianList().size(),
+ manners2009.getTableList().size(),
+ manners2009.getSeatList().size()});
+
+ return manners2009;
+ }
+
+ private void readTableListAndSeatList(Manners2009 manners2009)
+ throws IOException {
+ int tableListSize = readIntegerValue("Tables:");
+ int seatsPerTable = readIntegerValue("SeatsPerTable:");
+ List<Table> tableList = new ArrayList<Table>(tableListSize);
+ List<Seat> seatList = new ArrayList<Seat>(tableListSize * seatsPerTable);
+ for (int i = 0; i < tableListSize; i++) {
+ Table table = new Table();
+ table.setId((long) i);
+ table.setTableIndex(i);
+ List<Seat> tableSeatList = new ArrayList<Seat>(seatsPerTable);
+ Seat firstSeat = null;
+ Seat previousSeat = null;
+ for (int j = 0; j < seatsPerTable; j++) {
+ Seat seat = new Seat();
+ seat.setId((long) ((i * seatsPerTable) + j));
+ seat.setTable(table);
+ seat.setSeatIndexInTable(j);
+ if (previousSeat != null) {
+ seat.setLeftSeat(previousSeat);
+ previousSeat.setRightSeat(seat);
+ } else {
+ firstSeat = seat;
+ }
+ tableSeatList.add(seat);
+ seatList.add(seat);
+ previousSeat = seat;
+ }
+ firstSeat.setLeftSeat(previousSeat);
+ previousSeat.setRightSeat(firstSeat);
+ table.setSeatList(tableSeatList);
+ tableList.add(table);
+ }
+ manners2009.setTableList(tableList);
+ manners2009.setSeatList(seatList);
+ }
+
+
+ private void readJobListGuestListAndHobbyPracticianList(Manners2009 manners2009)
+ throws IOException {
+ readConstantLine("Num,Profession,SubProf,Gender,Spt1,Spt2,Spt3");
+ readConstantLine("-------------------------------------------");
+ int guestSize = manners2009.getSeatList().size();
+
+ List<Guest> guestList = new ArrayList<Guest>(guestSize);
+ List<HobbyPractician> hobbyPracticianList = new ArrayList<HobbyPractician>(guestSize * 3);
+ Map<String, Job> jobMap = new HashMap<String, Job>(JobType.values().length * 5);
+ int jobNextId = 0;
+ int hobbyPracticianJobId = 0;
+ for (int i = 0; i < guestSize; i++) {
+ Guest guest = new Guest();
+ guest.setId((long) i);
+ String line = bufferedReader.readLine();
+ String[] lineTokens = line.split("\\,");
+ if (lineTokens.length < 5) {
+ throw new IllegalArgumentException("Read line (" + line
+ + ") is expected to contain at least 5 tokens.");
+ }
+ guest.setCode(lineTokens[0].trim());
+ JobType jobType = JobType.valueOfCode(lineTokens[1].trim());
+ String jobName = lineTokens[2].trim();
+ String jobMapKey = jobType + "/" + jobName;
+ Job job = jobMap.get(jobMapKey);
+ if (job == null) {
+ job = new Job();
+ job.setId((long) jobNextId);
+ jobNextId++;
+ job.setJobType(jobType);
+ job.setName(jobName);
+ jobMap.put(jobMapKey, job);
+ }
+ guest.setJob(job);
+ guest.setGender(Gender.valueOfCode(lineTokens[3].trim()));
+ List<HobbyPractician> hobbyPracticianOfGuestList = new ArrayList<HobbyPractician>(lineTokens.length - 4);
+ for (int j = 4; j < lineTokens.length; j++) {
+ HobbyPractician hobbyPractician = new HobbyPractician();
+ hobbyPractician.setId((long) hobbyPracticianJobId);
+ hobbyPracticianJobId++;
+ hobbyPractician.setGuest(guest);
+ hobbyPractician.setHobby(Hobby.valueOfCode(lineTokens[j].trim()));
+ hobbyPracticianOfGuestList.add(hobbyPractician);
+ hobbyPracticianList.add(hobbyPractician);
+ }
+ guest.setHobbyPracticianList(hobbyPracticianOfGuestList);
+ guestList.add(guest);
+ }
+ manners2009.setJobList(new ArrayList<Job>(jobMap.values()));
+ manners2009.setGuestList(guestList);
+ manners2009.setHobbyPracticianList(hobbyPracticianList);
+ }
+
+ }
+
+}
Deleted: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/manners2009/persistence/Manners2009InputConvertor.java
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/manners2009/persistence/Manners2009InputConvertor.java 2010-03-10 20:15:05 UTC (rev 32025)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/manners2009/persistence/Manners2009InputConvertor.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -1,151 +0,0 @@
-package org.drools.planner.examples.manners2009.persistence;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.drools.planner.core.solution.Solution;
-import org.drools.planner.examples.common.persistence.AbstractInputConvertor;
-import org.drools.planner.examples.common.persistence.SolutionDao;
-import org.drools.planner.examples.manners2009.domain.Gender;
-import org.drools.planner.examples.manners2009.domain.Guest;
-import org.drools.planner.examples.manners2009.domain.Hobby;
-import org.drools.planner.examples.manners2009.domain.HobbyPractician;
-import org.drools.planner.examples.manners2009.domain.Job;
-import org.drools.planner.examples.manners2009.domain.JobType;
-import org.drools.planner.examples.manners2009.domain.Manners2009;
-import org.drools.planner.examples.manners2009.domain.Seat;
-import org.drools.planner.examples.manners2009.domain.Table;
-
-/**
- * @author Geoffrey De Smet
- */
-public class Manners2009InputConvertor extends AbstractInputConvertor {
-
- public static void main(String[] args) {
- new Manners2009InputConvertor().convertAll();
- }
-
- public Manners2009InputConvertor() {
- super(new Manners2009DaoImpl());
- }
-
- public InputBuilder createInputBuilder() {
- return new Manners2009InputBuilder();
- }
-
- public class Manners2009InputBuilder extends InputBuilder {
-
- public Solution readSolution() throws IOException {
- Manners2009 manners2009 = new Manners2009();
- manners2009.setId(0L);
-
- readTableListAndSeatList(manners2009);
- readJobListGuestListAndHobbyPracticianList(manners2009);
-
- logger.info("Manners2009 with {} jobs, {} guests, {} hobby practicians, {} tables and {} seats.",
- new Object[]{manners2009.getJobList().size(),
- manners2009.getGuestList().size(),
- manners2009.getHobbyPracticianList().size(),
- manners2009.getTableList().size(),
- manners2009.getSeatList().size()});
-
- return manners2009;
- }
-
- private void readTableListAndSeatList(Manners2009 manners2009)
- throws IOException {
- int tableListSize = readIntegerValue("Tables:");
- int seatsPerTable = readIntegerValue("SeatsPerTable:");
- List<Table> tableList = new ArrayList<Table>(tableListSize);
- List<Seat> seatList = new ArrayList<Seat>(tableListSize * seatsPerTable);
- for (int i = 0; i < tableListSize; i++) {
- Table table = new Table();
- table.setId((long) i);
- table.setTableIndex(i);
- List<Seat> tableSeatList = new ArrayList<Seat>(seatsPerTable);
- Seat firstSeat = null;
- Seat previousSeat = null;
- for (int j = 0; j < seatsPerTable; j++) {
- Seat seat = new Seat();
- seat.setId((long) ((i * seatsPerTable) + j));
- seat.setTable(table);
- seat.setSeatIndexInTable(j);
- if (previousSeat != null) {
- seat.setLeftSeat(previousSeat);
- previousSeat.setRightSeat(seat);
- } else {
- firstSeat = seat;
- }
- tableSeatList.add(seat);
- seatList.add(seat);
- previousSeat = seat;
- }
- firstSeat.setLeftSeat(previousSeat);
- previousSeat.setRightSeat(firstSeat);
- table.setSeatList(tableSeatList);
- tableList.add(table);
- }
- manners2009.setTableList(tableList);
- manners2009.setSeatList(seatList);
- }
-
-
- private void readJobListGuestListAndHobbyPracticianList(Manners2009 manners2009)
- throws IOException {
- readConstantLine("Num,Profession,SubProf,Gender,Spt1,Spt2,Spt3");
- readConstantLine("-------------------------------------------");
- int guestSize = manners2009.getSeatList().size();
-
- List<Guest> guestList = new ArrayList<Guest>(guestSize);
- List<HobbyPractician> hobbyPracticianList = new ArrayList<HobbyPractician>(guestSize * 3);
- Map<String, Job> jobMap = new HashMap<String, Job>(JobType.values().length * 5);
- int jobNextId = 0;
- int hobbyPracticianJobId = 0;
- for (int i = 0; i < guestSize; i++) {
- Guest guest = new Guest();
- guest.setId((long) i);
- String line = bufferedReader.readLine();
- String[] lineTokens = line.split("\\,");
- if (lineTokens.length < 5) {
- throw new IllegalArgumentException("Read line (" + line
- + ") is expected to contain at least 5 tokens.");
- }
- guest.setCode(lineTokens[0].trim());
- JobType jobType = JobType.valueOfCode(lineTokens[1].trim());
- String jobName = lineTokens[2].trim();
- String jobMapKey = jobType + "/" + jobName;
- Job job = jobMap.get(jobMapKey);
- if (job == null) {
- job = new Job();
- job.setId((long) jobNextId);
- jobNextId++;
- job.setJobType(jobType);
- job.setName(jobName);
- jobMap.put(jobMapKey, job);
- }
- guest.setJob(job);
- guest.setGender(Gender.valueOfCode(lineTokens[3].trim()));
- List<HobbyPractician> hobbyPracticianOfGuestList = new ArrayList<HobbyPractician>(lineTokens.length - 4);
- for (int j = 4; j < lineTokens.length; j++) {
- HobbyPractician hobbyPractician = new HobbyPractician();
- hobbyPractician.setId((long) hobbyPracticianJobId);
- hobbyPracticianJobId++;
- hobbyPractician.setGuest(guest);
- hobbyPractician.setHobby(Hobby.valueOfCode(lineTokens[j].trim()));
- hobbyPracticianOfGuestList.add(hobbyPractician);
- hobbyPracticianList.add(hobbyPractician);
- }
- guest.setHobbyPracticianList(hobbyPracticianOfGuestList);
- guestList.add(guest);
- }
- manners2009.setJobList(new ArrayList<Job>(jobMap.values()));
- manners2009.setGuestList(guestList);
- manners2009.setHobbyPracticianList(hobbyPracticianList);
- }
-
- }
-
-}
\ No newline at end of file
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/nurserostering/domain/NurseAssignment.java (from rev 32008, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/domain/Lecture.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/nurserostering/domain/NurseAssignment.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/nurserostering/domain/NurseAssignment.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,141 @@
+package org.drools.planner.examples.nurserostering.domain;
+
+import java.util.List;
+
+import com.thoughtworks.xstream.annotations.XStreamAlias;
+import org.apache.commons.lang.builder.CompareToBuilder;
+import org.apache.commons.lang.builder.EqualsBuilder;
+import org.apache.commons.lang.builder.HashCodeBuilder;
+import org.drools.planner.examples.common.domain.AbstractPersistable;
+import org.drools.planner.examples.curriculumcourse.domain.Course;
+import org.drools.planner.examples.curriculumcourse.domain.Curriculum;
+import org.drools.planner.examples.curriculumcourse.domain.Day;
+import org.drools.planner.examples.curriculumcourse.domain.Period;
+import org.drools.planner.examples.curriculumcourse.domain.Room;
+
+/**
+ * @author Geoffrey De Smet
+ */
+ at XStreamAlias("NurseAssignment")
+public class NurseAssignment extends AbstractPersistable implements Comparable<NurseAssignment> {
+
+// private Course course;
+// private int lectureIndexInCourse;
+//
+// // Changed by moves, between score calculations.
+// private Period period;
+// private Room room;
+//
+// public Course getCourse() {
+// return course;
+// }
+//
+// public void setCourse(Course course) {
+// this.course = course;
+// }
+//
+// public int getLectureIndexInCourse() {
+// return lectureIndexInCourse;
+// }
+//
+// public void setLectureIndexInCourse(int lectureIndexInCourse) {
+// this.lectureIndexInCourse = lectureIndexInCourse;
+// }
+//
+// public Period getPeriod() {
+// return period;
+// }
+//
+// public void setPeriod(Period period) {
+// this.period = period;
+// }
+//
+// public Room getRoom() {
+// return room;
+// }
+//
+// public void setRoom(Room room) {
+// this.room = room;
+// }
+//
+//
+// public String getLabel() {
+// return course + "-" + lectureIndexInCourse;
+// }
+//
+// public int getStudentSize() {
+// return course.getStudentSize();
+// }
+//
+// public List<Curriculum> getCurriculumList() {
+// return course.getCurriculumList();
+// }
+//
+// public Day getDay() {
+// return period.getDay();
+// }
+//
+// public int getTimeslotIndex() {
+// return period.getTimeslot().getTimeslotIndex();
+// }
+
+ public int compareTo(NurseAssignment other) {
+ return new CompareToBuilder()
+// .append(period, other.period)
+// .append(room, other.room)
+// .append(course, other.course)
+ .toComparison();
+ }
+
+ public NurseAssignment clone() {
+ NurseAssignment clone = new NurseAssignment();
+ clone.id = id;
+// clone.course = course;
+// clone.lectureIndexInCourse = lectureIndexInCourse;
+// clone.period = period;
+// clone.room = room;
+ return clone;
+ }
+
+ /**
+ * The normal methods {@link #equals(Object)} and {@link #hashCode()} cannot be used because the rule engine already
+ * requires them (for performance in their original state).
+ * @see #solutionHashCode()
+ */
+ public boolean solutionEquals(Object o) {
+ if (this == o) {
+ return true;
+ } else if (o instanceof NurseAssignment) {
+ NurseAssignment other = (NurseAssignment) o;
+ return new EqualsBuilder()
+ .append(id, other.id)
+// .append(course, other.course)
+// .append(period, other.period)
+// .append(room, other.room)
+ .isEquals();
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * The normal methods {@link #equals(Object)} and {@link #hashCode()} cannot be used because the rule engine already
+ * requires them (for performance in their original state).
+ * @see #solutionEquals(Object)
+ */
+ public int solutionHashCode() {
+ return new HashCodeBuilder()
+ .append(id)
+// .append(course)
+// .append(period)
+// .append(room)
+ .toHashCode();
+ }
+
+ @Override
+ public String toString() {
+ return id.toString();
+// return course + "-" + lectureIndexInCourse + " @ " + period + " + " + room;
+ }
+
+}
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/nurserostering/domain/NurseRoster.java (from rev 32008, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/domain/CurriculumCourseSchedule.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/nurserostering/domain/NurseRoster.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/nurserostering/domain/NurseRoster.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,143 @@
+package org.drools.planner.examples.nurserostering.domain;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+
+import com.thoughtworks.xstream.annotations.XStreamAlias;
+import org.apache.commons.lang.builder.HashCodeBuilder;
+import org.drools.planner.core.score.HardAndSoftScore;
+import org.drools.planner.core.score.Score;
+import org.drools.planner.core.solution.Solution;
+import org.drools.planner.examples.common.domain.AbstractPersistable;
+
+/**
+ * @author Geoffrey De Smet
+ */
+ at XStreamAlias("NurseRoster")
+public class NurseRoster extends AbstractPersistable implements Solution {
+
+ private String code;
+
+ private List<Skill> skillList;
+ private List<ShiftType> shiftTypeList;
+
+ private List<NurseAssignment> nurseAssignmentList;
+
+ private HardAndSoftScore score;
+
+ public String getCode() {
+ return code;
+ }
+
+ public void setCode(String code) {
+ this.code = code;
+ }
+
+ public List<Skill> getSkillList() {
+ return skillList;
+ }
+
+ public void setSkillList(List<Skill> skillList) {
+ this.skillList = skillList;
+ }
+
+ public List<ShiftType> getShiftTypeList() {
+ return shiftTypeList;
+ }
+
+ public void setShiftTypeList(List<ShiftType> shiftTypeList) {
+ this.shiftTypeList = shiftTypeList;
+ }
+
+ public List<NurseAssignment> getNurseAssignmentList() {
+ return nurseAssignmentList;
+ }
+
+ public void setNurseAssignmentList(List<NurseAssignment> nurseAssignmentList) {
+ this.nurseAssignmentList = nurseAssignmentList;
+ }
+
+ public HardAndSoftScore getScore() {
+ return score;
+ }
+
+ public void setScore(Score score) {
+ this.score = (HardAndSoftScore) score;
+ }
+
+
+ public boolean isInitialized() {
+ return (nurseAssignmentList != null);
+ }
+
+ public Collection<? extends Object> getFacts() {
+ List<Object> facts = new ArrayList<Object>();
+ facts.add(skillList);
+ facts.addAll(shiftTypeList);
+ // TODO add more properties
+
+
+ if (isInitialized()) {
+ facts.addAll(nurseAssignmentList);
+ }
+ return facts;
+ }
+
+ /**
+ * Clone will only deep copy the nurseAssignmentList
+ */
+ public NurseRoster cloneSolution() {
+ NurseRoster clone = new NurseRoster();
+ clone.id = id;
+ clone.code = code;
+ clone.skillList = skillList;
+ clone.shiftTypeList = shiftTypeList;
+ // TODO add more properties
+
+
+ // deep clone lectures
+ List<NurseAssignment> clonedLectureList = new ArrayList<NurseAssignment>(nurseAssignmentList.size());
+ for (NurseAssignment nurseAssignment : nurseAssignmentList) {
+ NurseAssignment clonedNurseAssignment = nurseAssignment.clone();
+ clonedLectureList.add(clonedNurseAssignment);
+ }
+ clone.nurseAssignmentList = clonedLectureList;
+ clone.score = score;
+ return clone;
+ }
+
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (id == null || !(o instanceof NurseRoster)) {
+ return false;
+ } else {
+ NurseRoster other = (NurseRoster) o;
+ if (nurseAssignmentList.size() != other.nurseAssignmentList.size()) {
+ return false;
+ }
+ for (Iterator<NurseAssignment> it = nurseAssignmentList.iterator(), otherIt = other.nurseAssignmentList.iterator(); it.hasNext();) {
+ NurseAssignment nurseAssignment = it.next();
+ NurseAssignment otherNurseAssignment = otherIt.next();
+ // Notice: we don't use equals()
+ if (!nurseAssignment.solutionEquals(otherNurseAssignment)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+
+ public int hashCode() {
+ HashCodeBuilder hashCodeBuilder = new HashCodeBuilder();
+ for (NurseAssignment nurseAssignment : nurseAssignmentList) {
+ // Notice: we don't use hashCode()
+ hashCodeBuilder.append(nurseAssignment.solutionHashCode());
+ }
+ return hashCodeBuilder.toHashCode();
+ }
+
+}
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/nurserostering/persistence/NurseRosteringDaoImpl.java (from rev 32008, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseDaoImpl.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/nurserostering/persistence/NurseRosteringDaoImpl.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/nurserostering/persistence/NurseRosteringDaoImpl.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,15 @@
+package org.drools.planner.examples.nurserostering.persistence;
+
+import org.drools.planner.examples.common.persistence.XstreamSolutionDaoImpl;
+import org.drools.planner.examples.nurserostering.domain.NurseRoster;
+
+/**
+ * @author Geoffrey De Smet
+ */
+public class NurseRosteringDaoImpl extends XstreamSolutionDaoImpl {
+
+ public NurseRosteringDaoImpl() {
+ super("nurserostering", NurseRoster.class);
+ }
+
+}
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/nurserostering/persistence/NurseRosteringInputConverter.java (from rev 32008, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/persistence/CurriculumCourseInputConvertor.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/nurserostering/persistence/NurseRosteringInputConverter.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/nurserostering/persistence/NurseRosteringInputConverter.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,67 @@
+package org.drools.planner.examples.nurserostering.persistence;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.drools.planner.core.solution.Solution;
+import org.drools.planner.examples.common.persistence.AbstractInputConverter;
+import org.drools.planner.examples.common.persistence.AbstractTxtInputConverter;
+import org.drools.planner.examples.common.persistence.AbstractXmlInputConverter;
+import org.drools.planner.examples.nurserostering.domain.NurseRoster;
+import org.drools.planner.examples.nurserostering.domain.Skill;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * @author Geoffrey De Smet
+ */
+public class NurseRosteringInputConverter extends AbstractXmlInputConverter {
+
+ public static void main(String[] args) {
+ new NurseRosteringInputConverter().convertAll();
+ }
+
+ public NurseRosteringInputConverter() {
+ super(new NurseRosteringDaoImpl());
+ }
+
+ public XmlInputBuilder createXmlInputBuilder() {
+ return new NurseRosteringInputBuilder();
+ }
+
+ public class NurseRosteringInputBuilder extends XmlInputBuilder {
+
+ public Solution readSolution() throws IOException {
+ NurseRoster nurseRoster = new NurseRoster();
+ nurseRoster.setId(0L);
+
+ Node schedulingPeriodNode = document.getChildNodes().item(0);
+ nurseRoster.setCode(schedulingPeriodNode.getAttributes().getNamedItem("ID").getNodeValue());
+ Node skillsNode = schedulingPeriodNode.getChildNodes().item(5);
+ assertNodeName(skillsNode, "Skills");
+ NodeList skillNodeList = skillsNode.getChildNodes();
+ List<Skill> skillList = new ArrayList<Skill>(skillNodeList.getLength());
+ for (int i = 1; i < skillNodeList.getLength(); i += 2) {
+ Node skillNode = skillNodeList.item(i);
+ assertNodeName(skillNode, "Skill");
+ Skill skill = new Skill();
+ skill.setId((long) i);
+ skill.setCode(skillNode.getTextContent());
+ skillList.add(skill);
+ }
+ nurseRoster.setSkillList(skillList);
+
+ return nurseRoster;
+ }
+
+ }
+
+}
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleInputConverter.java (from rev 32019, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleInputConvertor.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleInputConverter.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleInputConverter.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,523 @@
+package org.drools.planner.examples.pas.persistence;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Collections;
+
+import org.drools.planner.core.solution.Solution;
+import org.drools.planner.examples.common.persistence.AbstractTxtInputConverter;
+import org.drools.planner.examples.pas.domain.AdmissionPart;
+import org.drools.planner.examples.pas.domain.Bed;
+import org.drools.planner.examples.pas.domain.Department;
+import org.drools.planner.examples.pas.domain.DepartmentSpecialism;
+import org.drools.planner.examples.pas.domain.Equipment;
+import org.drools.planner.examples.pas.domain.Gender;
+import org.drools.planner.examples.pas.domain.GenderLimitation;
+import org.drools.planner.examples.pas.domain.Night;
+import org.drools.planner.examples.pas.domain.Patient;
+import org.drools.planner.examples.pas.domain.PatientAdmissionSchedule;
+import org.drools.planner.examples.pas.domain.PreferredPatientEquipment;
+import org.drools.planner.examples.pas.domain.RequiredPatientEquipment;
+import org.drools.planner.examples.pas.domain.Room;
+import org.drools.planner.examples.pas.domain.RoomEquipment;
+import org.drools.planner.examples.pas.domain.RoomSpecialism;
+import org.drools.planner.examples.pas.domain.Specialism;
+
+/**
+ * @author Geoffrey De Smet
+ * @author Wim Vancroonenburg
+ */
+public class PatientAdmissionScheduleInputConverter extends AbstractTxtInputConverter {
+
+ public static void main(String[] args) {
+ new PatientAdmissionScheduleInputConverter().convertAll();
+ }
+
+ public PatientAdmissionScheduleInputConverter() {
+ super(new PatientAdmissionScheduleDaoImpl());
+ }
+
+ public TxtInputBuilder createTxtInputBuilder() {
+ return new PatientAdmissionScheduleInputBuilder();
+ }
+
+ public class PatientAdmissionScheduleInputBuilder extends TxtInputBuilder {
+
+ private PatientAdmissionSchedule patientAdmissionSchedule;
+
+ private int specialismListSize;
+ private int departmentListSize;
+ private int equipmentListSize;
+ private int roomListSize;
+ private int bedListSize;
+ private int nightListSize;
+ private int patientListSize;
+
+ private Map<Long, Specialism> idToSpecialismMap = null;
+ private Map<Long, Department> idToDepartmentMap = null;
+ private Map<Integer, Equipment> indexToEquipmentMap = null;
+ private Map<Long, Room> idToRoomMap = null;
+ private Map<Integer, Night> indexToNightMap = null;
+
+ public Solution readSolution() throws IOException {
+ patientAdmissionSchedule = new PatientAdmissionSchedule();
+ patientAdmissionSchedule.setId(0L);
+ readSizes();
+ readEmptyLine();
+ readEmptyLine();
+ readSpecialismList();
+ readEmptyLine();
+ readDepartmentListAndDepartmentSpecialismList();
+ readEmptyLine();
+ readEquipmentList();
+ readEmptyLine();
+ readRoomListAndRoomSpecialismListAndRoomEquipmentList();
+ readEmptyLine();
+ readBedList();
+ readEmptyLine();
+ generateNightList();
+ readPatientListAndAdmissionPartListAndRequiredPatientEquipmentListAndPreferredPatientEquipmentList();
+ readEmptyLine();
+ readConstantLine("END.");
+ // TODO not all nights are planned, only the "planning horizon" nights are planned
+ logger.info("PatientAdmissionSchedule with {} specialisms, {} equipments, {} departments, {} rooms, "
+ + "{} beds, {} nights, {} patients and {} admissions.",
+ new Object[]{patientAdmissionSchedule.getSpecialismList().size(),
+ patientAdmissionSchedule.getEquipmentList().size(),
+ patientAdmissionSchedule.getDepartmentList().size(),
+ patientAdmissionSchedule.getRoomList().size(),
+ patientAdmissionSchedule.getBedList().size(),
+ patientAdmissionSchedule.getNightList().size(),
+ patientAdmissionSchedule.getPatientList().size(),
+ patientAdmissionSchedule.getAdmissionPartList().size()});
+ return patientAdmissionSchedule;
+ }
+
+ private void readSizes() throws IOException {
+ readConstantLine("ARTICLE BENCHMARK DATA SET");
+ roomListSize = readIntegerValue("Rooms:");
+ equipmentListSize = readIntegerValue("Roomproperties:");
+ bedListSize = readIntegerValue("Beds:");
+ departmentListSize = readIntegerValue("Departments:");
+ specialismListSize = readIntegerValue("Specialisms:");
+ patientListSize = readIntegerValue("Patients:");
+ nightListSize = readIntegerValue("Planning horizon:");
+ }
+
+ private void readSpecialismList() throws IOException {
+ readConstantLine("SPECIALISMS:");
+ List<Specialism> specialismList = new ArrayList<Specialism>(specialismListSize);
+ idToSpecialismMap = new HashMap<Long, Specialism>(specialismListSize);
+ for (int i = 0; i < specialismListSize; i++) {
+ String line = bufferedReader.readLine();
+ String[] lineTokens = splitBySpace(line, 2);
+ Specialism specialism = new Specialism();
+ specialism.setId(Long.parseLong(lineTokens[0]));
+ specialism.setName(lineTokens[1]);
+ specialismList.add(specialism);
+ idToSpecialismMap.put(specialism.getId(), specialism);
+ }
+ patientAdmissionSchedule.setSpecialismList(specialismList);
+ }
+
+ private void readDepartmentListAndDepartmentSpecialismList() throws IOException {
+ readConstantLine("DEPARTMENTS:");
+ List<Department> departmentList = new ArrayList<Department>(departmentListSize);
+ idToDepartmentMap = new HashMap<Long, Department>(departmentListSize);
+ List<DepartmentSpecialism> departmentSpecialismList = new ArrayList<DepartmentSpecialism>(
+ departmentListSize * 5);
+ long departmentSpecialismId = 0L;
+ for (int i = 0; i < departmentListSize; i++) {
+ String line = bufferedReader.readLine();
+ String[] lineTokens = splitByPipeline(line, 2);
+
+ String[] departmentTokens = splitBySpace(lineTokens[0], 4);
+ Department department = new Department();
+ department.setId(Long.parseLong(departmentTokens[0]));
+ department.setName(departmentTokens[1]);
+ int minimumAge = Integer.parseInt(departmentTokens[2]);
+ if (minimumAge != 0) {
+ department.setMinimumAge(Integer.valueOf(minimumAge));
+ }
+ int maximumAge = Integer.parseInt(departmentTokens[3]);
+ if (maximumAge != 0) {
+ department.setMaximumAge(Integer.valueOf(maximumAge));
+ }
+ departmentList.add(department);
+ idToDepartmentMap.put(department.getId(), department);
+
+ String[] departmentSpecialismTokens = splitBySpace(lineTokens[1]);
+ if (departmentSpecialismTokens.length % 2 != 0) {
+ throw new IllegalArgumentException("Read line (" + line
+ + ") is expected to contain even number of tokens (" + departmentSpecialismTokens.length
+ + ") after 1st pipeline (|) seperated by a space ( ).");
+ }
+ for (int j = 0; j < departmentSpecialismTokens.length; j += 2) {
+ long specialismId = Long.parseLong(departmentSpecialismTokens[j + 1]);
+ if (specialismId != 0) {
+ DepartmentSpecialism departmentSpecialism = new DepartmentSpecialism();
+ departmentSpecialism.setId(departmentSpecialismId);
+ departmentSpecialism.setDepartment(department);
+ departmentSpecialism.setPriority(Integer.parseInt(departmentSpecialismTokens[j]));
+ Specialism specialism = idToSpecialismMap.get(specialismId);
+ if (specialism == null) {
+ throw new IllegalArgumentException("Read line (" + line
+ + ") has a non existing specialismId (" + specialismId + ").");
+ }
+ departmentSpecialism.setSpecialism(specialism);
+ departmentSpecialismList.add(departmentSpecialism);
+ departmentSpecialismId++;
+ }
+ }
+ }
+ Collections.sort(departmentList);
+ patientAdmissionSchedule.setDepartmentList(departmentList);
+ patientAdmissionSchedule.setDepartmentSpecialismList(departmentSpecialismList);
+ }
+
+ private void readEquipmentList() throws IOException {
+ readConstantLine("ROOMPROPERTIES:");
+ List<Equipment> equipmentList = new ArrayList<Equipment>(equipmentListSize);
+ indexToEquipmentMap = new HashMap<Integer, Equipment>(equipmentListSize);
+ for (int i = 0; i < equipmentListSize; i++) {
+ String line = bufferedReader.readLine();
+ String[] lineTokens = splitBySpace(line, 2);
+ Equipment equipment = new Equipment();
+ equipment.setId(Long.parseLong(lineTokens[0]));
+ equipment.setName(lineTokens[1]);
+ equipmentList.add(equipment);
+ indexToEquipmentMap.put(i, equipment);
+ }
+ patientAdmissionSchedule.setEquipmentList(equipmentList);
+ }
+
+ private void readRoomListAndRoomSpecialismListAndRoomEquipmentList() throws IOException {
+ readConstantLine("ROOMS:");
+ List<Room> roomList = new ArrayList<Room>(roomListSize);
+ idToRoomMap = new HashMap<Long, Room>(roomListSize);
+ List<RoomSpecialism> roomSpecialismList = new ArrayList<RoomSpecialism>(roomListSize * 5);
+ List<RoomEquipment> roomEquipmentList = new ArrayList<RoomEquipment>(roomListSize * 2);
+ long roomSpecialismId = 0L;
+ long roomEquipmentId = 0L;
+ for (int i = 0; i < roomListSize; i++) {
+ String line = bufferedReader.readLine();
+ String[] lineTokens = splitByPipeline(line, 6);
+
+ String[] roomTokens = splitBySpace(lineTokens[0], 2);
+ Room room = new Room();
+ room.setId(Long.parseLong(roomTokens[0]));
+ room.setName(roomTokens[1]);
+ room.setCapacity(Integer.parseInt(lineTokens[1]));
+ room.setDepartment(idToDepartmentMap.get(
+ Long.parseLong(lineTokens[2])));
+ room.setGenderLimitation(GenderLimitation.valueOfCode(lineTokens[3]));
+ roomList.add(room);
+ idToRoomMap.put(room.getId(), room);
+
+ String[] roomSpecialismTokens = splitBySpace(lineTokens[4]);
+ if (roomSpecialismTokens.length % 2 != 0) {
+ throw new IllegalArgumentException("Read line (" + line
+ + ") is expected to contain even number of tokens (" + roomSpecialismTokens.length
+ + ") after 4th pipeline (|) seperated by a space ( ).");
+ }
+ List<RoomSpecialism> roomSpecialismListOfRoom = new ArrayList<RoomSpecialism>(roomSpecialismTokens.length / 2);
+ for (int j = 0; j < roomSpecialismTokens.length; j += 2) {
+ int priority = Integer.parseInt(roomSpecialismTokens[j]);
+ long specialismId = Long.parseLong(roomSpecialismTokens[j + 1]);
+ if (specialismId != 0) {
+ RoomSpecialism roomSpecialism = new RoomSpecialism();
+ roomSpecialism.setId(roomSpecialismId);
+ roomSpecialism.setRoom(room);
+ Specialism specialism = idToSpecialismMap.get(specialismId);
+ if (specialism == null) {
+ throw new IllegalArgumentException("Read line (" + line
+ + ") has a non existing specialismId (" + specialismId + ").");
+ }
+ roomSpecialism.setSpecialism(specialism);
+ roomSpecialism.setPriority(priority);
+ roomSpecialismListOfRoom.add(roomSpecialism);
+ roomSpecialismList.add(roomSpecialism);
+ roomSpecialismId++;
+ }
+ }
+ room.setRoomSpecialismList(roomSpecialismListOfRoom);
+
+ List<RoomEquipment> roomEquipmentListOfRoom = new ArrayList<RoomEquipment>(equipmentListSize);
+ String[] roomEquipmentTokens = splitBySpace(lineTokens[5]);
+ if (roomEquipmentTokens.length != equipmentListSize) {
+ throw new IllegalArgumentException("Read line (" + line
+ + ") is expected to contain equal number of tokens (" + roomEquipmentTokens.length
+ + ") as equipmentListSize (" + equipmentListSize + ") after 5th pipeline (|).");
+ }
+ for (int j = 0; j < roomEquipmentTokens.length; j++) {
+ int hasEquipment = Integer.parseInt(roomEquipmentTokens[j]);
+ if (hasEquipment == 1) {
+ RoomEquipment roomEquipment = new RoomEquipment();
+ roomEquipment.setId(roomEquipmentId);
+ roomEquipment.setRoom(room);
+ roomEquipment.setEquipment(indexToEquipmentMap.get(j));
+ roomEquipmentListOfRoom.add(roomEquipment);
+ roomEquipmentList.add(roomEquipment);
+ roomEquipmentId++;
+ } else if (hasEquipment != 0) {
+ throw new IllegalArgumentException("Read line (" + line
+ + ") is expected to have 0 or 1 hasEquipment (" + hasEquipment + ").");
+ }
+ }
+ room.setRoomEquipmentList(roomEquipmentListOfRoom);
+ }
+ Collections.sort(roomList);
+ patientAdmissionSchedule.setRoomList(roomList);
+ patientAdmissionSchedule.setRoomSpecialismList(roomSpecialismList);
+ patientAdmissionSchedule.setRoomEquipmentList(roomEquipmentList);
+ }
+
+ private void readBedList() throws IOException {
+ readConstantLine("BEDS:");
+ List<Bed> bedList = new ArrayList<Bed>(bedListSize);
+ Map<Room, Integer> roomToLastIndexInRoomMap = new HashMap<Room, Integer>(roomListSize);
+ for (int i = 0; i < bedListSize; i++) {
+ String line = bufferedReader.readLine();
+ String[] lineTokens = splitBySpace(line, 2);
+ Bed bed = new Bed();
+ bed.setId(Long.parseLong(lineTokens[0]));
+ Room room = idToRoomMap.get(Long.parseLong(lineTokens[1]));
+ bed.setRoom(room);
+ Integer indexInRoom = roomToLastIndexInRoomMap.get(room);
+ if (indexInRoom == null) {
+ indexInRoom = 0;
+ } else {
+ indexInRoom++;
+ }
+ bed.setIndexInRoom(indexInRoom);
+ roomToLastIndexInRoomMap.put(room, indexInRoom);
+ bedList.add(bed);
+ }
+ Collections.sort(bedList);
+ patientAdmissionSchedule.setBedList(bedList);
+ }
+
+ private void generateNightList() {
+ List<Night> nightList = new ArrayList<Night>(nightListSize);
+ indexToNightMap = new HashMap<Integer, Night>(nightListSize);
+ long nightId = 0L;
+ for (int i = 0; i < nightListSize; i++) {
+ Night night = new Night();
+ night.setId(nightId);
+ night.setIndex(i);
+ nightList.add(night);
+ indexToNightMap.put(i, night);
+ nightId++;
+ }
+ patientAdmissionSchedule.setNightList(nightList);
+ }
+
+ private void readPatientListAndAdmissionPartListAndRequiredPatientEquipmentListAndPreferredPatientEquipmentList() throws IOException {
+ readConstantLine("PATIENTS:");
+ List<Patient> patientList = new ArrayList<Patient>(patientListSize);
+ List<AdmissionPart> admissionPartList = new ArrayList<AdmissionPart>(patientListSize);
+ List<RequiredPatientEquipment> requiredPatientEquipmentList = new ArrayList<RequiredPatientEquipment>(patientListSize * equipmentListSize);
+ List<PreferredPatientEquipment> preferredPatientEquipmentList = new ArrayList<PreferredPatientEquipment>(patientListSize * equipmentListSize);
+ long admissionPartId = 0L;
+ long requiredPatientEquipmentId = 0L;
+ long preferredPatientEquipmentId = 0L;
+ for (int i = 0; i < patientListSize; i++) {
+ String line = bufferedReader.readLine();
+ String[] lineTokens = splitByPipeline(line, 6);
+
+ String[] nightTokens = splitBySpace(lineTokens[1], 2);
+ int firstNightIndex = Integer.parseInt(nightTokens[0]);
+ int lastNightIndex = Integer.parseInt(nightTokens[1]);
+ int patientNightListSize = lastNightIndex - firstNightIndex;
+ // A patient with no nights in the planning horizon or no nights at all is ignored
+ if (firstNightIndex >= nightListSize || patientNightListSize == 0) {
+ continue;
+ }
+
+ String[] patientTokens = splitBySpace(lineTokens[0], 4);
+ Patient patient = new Patient();
+ patient.setId(Long.parseLong(patientTokens[0]));
+ patient.setName(patientTokens[1]);
+ patient.setAge(Integer.parseInt(patientTokens[2]));
+ patient.setGender(Gender.valueOfCode(patientTokens[3]));
+ int preferredMaximumRoomCapacity = Integer.parseInt(lineTokens[3]);
+ patient.setPreferredMaximumRoomCapacity(preferredMaximumRoomCapacity == 0
+ ? null : preferredMaximumRoomCapacity);
+ patientList.add(patient);
+
+ String[] admissionPartTokens = splitBySpace(lineTokens[2]);
+ if (admissionPartTokens.length % 2 != 1) {
+ }
+ int patientAdmissionPartListSize = Integer.parseInt(admissionPartTokens[0]);
+ if (admissionPartTokens.length != ((patientAdmissionPartListSize * 2) + 1)) {
+ throw new IllegalArgumentException("Read line (" + line
+ + ") is expected to contain " + ((patientAdmissionPartListSize * 2) + 1)
+ + " number of tokens after 2th pipeline (|).");
+ }
+ int nextFirstNightIndex = firstNightIndex;
+ for (int j = 1; j < admissionPartTokens.length; j += 2) {
+ long specialismId = Long.parseLong(admissionPartTokens[j]);
+ int admissionPartNightListSize = Integer.parseInt(admissionPartTokens[j + 1]);
+ if (nextFirstNightIndex >= nightListSize || admissionPartNightListSize == 0) {
+ nextFirstNightIndex += admissionPartNightListSize;
+ continue;
+ }
+ AdmissionPart admissionPart = new AdmissionPart();
+ admissionPart.setId(admissionPartId);
+ admissionPart.setPatient(patient);
+ Specialism specialism = (specialismId == 0) ? null : idToSpecialismMap.get(specialismId);
+ if (specialism == null) {
+ throw new IllegalArgumentException("Read line (" + line
+ + ") has a non existing specialismId (" + specialismId + ").");
+ }
+ admissionPart.setSpecialism(specialism);
+ int admissionPartFirstNightIndex = nextFirstNightIndex;
+ Night admissionPartFirstNight = indexToNightMap.get(admissionPartFirstNightIndex);
+ if (admissionPartFirstNight == null) {
+ throw new IllegalStateException(
+ "The admissionPartFirstNight was not found for admissionPartFirstNightIndex("
+ + admissionPartFirstNightIndex + ").");
+ }
+ admissionPart.setFirstNight(admissionPartFirstNight);
+ int admissionPartLastNightIndex = nextFirstNightIndex + admissionPartNightListSize - 1;
+ // TODO Instead of ensureEnoughNights(lastNightIndex);
+ // the official score function ignores any broken constraints after the planning horizon
+ if (admissionPartLastNightIndex >= nightListSize) {
+ admissionPartLastNightIndex = nightListSize - 1;
+ }
+ Night admissionPartLastNight = indexToNightMap.get(admissionPartLastNightIndex);
+ if (admissionPartLastNight == null) {
+ throw new IllegalStateException(
+ "The admissionPartLastNight was not found for admissionPartLastNightIndex("
+ + admissionPartLastNightIndex + ").");
+ }
+ admissionPart.setLastNight(admissionPartLastNight);
+ admissionPartList.add(admissionPart);
+ admissionPartId++;
+ nextFirstNightIndex += admissionPartNightListSize;
+ }
+ int admissionPartNightListSizeSum = nextFirstNightIndex - firstNightIndex;
+ if (patientNightListSize != admissionPartNightListSizeSum) {
+ throw new IllegalArgumentException("Read line (" + line
+ + ") has patientNightListSize (" + patientNightListSize
+ + ") different from admissionPartNightListSizeSum(" + admissionPartNightListSizeSum + ")");
+ }
+
+ String[] requiredPatientEquipmentTokens = splitBySpace(lineTokens[4]);
+ if (requiredPatientEquipmentTokens.length != equipmentListSize) {
+ throw new IllegalArgumentException("Read line (" + line
+ + ") is expected to contain equal number of tokens ("
+ + requiredPatientEquipmentTokens.length
+ + ") as equipmentListSize (" + equipmentListSize + ") after 4th pipeline (|).");
+ }
+ List<RequiredPatientEquipment> requiredPatientEquipmentOfPatientList
+ = new ArrayList<RequiredPatientEquipment>(equipmentListSize);
+ for (int j = 0; j < requiredPatientEquipmentTokens.length; j++) {
+ int hasEquipment = Integer.parseInt(requiredPatientEquipmentTokens[j]);
+ if (hasEquipment == 1) {
+ RequiredPatientEquipment requiredPatientEquipment = new RequiredPatientEquipment();
+ requiredPatientEquipment.setId(requiredPatientEquipmentId);
+ requiredPatientEquipment.setPatient(patient);
+ requiredPatientEquipment.setEquipment(indexToEquipmentMap.get(j));
+ requiredPatientEquipmentOfPatientList.add(requiredPatientEquipment);
+ requiredPatientEquipmentList.add(requiredPatientEquipment);
+ requiredPatientEquipmentId++;
+ } else if (hasEquipment != 0) {
+ throw new IllegalArgumentException("Read line (" + line
+ + ") is expected to have 0 or 1 hasEquipment (" + hasEquipment + ").");
+ }
+ }
+ patient.setRequiredPatientEquipmentList(requiredPatientEquipmentOfPatientList);
+
+ String[] preferredPatientEquipmentTokens = splitBySpace(lineTokens[5]);
+ if (preferredPatientEquipmentTokens.length != equipmentListSize) {
+ throw new IllegalArgumentException("Read line (" + line
+ + ") is expected to contain equal number of tokens ("
+ + preferredPatientEquipmentTokens.length
+ + ") as equipmentListSize (" + equipmentListSize + ") after 5th pipeline (|).");
+ }
+ List<PreferredPatientEquipment> preferredPatientEquipmentOfPatientList
+ = new ArrayList<PreferredPatientEquipment>(equipmentListSize);
+ for (int j = 0; j < preferredPatientEquipmentTokens.length; j++) {
+ int hasEquipment = Integer.parseInt(preferredPatientEquipmentTokens[j]);
+ if (hasEquipment == 1) {
+ boolean alreadyRequired = (Integer.parseInt(requiredPatientEquipmentTokens[j]) == 1);
+ // Official spec: if equipment is required
+ // then a duplicate preffered constraint should be ignored
+ if (!alreadyRequired) {
+ PreferredPatientEquipment preferredPatientEquipment = new PreferredPatientEquipment();
+ preferredPatientEquipment.setId(preferredPatientEquipmentId);
+ preferredPatientEquipment.setPatient(patient);
+ preferredPatientEquipment.setEquipment(indexToEquipmentMap.get(j));
+ preferredPatientEquipmentOfPatientList.add(preferredPatientEquipment);
+ preferredPatientEquipmentList.add(preferredPatientEquipment);
+ preferredPatientEquipmentId++;
+ }
+ } else if (hasEquipment != 0) {
+ throw new IllegalArgumentException("Read line (" + line
+ + ") is expected to have 0 or 1 hasEquipment (" + hasEquipment + ").");
+ }
+ }
+ patient.setPreferredPatientEquipmentList(preferredPatientEquipmentOfPatientList);
+ }
+ patientAdmissionSchedule.setPatientList(patientList);
+ patientAdmissionSchedule.setAdmissionPartList(admissionPartList);
+ patientAdmissionSchedule.setRequiredPatientEquipmentList(requiredPatientEquipmentList);
+ patientAdmissionSchedule.setPreferredPatientEquipmentList(preferredPatientEquipmentList);
+ }
+
+// /**
+// * hack to make sure there are enough nights
+// * @param lastNightIndex >= 0
+// */
+// private void ensureEnoughNights(int lastNightIndex) {
+// List<Night> nightList = patientAdmissionSchedule.getNightList();
+// if (lastNightIndex >= nightList.size()) {
+// long nightId = nightList.size();
+// for (int j = nightList.size(); j <= lastNightIndex; j++) {
+// Night night = new Night();
+// night.setId(nightId);
+// night.setIndex(j);
+// nightList.add(night);
+// indexToNightMap.put(j, night);
+// nightId++;
+// }
+// }
+// }
+
+ // ************************************************************************
+ // Helper methods
+ // ************************************************************************
+
+ private String[] splitBySpace(String line) {
+ String[] lineTokens = line.split("\\ ");
+ return lineTokens;
+ }
+
+ private String[] splitBySpace(String line, int numberOfTokens) {
+ String[] lineTokens = line.split("\\ ");
+ if (lineTokens.length != numberOfTokens) {
+ throw new IllegalArgumentException("Read line (" + line
+ + ") is expected to contain " + numberOfTokens + " tokens seperated by a space ( ).");
+ }
+ return lineTokens;
+ }
+
+ private String[] splitByPipeline(String line, int numberOfTokens) {
+ String[] lineTokens = line.split("\\|");
+ if (lineTokens.length != numberOfTokens) {
+ throw new IllegalArgumentException("Read line (" + line
+ + ") is expected to contain " + numberOfTokens + " tokens seperated by a pipeline (|).");
+ }
+ for (int i = 0; i < lineTokens.length; i++) {
+ lineTokens[i] = lineTokens[i].trim();
+ }
+ return lineTokens;
+ }
+
+ }
+
+}
Deleted: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleInputConvertor.java
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleInputConvertor.java 2010-03-10 20:15:05 UTC (rev 32025)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleInputConvertor.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -1,524 +0,0 @@
-package org.drools.planner.examples.pas.persistence;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Collections;
-
-import org.drools.planner.core.solution.Solution;
-import org.drools.planner.examples.common.persistence.AbstractInputConvertor;
-import org.drools.planner.examples.common.persistence.SolutionDao;
-import org.drools.planner.examples.pas.domain.AdmissionPart;
-import org.drools.planner.examples.pas.domain.Bed;
-import org.drools.planner.examples.pas.domain.Department;
-import org.drools.planner.examples.pas.domain.DepartmentSpecialism;
-import org.drools.planner.examples.pas.domain.Equipment;
-import org.drools.planner.examples.pas.domain.Gender;
-import org.drools.planner.examples.pas.domain.GenderLimitation;
-import org.drools.planner.examples.pas.domain.Night;
-import org.drools.planner.examples.pas.domain.Patient;
-import org.drools.planner.examples.pas.domain.PatientAdmissionSchedule;
-import org.drools.planner.examples.pas.domain.PreferredPatientEquipment;
-import org.drools.planner.examples.pas.domain.RequiredPatientEquipment;
-import org.drools.planner.examples.pas.domain.Room;
-import org.drools.planner.examples.pas.domain.RoomEquipment;
-import org.drools.planner.examples.pas.domain.RoomSpecialism;
-import org.drools.planner.examples.pas.domain.Specialism;
-
-/**
- * @author Geoffrey De Smet
- * @author Wim Vancroonenburg
- */
-public class PatientAdmissionScheduleInputConvertor extends AbstractInputConvertor {
-
- public static void main(String[] args) {
- new PatientAdmissionScheduleInputConvertor().convertAll();
- }
-
- public PatientAdmissionScheduleInputConvertor() {
- super(new PatientAdmissionScheduleDaoImpl());
- }
-
- public InputBuilder createInputBuilder() {
- return new PatientAdmissionScheduleInputBuilder();
- }
-
- public class PatientAdmissionScheduleInputBuilder extends InputBuilder {
-
- private PatientAdmissionSchedule patientAdmissionSchedule;
-
- private int specialismListSize;
- private int departmentListSize;
- private int equipmentListSize;
- private int roomListSize;
- private int bedListSize;
- private int nightListSize;
- private int patientListSize;
-
- private Map<Long, Specialism> idToSpecialismMap = null;
- private Map<Long, Department> idToDepartmentMap = null;
- private Map<Integer, Equipment> indexToEquipmentMap = null;
- private Map<Long, Room> idToRoomMap = null;
- private Map<Integer, Night> indexToNightMap = null;
-
- public Solution readSolution() throws IOException {
- patientAdmissionSchedule = new PatientAdmissionSchedule();
- patientAdmissionSchedule.setId(0L);
- readSizes();
- readEmptyLine();
- readEmptyLine();
- readSpecialismList();
- readEmptyLine();
- readDepartmentListAndDepartmentSpecialismList();
- readEmptyLine();
- readEquipmentList();
- readEmptyLine();
- readRoomListAndRoomSpecialismListAndRoomEquipmentList();
- readEmptyLine();
- readBedList();
- readEmptyLine();
- generateNightList();
- readPatientListAndAdmissionPartListAndRequiredPatientEquipmentListAndPreferredPatientEquipmentList();
- readEmptyLine();
- readConstantLine("END.");
- // TODO not all nights are planned, only the "planning horizon" nights are planned
- logger.info("PatientAdmissionSchedule with {} specialisms, {} equipments, {} departments, {} rooms, "
- + "{} beds, {} nights, {} patients and {} admissions.",
- new Object[]{patientAdmissionSchedule.getSpecialismList().size(),
- patientAdmissionSchedule.getEquipmentList().size(),
- patientAdmissionSchedule.getDepartmentList().size(),
- patientAdmissionSchedule.getRoomList().size(),
- patientAdmissionSchedule.getBedList().size(),
- patientAdmissionSchedule.getNightList().size(),
- patientAdmissionSchedule.getPatientList().size(),
- patientAdmissionSchedule.getAdmissionPartList().size()});
- return patientAdmissionSchedule;
- }
-
- private void readSizes() throws IOException {
- readConstantLine("ARTICLE BENCHMARK DATA SET");
- roomListSize = readIntegerValue("Rooms:");
- equipmentListSize = readIntegerValue("Roomproperties:");
- bedListSize = readIntegerValue("Beds:");
- departmentListSize = readIntegerValue("Departments:");
- specialismListSize = readIntegerValue("Specialisms:");
- patientListSize = readIntegerValue("Patients:");
- nightListSize = readIntegerValue("Planning horizon:");
- }
-
- private void readSpecialismList() throws IOException {
- readConstantLine("SPECIALISMS:");
- List<Specialism> specialismList = new ArrayList<Specialism>(specialismListSize);
- idToSpecialismMap = new HashMap<Long, Specialism>(specialismListSize);
- for (int i = 0; i < specialismListSize; i++) {
- String line = bufferedReader.readLine();
- String[] lineTokens = splitBySpace(line, 2);
- Specialism specialism = new Specialism();
- specialism.setId(Long.parseLong(lineTokens[0]));
- specialism.setName(lineTokens[1]);
- specialismList.add(specialism);
- idToSpecialismMap.put(specialism.getId(), specialism);
- }
- patientAdmissionSchedule.setSpecialismList(specialismList);
- }
-
- private void readDepartmentListAndDepartmentSpecialismList() throws IOException {
- readConstantLine("DEPARTMENTS:");
- List<Department> departmentList = new ArrayList<Department>(departmentListSize);
- idToDepartmentMap = new HashMap<Long, Department>(departmentListSize);
- List<DepartmentSpecialism> departmentSpecialismList = new ArrayList<DepartmentSpecialism>(
- departmentListSize * 5);
- long departmentSpecialismId = 0L;
- for (int i = 0; i < departmentListSize; i++) {
- String line = bufferedReader.readLine();
- String[] lineTokens = splitByPipeline(line, 2);
-
- String[] departmentTokens = splitBySpace(lineTokens[0], 4);
- Department department = new Department();
- department.setId(Long.parseLong(departmentTokens[0]));
- department.setName(departmentTokens[1]);
- int minimumAge = Integer.parseInt(departmentTokens[2]);
- if (minimumAge != 0) {
- department.setMinimumAge(Integer.valueOf(minimumAge));
- }
- int maximumAge = Integer.parseInt(departmentTokens[3]);
- if (maximumAge != 0) {
- department.setMaximumAge(Integer.valueOf(maximumAge));
- }
- departmentList.add(department);
- idToDepartmentMap.put(department.getId(), department);
-
- String[] departmentSpecialismTokens = splitBySpace(lineTokens[1]);
- if (departmentSpecialismTokens.length % 2 != 0) {
- throw new IllegalArgumentException("Read line (" + line
- + ") is expected to contain even number of tokens (" + departmentSpecialismTokens.length
- + ") after 1st pipeline (|) seperated by a space ( ).");
- }
- for (int j = 0; j < departmentSpecialismTokens.length; j += 2) {
- long specialismId = Long.parseLong(departmentSpecialismTokens[j + 1]);
- if (specialismId != 0) {
- DepartmentSpecialism departmentSpecialism = new DepartmentSpecialism();
- departmentSpecialism.setId(departmentSpecialismId);
- departmentSpecialism.setDepartment(department);
- departmentSpecialism.setPriority(Integer.parseInt(departmentSpecialismTokens[j]));
- Specialism specialism = idToSpecialismMap.get(specialismId);
- if (specialism == null) {
- throw new IllegalArgumentException("Read line (" + line
- + ") has a non existing specialismId (" + specialismId + ").");
- }
- departmentSpecialism.setSpecialism(specialism);
- departmentSpecialismList.add(departmentSpecialism);
- departmentSpecialismId++;
- }
- }
- }
- Collections.sort(departmentList);
- patientAdmissionSchedule.setDepartmentList(departmentList);
- patientAdmissionSchedule.setDepartmentSpecialismList(departmentSpecialismList);
- }
-
- private void readEquipmentList() throws IOException {
- readConstantLine("ROOMPROPERTIES:");
- List<Equipment> equipmentList = new ArrayList<Equipment>(equipmentListSize);
- indexToEquipmentMap = new HashMap<Integer, Equipment>(equipmentListSize);
- for (int i = 0; i < equipmentListSize; i++) {
- String line = bufferedReader.readLine();
- String[] lineTokens = splitBySpace(line, 2);
- Equipment equipment = new Equipment();
- equipment.setId(Long.parseLong(lineTokens[0]));
- equipment.setName(lineTokens[1]);
- equipmentList.add(equipment);
- indexToEquipmentMap.put(i, equipment);
- }
- patientAdmissionSchedule.setEquipmentList(equipmentList);
- }
-
- private void readRoomListAndRoomSpecialismListAndRoomEquipmentList() throws IOException {
- readConstantLine("ROOMS:");
- List<Room> roomList = new ArrayList<Room>(roomListSize);
- idToRoomMap = new HashMap<Long, Room>(roomListSize);
- List<RoomSpecialism> roomSpecialismList = new ArrayList<RoomSpecialism>(roomListSize * 5);
- List<RoomEquipment> roomEquipmentList = new ArrayList<RoomEquipment>(roomListSize * 2);
- long roomSpecialismId = 0L;
- long roomEquipmentId = 0L;
- for (int i = 0; i < roomListSize; i++) {
- String line = bufferedReader.readLine();
- String[] lineTokens = splitByPipeline(line, 6);
-
- String[] roomTokens = splitBySpace(lineTokens[0], 2);
- Room room = new Room();
- room.setId(Long.parseLong(roomTokens[0]));
- room.setName(roomTokens[1]);
- room.setCapacity(Integer.parseInt(lineTokens[1]));
- room.setDepartment(idToDepartmentMap.get(
- Long.parseLong(lineTokens[2])));
- room.setGenderLimitation(GenderLimitation.valueOfCode(lineTokens[3]));
- roomList.add(room);
- idToRoomMap.put(room.getId(), room);
-
- String[] roomSpecialismTokens = splitBySpace(lineTokens[4]);
- if (roomSpecialismTokens.length % 2 != 0) {
- throw new IllegalArgumentException("Read line (" + line
- + ") is expected to contain even number of tokens (" + roomSpecialismTokens.length
- + ") after 4th pipeline (|) seperated by a space ( ).");
- }
- List<RoomSpecialism> roomSpecialismListOfRoom = new ArrayList<RoomSpecialism>(roomSpecialismTokens.length / 2);
- for (int j = 0; j < roomSpecialismTokens.length; j += 2) {
- int priority = Integer.parseInt(roomSpecialismTokens[j]);
- long specialismId = Long.parseLong(roomSpecialismTokens[j + 1]);
- if (specialismId != 0) {
- RoomSpecialism roomSpecialism = new RoomSpecialism();
- roomSpecialism.setId(roomSpecialismId);
- roomSpecialism.setRoom(room);
- Specialism specialism = idToSpecialismMap.get(specialismId);
- if (specialism == null) {
- throw new IllegalArgumentException("Read line (" + line
- + ") has a non existing specialismId (" + specialismId + ").");
- }
- roomSpecialism.setSpecialism(specialism);
- roomSpecialism.setPriority(priority);
- roomSpecialismListOfRoom.add(roomSpecialism);
- roomSpecialismList.add(roomSpecialism);
- roomSpecialismId++;
- }
- }
- room.setRoomSpecialismList(roomSpecialismListOfRoom);
-
- List<RoomEquipment> roomEquipmentListOfRoom = new ArrayList<RoomEquipment>(equipmentListSize);
- String[] roomEquipmentTokens = splitBySpace(lineTokens[5]);
- if (roomEquipmentTokens.length != equipmentListSize) {
- throw new IllegalArgumentException("Read line (" + line
- + ") is expected to contain equal number of tokens (" + roomEquipmentTokens.length
- + ") as equipmentListSize (" + equipmentListSize + ") after 5th pipeline (|).");
- }
- for (int j = 0; j < roomEquipmentTokens.length; j++) {
- int hasEquipment = Integer.parseInt(roomEquipmentTokens[j]);
- if (hasEquipment == 1) {
- RoomEquipment roomEquipment = new RoomEquipment();
- roomEquipment.setId(roomEquipmentId);
- roomEquipment.setRoom(room);
- roomEquipment.setEquipment(indexToEquipmentMap.get(j));
- roomEquipmentListOfRoom.add(roomEquipment);
- roomEquipmentList.add(roomEquipment);
- roomEquipmentId++;
- } else if (hasEquipment != 0) {
- throw new IllegalArgumentException("Read line (" + line
- + ") is expected to have 0 or 1 hasEquipment (" + hasEquipment + ").");
- }
- }
- room.setRoomEquipmentList(roomEquipmentListOfRoom);
- }
- Collections.sort(roomList);
- patientAdmissionSchedule.setRoomList(roomList);
- patientAdmissionSchedule.setRoomSpecialismList(roomSpecialismList);
- patientAdmissionSchedule.setRoomEquipmentList(roomEquipmentList);
- }
-
- private void readBedList() throws IOException {
- readConstantLine("BEDS:");
- List<Bed> bedList = new ArrayList<Bed>(bedListSize);
- Map<Room, Integer> roomToLastIndexInRoomMap = new HashMap<Room, Integer>(roomListSize);
- for (int i = 0; i < bedListSize; i++) {
- String line = bufferedReader.readLine();
- String[] lineTokens = splitBySpace(line, 2);
- Bed bed = new Bed();
- bed.setId(Long.parseLong(lineTokens[0]));
- Room room = idToRoomMap.get(Long.parseLong(lineTokens[1]));
- bed.setRoom(room);
- Integer indexInRoom = roomToLastIndexInRoomMap.get(room);
- if (indexInRoom == null) {
- indexInRoom = 0;
- } else {
- indexInRoom++;
- }
- bed.setIndexInRoom(indexInRoom);
- roomToLastIndexInRoomMap.put(room, indexInRoom);
- bedList.add(bed);
- }
- Collections.sort(bedList);
- patientAdmissionSchedule.setBedList(bedList);
- }
-
- private void generateNightList() {
- List<Night> nightList = new ArrayList<Night>(nightListSize);
- indexToNightMap = new HashMap<Integer, Night>(nightListSize);
- long nightId = 0L;
- for (int i = 0; i < nightListSize; i++) {
- Night night = new Night();
- night.setId(nightId);
- night.setIndex(i);
- nightList.add(night);
- indexToNightMap.put(i, night);
- nightId++;
- }
- patientAdmissionSchedule.setNightList(nightList);
- }
-
- private void readPatientListAndAdmissionPartListAndRequiredPatientEquipmentListAndPreferredPatientEquipmentList() throws IOException {
- readConstantLine("PATIENTS:");
- List<Patient> patientList = new ArrayList<Patient>(patientListSize);
- List<AdmissionPart> admissionPartList = new ArrayList<AdmissionPart>(patientListSize);
- List<RequiredPatientEquipment> requiredPatientEquipmentList = new ArrayList<RequiredPatientEquipment>(patientListSize * equipmentListSize);
- List<PreferredPatientEquipment> preferredPatientEquipmentList = new ArrayList<PreferredPatientEquipment>(patientListSize * equipmentListSize);
- long admissionPartId = 0L;
- long requiredPatientEquipmentId = 0L;
- long preferredPatientEquipmentId = 0L;
- for (int i = 0; i < patientListSize; i++) {
- String line = bufferedReader.readLine();
- String[] lineTokens = splitByPipeline(line, 6);
-
- String[] nightTokens = splitBySpace(lineTokens[1], 2);
- int firstNightIndex = Integer.parseInt(nightTokens[0]);
- int lastNightIndex = Integer.parseInt(nightTokens[1]);
- int patientNightListSize = lastNightIndex - firstNightIndex;
- // A patient with no nights in the planning horizon or no nights at all is ignored
- if (firstNightIndex >= nightListSize || patientNightListSize == 0) {
- continue;
- }
-
- String[] patientTokens = splitBySpace(lineTokens[0], 4);
- Patient patient = new Patient();
- patient.setId(Long.parseLong(patientTokens[0]));
- patient.setName(patientTokens[1]);
- patient.setAge(Integer.parseInt(patientTokens[2]));
- patient.setGender(Gender.valueOfCode(patientTokens[3]));
- int preferredMaximumRoomCapacity = Integer.parseInt(lineTokens[3]);
- patient.setPreferredMaximumRoomCapacity(preferredMaximumRoomCapacity == 0
- ? null : preferredMaximumRoomCapacity);
- patientList.add(patient);
-
- String[] admissionPartTokens = splitBySpace(lineTokens[2]);
- if (admissionPartTokens.length % 2 != 1) {
- }
- int patientAdmissionPartListSize = Integer.parseInt(admissionPartTokens[0]);
- if (admissionPartTokens.length != ((patientAdmissionPartListSize * 2) + 1)) {
- throw new IllegalArgumentException("Read line (" + line
- + ") is expected to contain " + ((patientAdmissionPartListSize * 2) + 1)
- + " number of tokens after 2th pipeline (|).");
- }
- int nextFirstNightIndex = firstNightIndex;
- for (int j = 1; j < admissionPartTokens.length; j += 2) {
- long specialismId = Long.parseLong(admissionPartTokens[j]);
- int admissionPartNightListSize = Integer.parseInt(admissionPartTokens[j + 1]);
- if (nextFirstNightIndex >= nightListSize || admissionPartNightListSize == 0) {
- nextFirstNightIndex += admissionPartNightListSize;
- continue;
- }
- AdmissionPart admissionPart = new AdmissionPart();
- admissionPart.setId(admissionPartId);
- admissionPart.setPatient(patient);
- Specialism specialism = (specialismId == 0) ? null : idToSpecialismMap.get(specialismId);
- if (specialism == null) {
- throw new IllegalArgumentException("Read line (" + line
- + ") has a non existing specialismId (" + specialismId + ").");
- }
- admissionPart.setSpecialism(specialism);
- int admissionPartFirstNightIndex = nextFirstNightIndex;
- Night admissionPartFirstNight = indexToNightMap.get(admissionPartFirstNightIndex);
- if (admissionPartFirstNight == null) {
- throw new IllegalStateException(
- "The admissionPartFirstNight was not found for admissionPartFirstNightIndex("
- + admissionPartFirstNightIndex + ").");
- }
- admissionPart.setFirstNight(admissionPartFirstNight);
- int admissionPartLastNightIndex = nextFirstNightIndex + admissionPartNightListSize - 1;
- // TODO Instead of ensureEnoughNights(lastNightIndex);
- // the official score function ignores any broken constraints after the planning horizon
- if (admissionPartLastNightIndex >= nightListSize) {
- admissionPartLastNightIndex = nightListSize - 1;
- }
- Night admissionPartLastNight = indexToNightMap.get(admissionPartLastNightIndex);
- if (admissionPartLastNight == null) {
- throw new IllegalStateException(
- "The admissionPartLastNight was not found for admissionPartLastNightIndex("
- + admissionPartLastNightIndex + ").");
- }
- admissionPart.setLastNight(admissionPartLastNight);
- admissionPartList.add(admissionPart);
- admissionPartId++;
- nextFirstNightIndex += admissionPartNightListSize;
- }
- int admissionPartNightListSizeSum = nextFirstNightIndex - firstNightIndex;
- if (patientNightListSize != admissionPartNightListSizeSum) {
- throw new IllegalArgumentException("Read line (" + line
- + ") has patientNightListSize (" + patientNightListSize
- + ") different from admissionPartNightListSizeSum(" + admissionPartNightListSizeSum + ")");
- }
-
- String[] requiredPatientEquipmentTokens = splitBySpace(lineTokens[4]);
- if (requiredPatientEquipmentTokens.length != equipmentListSize) {
- throw new IllegalArgumentException("Read line (" + line
- + ") is expected to contain equal number of tokens ("
- + requiredPatientEquipmentTokens.length
- + ") as equipmentListSize (" + equipmentListSize + ") after 4th pipeline (|).");
- }
- List<RequiredPatientEquipment> requiredPatientEquipmentOfPatientList
- = new ArrayList<RequiredPatientEquipment>(equipmentListSize);
- for (int j = 0; j < requiredPatientEquipmentTokens.length; j++) {
- int hasEquipment = Integer.parseInt(requiredPatientEquipmentTokens[j]);
- if (hasEquipment == 1) {
- RequiredPatientEquipment requiredPatientEquipment = new RequiredPatientEquipment();
- requiredPatientEquipment.setId(requiredPatientEquipmentId);
- requiredPatientEquipment.setPatient(patient);
- requiredPatientEquipment.setEquipment(indexToEquipmentMap.get(j));
- requiredPatientEquipmentOfPatientList.add(requiredPatientEquipment);
- requiredPatientEquipmentList.add(requiredPatientEquipment);
- requiredPatientEquipmentId++;
- } else if (hasEquipment != 0) {
- throw new IllegalArgumentException("Read line (" + line
- + ") is expected to have 0 or 1 hasEquipment (" + hasEquipment + ").");
- }
- }
- patient.setRequiredPatientEquipmentList(requiredPatientEquipmentOfPatientList);
-
- String[] preferredPatientEquipmentTokens = splitBySpace(lineTokens[5]);
- if (preferredPatientEquipmentTokens.length != equipmentListSize) {
- throw new IllegalArgumentException("Read line (" + line
- + ") is expected to contain equal number of tokens ("
- + preferredPatientEquipmentTokens.length
- + ") as equipmentListSize (" + equipmentListSize + ") after 5th pipeline (|).");
- }
- List<PreferredPatientEquipment> preferredPatientEquipmentOfPatientList
- = new ArrayList<PreferredPatientEquipment>(equipmentListSize);
- for (int j = 0; j < preferredPatientEquipmentTokens.length; j++) {
- int hasEquipment = Integer.parseInt(preferredPatientEquipmentTokens[j]);
- if (hasEquipment == 1) {
- boolean alreadyRequired = (Integer.parseInt(requiredPatientEquipmentTokens[j]) == 1);
- // Official spec: if equipment is required
- // then a duplicate preffered constraint should be ignored
- if (!alreadyRequired) {
- PreferredPatientEquipment preferredPatientEquipment = new PreferredPatientEquipment();
- preferredPatientEquipment.setId(preferredPatientEquipmentId);
- preferredPatientEquipment.setPatient(patient);
- preferredPatientEquipment.setEquipment(indexToEquipmentMap.get(j));
- preferredPatientEquipmentOfPatientList.add(preferredPatientEquipment);
- preferredPatientEquipmentList.add(preferredPatientEquipment);
- preferredPatientEquipmentId++;
- }
- } else if (hasEquipment != 0) {
- throw new IllegalArgumentException("Read line (" + line
- + ") is expected to have 0 or 1 hasEquipment (" + hasEquipment + ").");
- }
- }
- patient.setPreferredPatientEquipmentList(preferredPatientEquipmentOfPatientList);
- }
- patientAdmissionSchedule.setPatientList(patientList);
- patientAdmissionSchedule.setAdmissionPartList(admissionPartList);
- patientAdmissionSchedule.setRequiredPatientEquipmentList(requiredPatientEquipmentList);
- patientAdmissionSchedule.setPreferredPatientEquipmentList(preferredPatientEquipmentList);
- }
-
-// /**
-// * hack to make sure there are enough nights
-// * @param lastNightIndex >= 0
-// */
-// private void ensureEnoughNights(int lastNightIndex) {
-// List<Night> nightList = patientAdmissionSchedule.getNightList();
-// if (lastNightIndex >= nightList.size()) {
-// long nightId = nightList.size();
-// for (int j = nightList.size(); j <= lastNightIndex; j++) {
-// Night night = new Night();
-// night.setId(nightId);
-// night.setIndex(j);
-// nightList.add(night);
-// indexToNightMap.put(j, night);
-// nightId++;
-// }
-// }
-// }
-
- // ************************************************************************
- // Helper methods
- // ************************************************************************
-
- private String[] splitBySpace(String line) {
- String[] lineTokens = line.split("\\ ");
- return lineTokens;
- }
-
- private String[] splitBySpace(String line, int numberOfTokens) {
- String[] lineTokens = line.split("\\ ");
- if (lineTokens.length != numberOfTokens) {
- throw new IllegalArgumentException("Read line (" + line
- + ") is expected to contain " + numberOfTokens + " tokens seperated by a space ( ).");
- }
- return lineTokens;
- }
-
- private String[] splitByPipeline(String line, int numberOfTokens) {
- String[] lineTokens = line.split("\\|");
- if (lineTokens.length != numberOfTokens) {
- throw new IllegalArgumentException("Read line (" + line
- + ") is expected to contain " + numberOfTokens + " tokens seperated by a pipeline (|).");
- }
- for (int i = 0; i < lineTokens.length; i++) {
- lineTokens[i] = lineTokens[i].trim();
- }
- return lineTokens;
- }
-
- }
-
-}
\ No newline at end of file
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleOutputConverter.java (from rev 32019, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleOutputConvertor.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleOutputConverter.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleOutputConverter.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,53 @@
+package org.drools.planner.examples.pas.persistence;
+
+import java.io.IOException;
+import java.util.Collections;
+
+import org.drools.planner.examples.common.persistence.AbstractTxtOutputConverter;
+import org.drools.planner.examples.pas.domain.PatientAdmissionSchedule;
+import org.drools.planner.examples.pas.domain.Patient;
+import org.drools.planner.examples.pas.domain.BedDesignation;
+import org.drools.planner.core.solution.Solution;
+
+/**
+ * @author Geoffrey De Smet
+ */
+public class PatientAdmissionScheduleOutputConverter extends AbstractTxtOutputConverter {
+
+ public static void main(String[] args) {
+ new PatientAdmissionScheduleOutputConverter().convertAll();
+ }
+
+ public PatientAdmissionScheduleOutputConverter() {
+ super(new PatientAdmissionScheduleDaoImpl());
+ }
+
+ public TxtOutputBuilder createTxtOutputBuilder() {
+ return new PatientAdmissionScheduleOutputBuilder();
+ }
+
+ public class PatientAdmissionScheduleOutputBuilder extends TxtOutputBuilder {
+
+ private PatientAdmissionSchedule patientAdmissionSchedule;
+
+ public void setSolution(Solution solution) {
+ patientAdmissionSchedule = (PatientAdmissionSchedule) solution;
+ }
+
+ public void writeSolution() throws IOException {
+ Collections.sort(patientAdmissionSchedule.getBedDesignationList());
+ for (Patient patient : patientAdmissionSchedule.getPatientList()) {
+ bufferedWriter.write(Long.toString(patient.getId()));
+ for (BedDesignation bedDesignation : patientAdmissionSchedule.getBedDesignationList()) {
+ if (bedDesignation.getPatient().equals(patient)) {
+ for (int i = 0; i < bedDesignation.getAdmissionPart().getNightCount(); i++) {
+ bufferedWriter.write(" " + Long.toString(bedDesignation.getBed().getId()));
+ }
+ }
+ }
+ bufferedWriter.write("\n");
+ }
+ }
+ }
+
+}
Deleted: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleOutputConvertor.java
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleOutputConvertor.java 2010-03-10 20:15:05 UTC (rev 32025)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/pas/persistence/PatientAdmissionScheduleOutputConvertor.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -1,53 +0,0 @@
-package org.drools.planner.examples.pas.persistence;
-
-import java.io.IOException;
-import java.util.Collections;
-
-import org.drools.planner.examples.common.persistence.AbstractOutputConvertor;
-import org.drools.planner.examples.pas.domain.PatientAdmissionSchedule;
-import org.drools.planner.examples.pas.domain.Patient;
-import org.drools.planner.examples.pas.domain.BedDesignation;
-import org.drools.planner.core.solution.Solution;
-
-/**
- * @author Geoffrey De Smet
- */
-public class PatientAdmissionScheduleOutputConvertor extends AbstractOutputConvertor {
-
- public static void main(String[] args) {
- new PatientAdmissionScheduleOutputConvertor().convertAll();
- }
-
- public PatientAdmissionScheduleOutputConvertor() {
- super(new PatientAdmissionScheduleDaoImpl());
- }
-
- public OutputBuilder createOutputBuilder() {
- return new PatientAdmissionScheduleOutputBuilder();
- }
-
- public class PatientAdmissionScheduleOutputBuilder extends OutputBuilder {
-
- private PatientAdmissionSchedule patientAdmissionSchedule;
-
- public void setSolution(Solution solution) {
- patientAdmissionSchedule = (PatientAdmissionSchedule) solution;
- }
-
- public void writeSolution() throws IOException {
- Collections.sort(patientAdmissionSchedule.getBedDesignationList());
- for (Patient patient : patientAdmissionSchedule.getPatientList()) {
- bufferedWriter.write(Long.toString(patient.getId()));
- for (BedDesignation bedDesignation : patientAdmissionSchedule.getBedDesignationList()) {
- if (bedDesignation.getPatient().equals(patient)) {
- for (int i = 0; i < bedDesignation.getAdmissionPart().getNightCount(); i++) {
- bufferedWriter.write(" " + Long.toString(bedDesignation.getBed().getId()));
- }
- }
- }
- bufferedWriter.write("\n");
- }
- }
- }
-
-}
\ No newline at end of file
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/TravelingTournamentInputConverter.java (from rev 32019, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/TravelingTournamentInputConvertor.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/TravelingTournamentInputConverter.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/TravelingTournamentInputConverter.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,115 @@
+package org.drools.planner.examples.travelingtournament.persistence;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import org.drools.planner.examples.common.persistence.AbstractTxtInputConverter;
+import org.drools.planner.examples.common.persistence.SolutionDao;
+import org.drools.planner.examples.travelingtournament.domain.Day;
+import org.drools.planner.examples.travelingtournament.domain.Match;
+import org.drools.planner.examples.travelingtournament.domain.Team;
+import org.drools.planner.examples.travelingtournament.domain.TravelingTournament;
+import org.drools.planner.core.solution.Solution;
+
+/**
+ * @author Geoffrey De Smet
+ */
+public abstract class TravelingTournamentInputConverter extends AbstractTxtInputConverter {
+
+ protected TravelingTournamentInputConverter(SolutionDao solutionDao) {
+ super(solutionDao);
+ }
+
+ public abstract class TravelingTournamentInputBuilder extends TxtInputBuilder {
+
+ public Solution readSolution() throws IOException {
+ TravelingTournament travelingTournament = new TravelingTournament();
+ travelingTournament.setId(0L);
+ int n = readN();
+ List<Team> teamList = readTeamList(n);
+ travelingTournament.setTeamList(teamList);
+ List<Day> dayList = constructDayList(n);
+ travelingTournament.setDayList(dayList);
+ List<List<Integer>> outerDistanceList = readOuterDistanceList();
+ List<Match> matchList = constructMatchListAndSetDistancesInTeamList(teamList, outerDistanceList);
+ travelingTournament.setMatchList(matchList);
+ initializeMatchDays(travelingTournament);
+ return travelingTournament;
+ }
+
+ private int readN() throws IOException {
+ return Integer.parseInt(bufferedReader.readLine());
+ }
+
+ private List<Team> readTeamList(int n) throws IOException {
+ List<Team> teamList = new ArrayList<Team>();
+ for (int i = 0; i < n; i++) {
+ Team team = new Team();
+ team.setId((long) i);
+ team.setName(bufferedReader.readLine());
+ team.setDistanceToTeamMap(new HashMap<Team, Integer>());
+ teamList.add(team);
+ }
+ return teamList;
+ }
+
+ private List<List<Integer>> readOuterDistanceList() throws IOException {
+ List<List<Integer>> outerDistanceList = new ArrayList<List<Integer>>();
+ String line = bufferedReader.readLine();
+ while (line != null && !line.replaceAll("\\s+", "").equals("")) {
+ StringTokenizer tokenizer = new StringTokenizer(line.replaceAll("\\s+", " ").trim());
+ List<Integer> innerDistanceList = new ArrayList<Integer>();
+ while (tokenizer.hasMoreTokens()) {
+ int distance = Integer.parseInt(tokenizer.nextToken());
+ innerDistanceList.add(distance);
+ }
+ outerDistanceList.add(innerDistanceList);
+ line = bufferedReader.readLine();
+ }
+ return outerDistanceList;
+ }
+
+ private List<Day> constructDayList(int n) {
+ List<Day> dayList = new ArrayList<Day>();
+ int daySize = (n - 1) * 2; // Play vs each team (except itself) twice (home and away)
+ for (int i = 0; i < daySize; i++) {
+ Day day = new Day();
+ day.setId((long) i);
+ day.setIndex(i);
+ dayList.add(day);
+ }
+ return dayList;
+ }
+
+ private List<Match> constructMatchListAndSetDistancesInTeamList(List<Team> teamList, List<List<Integer>> outerDistanceList) {
+ List<Match> matchList = new ArrayList<Match>();
+ int i = 0;
+ long matchId = 0;
+ for (Team homeTeam : teamList) {
+ int j = 0;
+ for (Team awayTeam : teamList) {
+ int distance = outerDistanceList.get(i).get(j);
+ homeTeam.getDistanceToTeamMap().put(awayTeam, distance);
+ if (i != j) {
+ Match match = new Match();
+ match.setId(matchId);
+ matchId++;
+ match.setHomeTeam(homeTeam);
+ match.setAwayTeam(awayTeam);
+ matchList.add(match);
+ }
+ j++;
+ }
+ i++;
+ }
+ return matchList;
+ }
+
+ protected abstract void initializeMatchDays(TravelingTournament travelingTournament);
+
+ }
+
+}
Deleted: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/TravelingTournamentInputConvertor.java
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/TravelingTournamentInputConvertor.java 2010-03-10 20:15:05 UTC (rev 32025)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/TravelingTournamentInputConvertor.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -1,115 +0,0 @@
-package org.drools.planner.examples.travelingtournament.persistence;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.StringTokenizer;
-
-import org.drools.planner.examples.common.persistence.AbstractInputConvertor;
-import org.drools.planner.examples.common.persistence.SolutionDao;
-import org.drools.planner.examples.travelingtournament.domain.Day;
-import org.drools.planner.examples.travelingtournament.domain.Match;
-import org.drools.planner.examples.travelingtournament.domain.Team;
-import org.drools.planner.examples.travelingtournament.domain.TravelingTournament;
-import org.drools.planner.core.solution.Solution;
-
-/**
- * @author Geoffrey De Smet
- */
-public abstract class TravelingTournamentInputConvertor extends AbstractInputConvertor {
-
- protected TravelingTournamentInputConvertor(SolutionDao solutionDao) {
- super(solutionDao);
- }
-
- public abstract class TravelingTournamentInputBuilder extends InputBuilder {
-
- public Solution readSolution() throws IOException {
- TravelingTournament travelingTournament = new TravelingTournament();
- travelingTournament.setId(0L);
- int n = readN();
- List<Team> teamList = readTeamList(n);
- travelingTournament.setTeamList(teamList);
- List<Day> dayList = constructDayList(n);
- travelingTournament.setDayList(dayList);
- List<List<Integer>> outerDistanceList = readOuterDistanceList();
- List<Match> matchList = constructMatchListAndSetDistancesInTeamList(teamList, outerDistanceList);
- travelingTournament.setMatchList(matchList);
- initializeMatchDays(travelingTournament);
- return travelingTournament;
- }
-
- private int readN() throws IOException {
- return Integer.parseInt(bufferedReader.readLine());
- }
-
- private List<Team> readTeamList(int n) throws IOException {
- List<Team> teamList = new ArrayList<Team>();
- for (int i = 0; i < n; i++) {
- Team team = new Team();
- team.setId((long) i);
- team.setName(bufferedReader.readLine());
- team.setDistanceToTeamMap(new HashMap<Team, Integer>());
- teamList.add(team);
- }
- return teamList;
- }
-
- private List<List<Integer>> readOuterDistanceList() throws IOException {
- List<List<Integer>> outerDistanceList = new ArrayList<List<Integer>>();
- String line = bufferedReader.readLine();
- while (line != null && !line.replaceAll("\\s+", "").equals("")) {
- StringTokenizer tokenizer = new StringTokenizer(line.replaceAll("\\s+", " ").trim());
- List<Integer> innerDistanceList = new ArrayList<Integer>();
- while (tokenizer.hasMoreTokens()) {
- int distance = Integer.parseInt(tokenizer.nextToken());
- innerDistanceList.add(distance);
- }
- outerDistanceList.add(innerDistanceList);
- line = bufferedReader.readLine();
- }
- return outerDistanceList;
- }
-
- private List<Day> constructDayList(int n) {
- List<Day> dayList = new ArrayList<Day>();
- int daySize = (n - 1) * 2; // Play vs each team (except itself) twice (home and away)
- for (int i = 0; i < daySize; i++) {
- Day day = new Day();
- day.setId((long) i);
- day.setIndex(i);
- dayList.add(day);
- }
- return dayList;
- }
-
- private List<Match> constructMatchListAndSetDistancesInTeamList(List<Team> teamList, List<List<Integer>> outerDistanceList) {
- List<Match> matchList = new ArrayList<Match>();
- int i = 0;
- long matchId = 0;
- for (Team homeTeam : teamList) {
- int j = 0;
- for (Team awayTeam : teamList) {
- int distance = outerDistanceList.get(i).get(j);
- homeTeam.getDistanceToTeamMap().put(awayTeam, distance);
- if (i != j) {
- Match match = new Match();
- match.setId(matchId);
- matchId++;
- match.setHomeTeam(homeTeam);
- match.setAwayTeam(awayTeam);
- matchList.add(match);
- }
- j++;
- }
- i++;
- }
- return matchList;
- }
-
- protected abstract void initializeMatchDays(TravelingTournament travelingTournament);
-
- }
-
-}
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/simple/SimpleTravelingTournamentInputConverter.java (from rev 32019, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/simple/SimpleTravelingTournamentInputConvertor.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/simple/SimpleTravelingTournamentInputConverter.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/simple/SimpleTravelingTournamentInputConverter.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,39 @@
+package org.drools.planner.examples.travelingtournament.persistence.simple;
+
+import java.util.List;
+
+import org.drools.planner.examples.travelingtournament.domain.Day;
+import org.drools.planner.examples.travelingtournament.domain.Match;
+import org.drools.planner.examples.travelingtournament.domain.TravelingTournament;
+import org.drools.planner.examples.travelingtournament.persistence.TravelingTournamentInputConverter;
+
+/**
+ * @author Geoffrey De Smet
+ */
+public class SimpleTravelingTournamentInputConverter extends TravelingTournamentInputConverter {
+
+ public static void main(String[] args) {
+ new SimpleTravelingTournamentInputConverter().convertAll();
+ }
+
+ public SimpleTravelingTournamentInputConverter() {
+ super(new SimpleTravelingTournamentDaoImpl());
+ }
+
+ public TxtInputBuilder createTxtInputBuilder() {
+ return new SimpleTravelingTournament();
+ }
+
+ public class SimpleTravelingTournament extends TravelingTournamentInputBuilder {
+
+ protected void initializeMatchDays(TravelingTournament travelingTournament) {
+ List<Match> matchList = travelingTournament.getMatchList();
+ List<Day> dayList = travelingTournament.getDayList();
+ for (Match match : matchList) {
+ match.setDay(dayList.get(0));
+ }
+ }
+
+ }
+
+}
Deleted: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/simple/SimpleTravelingTournamentInputConvertor.java
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/simple/SimpleTravelingTournamentInputConvertor.java 2010-03-10 20:15:05 UTC (rev 32025)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/simple/SimpleTravelingTournamentInputConvertor.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -1,41 +0,0 @@
-package org.drools.planner.examples.travelingtournament.persistence.simple;
-
-import java.io.File;
-import java.util.List;
-
-import org.drools.planner.examples.common.persistence.SolutionDao;
-import org.drools.planner.examples.travelingtournament.domain.Day;
-import org.drools.planner.examples.travelingtournament.domain.Match;
-import org.drools.planner.examples.travelingtournament.domain.TravelingTournament;
-import org.drools.planner.examples.travelingtournament.persistence.TravelingTournamentInputConvertor;
-
-/**
- * @author Geoffrey De Smet
- */
-public class SimpleTravelingTournamentInputConvertor extends TravelingTournamentInputConvertor {
-
- public static void main(String[] args) {
- new SimpleTravelingTournamentInputConvertor().convertAll();
- }
-
- public SimpleTravelingTournamentInputConvertor() {
- super(new SimpleTravelingTournamentDaoImpl());
- }
-
- public InputBuilder createInputBuilder() {
- return new SimpleTravelingTournament();
- }
-
- public class SimpleTravelingTournament extends TravelingTournamentInputBuilder {
-
- protected void initializeMatchDays(TravelingTournament travelingTournament) {
- List<Match> matchList = travelingTournament.getMatchList();
- List<Day> dayList = travelingTournament.getDayList();
- for (Match match : matchList) {
- match.setDay(dayList.get(0));
- }
- }
-
- }
-
-}
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentInputConverter.java (from rev 32019, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentInputConvertor.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentInputConverter.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentInputConverter.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,73 @@
+package org.drools.planner.examples.travelingtournament.persistence.smart;
+
+import java.util.List;
+
+import org.drools.planner.examples.travelingtournament.domain.Match;
+import org.drools.planner.examples.travelingtournament.domain.Team;
+import org.drools.planner.examples.travelingtournament.domain.TravelingTournament;
+import org.drools.planner.examples.travelingtournament.persistence.TravelingTournamentInputConverter;
+
+/**
+ * @author Geoffrey De Smet
+ */
+public class SmartTravelingTournamentInputConverter extends TravelingTournamentInputConverter {
+
+ public static void main(String[] args) {
+ new SmartTravelingTournamentInputConverter().convertAll();
+ }
+
+ public SmartTravelingTournamentInputConverter() {
+ super(new SmartTravelingTournamentDaoImpl());
+ }
+
+ public TxtInputBuilder createTxtInputBuilder() {
+ return new SmartTravelingTournamentInputBuilder();
+ }
+
+ public class SmartTravelingTournamentInputBuilder extends TravelingTournamentInputBuilder {
+
+ /**
+ * Canonical pattern initialization (see papers).
+ * @param travelingTournament the traveling tournament
+ */
+ protected void initializeMatchDays(TravelingTournament travelingTournament) {
+ int n = travelingTournament.getN();
+ for (int i = 0; i < (n - 1); i++) {
+ initializeMatchPairs(travelingTournament, (n - 1), i, i);
+ }
+ for (int startA = 1, startB = (n - 2); startA < (n - 1); startA += 2, startB -= 2) {
+ for (int i = 0; i < (n - 1); i++) {
+ int a = (startA + i) % (n - 1);
+ int b = (startB + i) % (n - 1);
+ initializeMatchPairs(travelingTournament, a, b, i);
+ }
+ }
+ }
+
+ private void initializeMatchPairs(TravelingTournament travelingTournament, int a, int b, int i) {
+ if ((i % 6) >= 3) { // Might not be a 100% the canonical pattern
+ // Swap them
+ int oldA = a;
+ a = b;
+ b = oldA;
+ }
+ Team aTeam = travelingTournament.getTeamList().get(a);
+ Team bTeam = travelingTournament.getTeamList().get(b);
+ Match m1 = findMatch(travelingTournament.getMatchList(), aTeam, bTeam);
+ m1.setDay(travelingTournament.getDayList().get(i));
+ Match m2 = findMatch(travelingTournament.getMatchList(), bTeam, aTeam);
+ m2.setDay(travelingTournament.getDayList().get(i + travelingTournament.getN() - 1));
+ }
+
+ private Match findMatch(List<Match> matchList, Team homeTeam, Team awayTeam) {
+ for (Match match : matchList) {
+ if (match.getHomeTeam().equals(homeTeam) && match.getAwayTeam().equals(awayTeam)) {
+ return match;
+ }
+ }
+ throw new IllegalStateException("Nothing found for: " + homeTeam + " and " + awayTeam);
+ }
+
+ }
+
+}
Deleted: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentInputConvertor.java
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentInputConvertor.java 2010-03-10 20:15:05 UTC (rev 32025)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentInputConvertor.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -1,75 +0,0 @@
-package org.drools.planner.examples.travelingtournament.persistence.smart;
-
-import java.io.File;
-import java.util.List;
-
-import org.drools.planner.examples.common.persistence.SolutionDao;
-import org.drools.planner.examples.travelingtournament.domain.Match;
-import org.drools.planner.examples.travelingtournament.domain.Team;
-import org.drools.planner.examples.travelingtournament.domain.TravelingTournament;
-import org.drools.planner.examples.travelingtournament.persistence.TravelingTournamentInputConvertor;
-
-/**
- * @author Geoffrey De Smet
- */
-public class SmartTravelingTournamentInputConvertor extends TravelingTournamentInputConvertor {
-
- public static void main(String[] args) {
- new SmartTravelingTournamentInputConvertor().convertAll();
- }
-
- public SmartTravelingTournamentInputConvertor() {
- super(new SmartTravelingTournamentDaoImpl());
- }
-
- public InputBuilder createInputBuilder() {
- return new SmartTravelingTournamentInputBuilder();
- }
-
- public class SmartTravelingTournamentInputBuilder extends TravelingTournamentInputBuilder {
-
- /**
- * Canonical pattern initialization (see papers).
- * @param travelingTournament the traveling tournament
- */
- protected void initializeMatchDays(TravelingTournament travelingTournament) {
- int n = travelingTournament.getN();
- for (int i = 0; i < (n - 1); i++) {
- initializeMatchPairs(travelingTournament, (n - 1), i, i);
- }
- for (int startA = 1, startB = (n - 2); startA < (n - 1); startA += 2, startB -= 2) {
- for (int i = 0; i < (n - 1); i++) {
- int a = (startA + i) % (n - 1);
- int b = (startB + i) % (n - 1);
- initializeMatchPairs(travelingTournament, a, b, i);
- }
- }
- }
-
- private void initializeMatchPairs(TravelingTournament travelingTournament, int a, int b, int i) {
- if ((i % 6) >= 3) { // Might not be a 100% the canonical pattern
- // Swap them
- int oldA = a;
- a = b;
- b = oldA;
- }
- Team aTeam = travelingTournament.getTeamList().get(a);
- Team bTeam = travelingTournament.getTeamList().get(b);
- Match m1 = findMatch(travelingTournament.getMatchList(), aTeam, bTeam);
- m1.setDay(travelingTournament.getDayList().get(i));
- Match m2 = findMatch(travelingTournament.getMatchList(), bTeam, aTeam);
- m2.setDay(travelingTournament.getDayList().get(i + travelingTournament.getN() - 1));
- }
-
- private Match findMatch(List<Match> matchList, Team homeTeam, Team awayTeam) {
- for (Match match : matchList) {
- if (match.getHomeTeam().equals(homeTeam) && match.getAwayTeam().equals(awayTeam)) {
- return match;
- }
- }
- throw new IllegalStateException("Nothing found for: " + homeTeam + " and " + awayTeam);
- }
-
- }
-
-}
Copied: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentOutputConverter.java (from rev 32019, labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentOutputConvertor.java)
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentOutputConverter.java (rev 0)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentOutputConverter.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -0,0 +1,84 @@
+package org.drools.planner.examples.travelingtournament.persistence.smart;
+
+import java.io.IOException;
+
+import org.drools.planner.examples.common.persistence.AbstractTxtOutputConverter;
+import org.drools.planner.examples.travelingtournament.domain.TravelingTournament;
+import org.drools.planner.examples.travelingtournament.domain.Team;
+import org.drools.planner.examples.travelingtournament.domain.Match;
+import org.drools.planner.examples.travelingtournament.domain.Day;
+import org.drools.planner.core.solution.Solution;
+
+/**
+ * @author Geoffrey De Smet
+ */
+public class SmartTravelingTournamentOutputConverter extends AbstractTxtOutputConverter {
+
+ private static final String OUTPUT_FILE_SUFFIX = ".trick.txt";
+
+ public static void main(String[] args) {
+ new SmartTravelingTournamentOutputConverter().convertAll();
+ }
+
+ public SmartTravelingTournamentOutputConverter() {
+ super(new SmartTravelingTournamentDaoImpl());
+ }
+
+ @Override
+ protected String getOutputFileSuffix() {
+ return OUTPUT_FILE_SUFFIX;
+ }
+
+ public TxtOutputBuilder createTxtOutputBuilder() {
+ return new SmartTravelingTournamentOutputBuilder();
+ }
+
+ public class SmartTravelingTournamentOutputBuilder extends TxtOutputBuilder {
+
+ private TravelingTournament travelingTournament;
+
+ public void setSolution(Solution solution) {
+ travelingTournament = (TravelingTournament) solution;
+ }
+
+ public void writeSolution() throws IOException {
+ int maximumTeamNameLength = 0;
+ for (Team team : travelingTournament.getTeamList()) {
+ if (team.getName().length() > maximumTeamNameLength) {
+ maximumTeamNameLength = team.getName().length();
+ }
+ }
+ for (Team team : travelingTournament.getTeamList()) {
+ bufferedWriter.write(String.format("%-" + (maximumTeamNameLength + 3) + "s", team.getName()));
+ }
+ bufferedWriter.write("\n");
+ for (Team team : travelingTournament.getTeamList()) {
+ bufferedWriter.write(String.format("%-" + (maximumTeamNameLength + 3) + "s", team.getName().replaceAll("[\\w\\d]", "-")));
+ }
+ bufferedWriter.write("\n");
+ for (Day day : travelingTournament.getDayList()) {
+ for (Team team : travelingTournament.getTeamList()) {
+ // this could be put in a hashmap first for performance
+ boolean opponentIsHome = false;
+ Team opponentTeam = null;
+ for (Match match : travelingTournament.getMatchList()) {
+ if (match.getDay().equals(day)) {
+ if (match.getHomeTeam().equals(team)) {
+ opponentIsHome = false;
+ opponentTeam = match.getAwayTeam();
+ } else if (match.getAwayTeam().equals(team)) {
+ opponentIsHome = true;
+ opponentTeam = match.getHomeTeam();
+ }
+ }
+ }
+ String opponentName = (opponentIsHome ? "@" : "") + opponentTeam.getName();
+ bufferedWriter.write(String.format("%-" + (maximumTeamNameLength + 3) + "s", opponentName));
+ }
+ bufferedWriter.write("\n");
+ }
+ }
+
+ }
+
+}
Deleted: labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentOutputConvertor.java
===================================================================
--- labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentOutputConvertor.java 2010-03-10 20:15:05 UTC (rev 32025)
+++ labs/jbossrules/trunk/drools-planner/drools-planner-examples/src/main/java/org/drools/planner/examples/travelingtournament/persistence/smart/SmartTravelingTournamentOutputConvertor.java 2010-03-10 20:23:01 UTC (rev 32026)
@@ -1,86 +0,0 @@
-package org.drools.planner.examples.travelingtournament.persistence.smart;
-
-import java.io.File;
-import java.io.IOException;
-
-import org.drools.planner.examples.common.persistence.AbstractOutputConvertor;
-import org.drools.planner.examples.common.persistence.SolutionDao;
-import org.drools.planner.examples.travelingtournament.domain.TravelingTournament;
-import org.drools.planner.examples.travelingtournament.domain.Team;
-import org.drools.planner.examples.travelingtournament.domain.Match;
-import org.drools.planner.examples.travelingtournament.domain.Day;
-import org.drools.planner.core.solution.Solution;
-
-/**
- * @author Geoffrey De Smet
- */
-public class SmartTravelingTournamentOutputConvertor extends AbstractOutputConvertor {
-
- private static final String OUTPUT_FILE_SUFFIX = ".trick.txt";
-
- public static void main(String[] args) {
- new SmartTravelingTournamentOutputConvertor().convertAll();
- }
-
- public SmartTravelingTournamentOutputConvertor() {
- super(new SmartTravelingTournamentDaoImpl());
- }
-
- @Override
- protected String getOutputFileSuffix() {
- return OUTPUT_FILE_SUFFIX;
- }
-
- public OutputBuilder createOutputBuilder() {
- return new SmartTravelingTournamentOutputBuilder();
- }
-
- public class SmartTravelingTournamentOutputBuilder extends OutputBuilder {
-
- private TravelingTournament travelingTournament;
-
- public void setSolution(Solution solution) {
- travelingTournament = (TravelingTournament) solution;
- }
-
- public void writeSolution() throws IOException {
- int maximumTeamNameLength = 0;
- for (Team team : travelingTournament.getTeamList()) {
- if (team.getName().length() > maximumTeamNameLength) {
- maximumTeamNameLength = team.getName().length();
- }
- }
- for (Team team : travelingTournament.getTeamList()) {
- bufferedWriter.write(String.format("%-" + (maximumTeamNameLength + 3) + "s", team.getName()));
- }
- bufferedWriter.write("\n");
- for (Team team : travelingTournament.getTeamList()) {
- bufferedWriter.write(String.format("%-" + (maximumTeamNameLength + 3) + "s", team.getName().replaceAll("[\\w\\d]", "-")));
- }
- bufferedWriter.write("\n");
- for (Day day : travelingTournament.getDayList()) {
- for (Team team : travelingTournament.getTeamList()) {
- // this could be put in a hashmap first for performance
- boolean opponentIsHome = false;
- Team opponentTeam = null;
- for (Match match : travelingTournament.getMatchList()) {
- if (match.getDay().equals(day)) {
- if (match.getHomeTeam().equals(team)) {
- opponentIsHome = false;
- opponentTeam = match.getAwayTeam();
- } else if (match.getAwayTeam().equals(team)) {
- opponentIsHome = true;
- opponentTeam = match.getHomeTeam();
- }
- }
- }
- String opponentName = (opponentIsHome ? "@" : "") + opponentTeam.getName();
- bufferedWriter.write(String.format("%-" + (maximumTeamNameLength + 3) + "s", opponentName));
- }
- bufferedWriter.write("\n");
- }
- }
-
- }
-
-}
\ No newline at end of file
More information about the jboss-svn-commits
mailing list