Search in sources :

Example 1 with Assignment

use of org.cpsolver.ifs.assignment.Assignment in project cpsolver by UniTime.

the class Test method main.

/**
 * Main program
 *
 * @param args
 *            problem property file, input file (optional, may be set by
 *            General.Input property), output file (optional, may be set by
 *            General.OutputFile property)
 */
public static void main(String[] args) {
    try {
        DataProperties cfg = new DataProperties();
        cfg.setProperty("Termination.StopWhenComplete", "false");
        cfg.setProperty("Termination.TimeOut", "1800");
        cfg.setProperty("General.SaveBestUnassigned", "-1");
        cfg.setProperty("Neighbour.Class", "org.cpsolver.exam.heuristics.ExamNeighbourSelection");
        if (args.length >= 1) {
            cfg.load(new FileInputStream(args[0]));
            cfg.setProperty("General.Config", new File(args[0]).getName());
        }
        cfg.putAll(System.getProperties());
        File inputFile = new File("c:\\test\\exam\\exam1070.xml");
        if (args.length >= 2) {
            inputFile = new File(args[1]);
        }
        ToolBox.setSeed(cfg.getPropertyLong("General.Seed", Math.round(Long.MAX_VALUE * Math.random())));
        cfg.setProperty("General.Input", inputFile.toString());
        String outName = inputFile.getName();
        if (outName.indexOf('.') >= 0)
            outName = outName.substring(0, outName.lastIndexOf('.')) + "s.xml";
        File outFile = new File(inputFile.getParentFile(), outName);
        if (args.length >= 3) {
            outFile = new File(args[2]);
            if (outFile.exists() && outFile.isDirectory())
                outFile = new File(outFile, outName);
            if (!outFile.exists() && !outFile.getName().endsWith(".xml"))
                outFile = new File(outFile, outName);
        }
        if (outFile.getParentFile() != null)
            outFile.getParentFile().mkdirs();
        cfg.setProperty("General.OutputFile", outFile.toString());
        cfg.setProperty("General.Output", outFile.getParent());
        String logName = outFile.getName();
        if (logName.indexOf('.') >= 0)
            logName = logName.substring(0, logName.lastIndexOf('.')) + ".log";
        ToolBox.setupLogging(new File(outFile.getParent(), logName), "true".equals(System.getProperty("debug", "false")));
        ExamModel model = new ExamModel(cfg);
        Document document = (new SAXReader()).read(new File(cfg.getProperty("General.Input")));
        int nrSolvers = cfg.getPropertyInt("Parallel.NrSolvers", 1);
        Assignment<Exam, ExamPlacement> assignment = (nrSolvers <= 1 ? new DefaultSingleAssignment<Exam, ExamPlacement>() : new DefaultParallelAssignment<Exam, ExamPlacement>());
        model.load(document, assignment);
        Solver<Exam, ExamPlacement> solver = (nrSolvers == 1 ? new Solver<Exam, ExamPlacement>(cfg) : new ParallelSolver<Exam, ExamPlacement>(cfg));
        solver.setInitalSolution(new Solution<Exam, ExamPlacement>(model, assignment));
        solver.currentSolution().addSolutionListener(new SolutionListener<Exam, ExamPlacement>() {

            @Override
            public void solutionUpdated(Solution<Exam, ExamPlacement> solution) {
            }

            @Override
            public void getInfo(Solution<Exam, ExamPlacement> solution, Map<String, String> info) {
            }

            @Override
            public void getInfo(Solution<Exam, ExamPlacement> solution, Map<String, String> info, Collection<Exam> variables) {
            }

            @Override
            public void bestCleared(Solution<Exam, ExamPlacement> solution) {
            }

            @Override
            public void bestSaved(Solution<Exam, ExamPlacement> solution) {
                ExamModel m = (ExamModel) solution.getModel();
                Assignment<Exam, ExamPlacement> a = solution.getAssignment();
                if (sLog.isInfoEnabled()) {
                    sLog.info("**BEST[" + solution.getIteration() + "]** " + (m.variables().size() > a.nrAssignedVariables() ? "V:" + a.nrAssignedVariables() + "/" + m.variables().size() + " - " : "") + "T:" + new DecimalFormat("0.00").format(m.getTotalValue(a)) + " " + m.toString(a) + (solution.getFailedIterations() > 0 ? ", F:" + sDoubleFormat.format(100.0 * solution.getFailedIterations() / solution.getIteration()) + "%" : ""));
                }
            }

            @Override
            public void bestRestored(Solution<Exam, ExamPlacement> solution) {
            }
        });
        Runtime.getRuntime().addShutdownHook(new ShutdownHook(solver));
        solver.start();
        try {
            solver.getSolverThread().join();
        } catch (InterruptedException e) {
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Solver(org.cpsolver.ifs.solver.Solver) ParallelSolver(org.cpsolver.ifs.solver.ParallelSolver) DefaultParallelAssignment(org.cpsolver.ifs.assignment.DefaultParallelAssignment) ExamModel(org.cpsolver.exam.model.ExamModel) SAXReader(org.dom4j.io.SAXReader) DecimalFormat(java.text.DecimalFormat) DataProperties(org.cpsolver.ifs.util.DataProperties) Document(org.dom4j.Document) DefaultParallelAssignment(org.cpsolver.ifs.assignment.DefaultParallelAssignment) DefaultSingleAssignment(org.cpsolver.ifs.assignment.DefaultSingleAssignment) Assignment(org.cpsolver.ifs.assignment.Assignment) ExamStudentConflictsPerExam(org.cpsolver.exam.reports.ExamStudentConflictsPerExam) Exam(org.cpsolver.exam.model.Exam) ParallelSolver(org.cpsolver.ifs.solver.ParallelSolver) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) ExamPlacement(org.cpsolver.exam.model.ExamPlacement) DefaultSingleAssignment(org.cpsolver.ifs.assignment.DefaultSingleAssignment) File(java.io.File)

Example 2 with Assignment

use of org.cpsolver.ifs.assignment.Assignment in project cpsolver by UniTime.

the class ExamColoringConstruction method selectNeighbour.

@Override
public Neighbour<Exam, ExamPlacement> selectNeighbour(final Solution<Exam, ExamPlacement> solution) {
    ExamModel model = (ExamModel) solution.getModel();
    // if (!model.assignedVariables().isEmpty()) return null;
    final HashMap<Exam, Vertex> vertices = new HashMap<Exam, Vertex>();
    for (Exam x : model.variables()) {
        vertices.put(x, new Vertex(x));
    }
    for (ExamStudent s : model.getStudents()) {
        for (Exam x : s.variables()) {
            for (Exam y : s.variables()) {
                if (!x.equals(y)) {
                    vertices.get(x).neighbors().add(vertices.get(y));
                    vertices.get(y).neighbors().add(vertices.get(x));
                }
            }
        }
    }
    for (ExamInstructor i : model.getInstructors()) {
        for (Exam x : i.variables()) {
            for (Exam y : i.variables()) {
                if (!x.equals(y)) {
                    vertices.get(x).neighbors().add(vertices.get(y));
                    vertices.get(y).neighbors().add(vertices.get(x));
                }
            }
        }
    }
    iProgress.setPhase("Graph coloring-based construction", vertices.size());
    iProgress.info("Looking for a conflict-free assignment using " + model.getPeriods().size() + " periods.");
    iT0 = JProf.currentTimeSec();
    iTimeLimitReached = false;
    if (iMode.isGreedy()) {
        iProgress.info("Using greedy heuristics only (no backtracking)...");
    } else if (backTrack(solution, 0, (iMode.isRedundant() ? null : new HashSet<Integer>()), vertices.values())) {
        iProgress.info("Success!");
    } else if (iTimeLimitReached) {
        iProgress.info("There was no conflict-free schedule found during the given time.");
    } else if (iSolver.isStop()) {
        iProgress.info("Solver was stopped.");
    } else {
        if (iMode.isRedundant())
            iProgress.info("There is no conflict-free schedule!");
        else
            iProgress.info("Conflict-free schedule not found.");
    }
    if (iMode.isConstraintCheck())
        solution.restoreBest();
    HashSet<Vertex> remaning = new HashSet<Vertex>();
    for (Vertex v : vertices.values()) if (v.color() < 0)
        remaning.add(v);
    remaining: while (!remaning.isEmpty()) {
        Vertex vertex = null;
        for (Vertex v : remaning) if (vertex == null || v.compareTo(vertex) < 0)
            vertex = v;
        remaning.remove(vertex);
        for (int color : vertex.domain()) if (vertex.colorize(solution.getAssignment(), color))
            continue remaining;
    }
    if (!iMode.isConstraintCheck()) {
        return new Neighbour<Exam, ExamPlacement>() {

            @Override
            public void assign(Assignment<Exam, ExamPlacement> assignment, long iteration) {
                iProgress.info("Using graph coloring solution ...");
                for (Vertex vertex : new TreeSet<Vertex>(vertices.values())) {
                    ExamPeriodPlacement period = vertex.period();
                    if (period == null || !vertex.exam().checkDistributionConstraints(assignment, period))
                        continue;
                    Set<ExamRoomPlacement> rooms = findRooms(assignment, vertex.exam(), period);
                    if (rooms == null)
                        continue;
                    assignment.assign(iteration, new ExamPlacement(vertex.exam(), period, rooms));
                }
                HashSet<Vertex> unassigned = new HashSet<Vertex>();
                for (Vertex vertex : vertices.values()) {
                    if (assignment.getValue(vertex.exam()) == null) {
                        unassigned.add(vertex);
                        vertex.colorize(assignment, -1);
                    }
                }
                solution.saveBest();
                iProgress.info("Extending ...");
                unassigned: while (!unassigned.isEmpty()) {
                    Vertex vertex = null;
                    for (Vertex v : unassigned) if (vertex == null || v.compareTo(vertex) < 0)
                        vertex = v;
                    unassigned.remove(vertex);
                    for (int color : vertex.domain()) {
                        if (!vertex.colorize(assignment, color))
                            continue;
                        ExamPeriodPlacement period = vertex.period(color);
                        if (period == null || !vertex.exam().checkDistributionConstraints(assignment, period))
                            continue;
                        Set<ExamRoomPlacement> rooms = findRooms(assignment, vertex.exam(), period);
                        if (rooms == null)
                            continue;
                        assignment.assign(iteration, new ExamPlacement(vertex.exam(), period, rooms));
                        continue unassigned;
                    }
                    vertex.colorize(assignment, -1);
                }
                solution.saveBest();
                iProgress.info("Construction done.");
            }

            @Override
            public double value(Assignment<Exam, ExamPlacement> assignment) {
                return 0;
            }

            @Override
            public Map<Exam, ExamPlacement> assignments() {
                throw new UnsupportedOperationException();
            }
        };
    }
    return null;
}
Also used : ExamInstructor(org.cpsolver.exam.model.ExamInstructor) Set(java.util.Set) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) HashMap(java.util.HashMap) ExamModel(org.cpsolver.exam.model.ExamModel) ExamStudent(org.cpsolver.exam.model.ExamStudent) Assignment(org.cpsolver.ifs.assignment.Assignment) ExamRoomPlacement(org.cpsolver.exam.model.ExamRoomPlacement) Neighbour(org.cpsolver.ifs.model.Neighbour) ExamPlacement(org.cpsolver.exam.model.ExamPlacement) TreeSet(java.util.TreeSet) ExamPeriodPlacement(org.cpsolver.exam.model.ExamPeriodPlacement) Exam(org.cpsolver.exam.model.Exam) HashSet(java.util.HashSet)

Example 3 with Assignment

use of org.cpsolver.ifs.assignment.Assignment in project cpsolver by UniTime.

the class Solution2Expectations method main.

public static void main(String[] args) {
    try {
        ToolBox.configureLogging();
        DataProperties config = new DataProperties();
        String command = args[0];
        if ("real2exp".equals(command)) {
            StudentSectioningModel model = new StudentSectioningModel(config);
            Assignment<Request, Enrollment> assignment = new DefaultSingleAssignment<Request, Enrollment>();
            StudentSectioningXMLLoader loader = new StudentSectioningXMLLoader(model, assignment);
            loader.setInputFile(new File(args[1]));
            loader.load();
            sLog.info("Loaded: " + ToolBox.dict2string(model.getExtendedInfo(assignment), 2));
            for (Student s : model.getStudents()) s.setDummy(true);
            model.computeOnlineSectioningInfos(assignment);
            for (Student s : model.getStudents()) s.setDummy(false);
            for (Request request : model.variables()) assignment.unassign(0, request);
            Solution<Request, Enrollment> solution = new Solution<Request, Enrollment>(model, assignment, 0, 0);
            Solver<Request, Enrollment> solver = new Solver<Request, Enrollment>(config);
            solver.setInitalSolution(solution);
            new StudentSectioningXMLSaver(solver).save(new File(args[2]));
            sLog.info("Saved: " + ToolBox.dict2string(model.getExtendedInfo(assignment), 2));
        } else if ("ll2exp".equals(command)) {
            StudentSectioningModel model = new StudentSectioningModel(config);
            Assignment<Request, Enrollment> assignment = new DefaultSingleAssignment<Request, Enrollment>();
            StudentSectioningXMLLoader loader = new StudentSectioningXMLLoader(model, assignment);
            loader.setInputFile(new File(args[1]));
            loader.load();
            sLog.info("Loaded: " + ToolBox.dict2string(model.getExtendedInfo(assignment), 2));
            model.computeOnlineSectioningInfos(assignment);
            for (Request request : model.variables()) assignment.unassign(0, request);
            Solution<Request, Enrollment> solution = new Solution<Request, Enrollment>(model, assignment, 0, 0);
            Solver<Request, Enrollment> solver = new Solver<Request, Enrollment>(config);
            solver.setInitalSolution(solution);
            new StudentSectioningXMLSaver(solver).save(new File(args[2]));
            sLog.info("Saved: " + ToolBox.dict2string(model.getExtendedInfo(assignment), 2));
        } else if ("students".equals(command)) {
            StudentSectioningModel model = new StudentSectioningModel(config);
            Assignment<Request, Enrollment> assignment = new DefaultSingleAssignment<Request, Enrollment>();
            StudentSectioningXMLLoader loader = new StudentSectioningXMLLoader(model, assignment);
            loader.setInputFile(new File(args[1]));
            loader.setLoadStudents(false);
            loader.load();
            sLog.info("Loaded [1]: " + ToolBox.dict2string(model.getExtendedInfo(assignment), 2));
            StudentSectioningXMLLoader loder2 = new StudentSectioningXMLLoader(model, assignment);
            loder2.setInputFile(new File(args[2]));
            loder2.setLoadOfferings(false);
            loder2.setLoadStudents(true);
            loder2.load();
            sLog.info("Loaded [2]: " + ToolBox.dict2string(model.getExtendedInfo(assignment), 2));
            Solution<Request, Enrollment> solution = new Solution<Request, Enrollment>(model, assignment, 0, 0);
            Solver<Request, Enrollment> solver = new Solver<Request, Enrollment>(config);
            solver.setInitalSolution(solution);
            new StudentSectioningXMLSaver(solver).save(new File(args[3]));
            sLog.info("Saved [3]: " + ToolBox.dict2string(model.getExtendedInfo(assignment), 2));
        } else {
            sLog.error("Unknown command: " + command);
        }
    } catch (Exception e) {
        sLog.error(e.getMessage(), e);
    }
}
Also used : Solver(org.cpsolver.ifs.solver.Solver) DataProperties(org.cpsolver.ifs.util.DataProperties) Request(org.cpsolver.studentsct.model.Request) Student(org.cpsolver.studentsct.model.Student) DefaultSingleAssignment(org.cpsolver.ifs.assignment.DefaultSingleAssignment) Assignment(org.cpsolver.ifs.assignment.Assignment) Enrollment(org.cpsolver.studentsct.model.Enrollment) DefaultSingleAssignment(org.cpsolver.ifs.assignment.DefaultSingleAssignment) File(java.io.File) Solution(org.cpsolver.ifs.solution.Solution)

Example 4 with Assignment

use of org.cpsolver.ifs.assignment.Assignment in project cpsolver by UniTime.

the class Test method execute.

/**
 * Run the problem
 */
public void execute() {
    int nrSolvers = getProperties().getPropertyInt("Parallel.NrSolvers", 1);
    Solver<TeachingRequest.Variable, TeachingAssignment> solver = (nrSolvers == 1 ? new Solver<TeachingRequest.Variable, TeachingAssignment>(getProperties()) : new ParallelSolver<TeachingRequest.Variable, TeachingAssignment>(getProperties()));
    Assignment<TeachingRequest.Variable, TeachingAssignment> assignment = (nrSolvers <= 1 ? new DefaultSingleAssignment<TeachingRequest.Variable, TeachingAssignment>() : new DefaultParallelAssignment<TeachingRequest.Variable, TeachingAssignment>());
    if (!load(new File(getProperties().getProperty("input", "input/solution.xml")), assignment))
        return;
    solver.setInitalSolution(new Solution<TeachingRequest.Variable, TeachingAssignment>(this, assignment));
    solver.currentSolution().addSolutionListener(new SolutionListener<TeachingRequest.Variable, TeachingAssignment>() {

        @Override
        public void solutionUpdated(Solution<TeachingRequest.Variable, TeachingAssignment> solution) {
        }

        @Override
        public void getInfo(Solution<TeachingRequest.Variable, TeachingAssignment> solution, Map<String, String> info) {
        }

        @Override
        public void getInfo(Solution<TeachingRequest.Variable, TeachingAssignment> solution, Map<String, String> info, Collection<TeachingRequest.Variable> variables) {
        }

        @Override
        public void bestCleared(Solution<TeachingRequest.Variable, TeachingAssignment> solution) {
        }

        @Override
        public void bestSaved(Solution<TeachingRequest.Variable, TeachingAssignment> solution) {
            Model<TeachingRequest.Variable, TeachingAssignment> m = solution.getModel();
            Assignment<TeachingRequest.Variable, TeachingAssignment> a = solution.getAssignment();
            System.out.println("**BEST[" + solution.getIteration() + "]** " + m.toString(a));
        }

        @Override
        public void bestRestored(Solution<TeachingRequest.Variable, TeachingAssignment> solution) {
        }
    });
    solver.start();
    try {
        solver.getSolverThread().join();
    } catch (InterruptedException e) {
    }
    Solution<TeachingRequest.Variable, TeachingAssignment> solution = solver.lastSolution();
    solution.restoreBest();
    sLog.info("Best solution found after " + solution.getBestTime() + " seconds (" + solution.getBestIteration() + " iterations).");
    sLog.info("Number of assigned variables is " + solution.getModel().assignedVariables(solution.getAssignment()).size());
    sLog.info("Total value of the solution is " + solution.getModel().getTotalValue(solution.getAssignment()));
    sLog.info("Info: " + ToolBox.dict2string(solution.getExtendedInfo(), 2));
    File outDir = new File(getProperties().getProperty("output", "output"));
    outDir.mkdirs();
    save(outDir, solution.getAssignment());
    try {
        generateReports(outDir, assignment);
    } catch (IOException e) {
        sLog.error("Failed to write reports: " + e.getMessage(), e);
    }
    ConflictStatistics<TeachingRequest.Variable, TeachingAssignment> cbs = null;
    for (Extension<TeachingRequest.Variable, TeachingAssignment> extension : solver.getExtensions()) {
        if (ConflictStatistics.class.isInstance(extension)) {
            cbs = (ConflictStatistics<TeachingRequest.Variable, TeachingAssignment>) extension;
        }
    }
    if (cbs != null) {
        PrintWriter out = null;
        try {
            out = new PrintWriter(new FileWriter(new File(outDir, "cbs.txt")));
            out.println(cbs.toString());
            out.flush();
            out.close();
        } catch (IOException e) {
            sLog.error("Failed to write CBS: " + e.getMessage(), e);
        } finally {
            if (out != null)
                out.close();
        }
    }
}
Also used : Solver(org.cpsolver.ifs.solver.Solver) ParallelSolver(org.cpsolver.ifs.solver.ParallelSolver) DefaultParallelAssignment(org.cpsolver.ifs.assignment.DefaultParallelAssignment) FileWriter(java.io.FileWriter) TeachingRequest(org.cpsolver.instructor.model.TeachingRequest) DefaultParallelAssignment(org.cpsolver.ifs.assignment.DefaultParallelAssignment) DefaultSingleAssignment(org.cpsolver.ifs.assignment.DefaultSingleAssignment) Assignment(org.cpsolver.ifs.assignment.Assignment) TeachingAssignment(org.cpsolver.instructor.model.TeachingAssignment) PrintWriter(java.io.PrintWriter) ParallelSolver(org.cpsolver.ifs.solver.ParallelSolver) IOException(java.io.IOException) TeachingAssignment(org.cpsolver.instructor.model.TeachingAssignment) Model(org.cpsolver.ifs.model.Model) InstructorSchedulingModel(org.cpsolver.instructor.model.InstructorSchedulingModel) DefaultSingleAssignment(org.cpsolver.ifs.assignment.DefaultSingleAssignment) File(java.io.File)

Aggregations

Assignment (org.cpsolver.ifs.assignment.Assignment)4 File (java.io.File)3 DefaultSingleAssignment (org.cpsolver.ifs.assignment.DefaultSingleAssignment)3 Solver (org.cpsolver.ifs.solver.Solver)3 IOException (java.io.IOException)2 Exam (org.cpsolver.exam.model.Exam)2 ExamModel (org.cpsolver.exam.model.ExamModel)2 ExamPlacement (org.cpsolver.exam.model.ExamPlacement)2 DefaultParallelAssignment (org.cpsolver.ifs.assignment.DefaultParallelAssignment)2 ParallelSolver (org.cpsolver.ifs.solver.ParallelSolver)2 DataProperties (org.cpsolver.ifs.util.DataProperties)2 FileInputStream (java.io.FileInputStream)1 FileWriter (java.io.FileWriter)1 PrintWriter (java.io.PrintWriter)1 DecimalFormat (java.text.DecimalFormat)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Set (java.util.Set)1 TreeSet (java.util.TreeSet)1 ExamInstructor (org.cpsolver.exam.model.ExamInstructor)1