Search in sources :

Example 6 with Solver

use of org.cpsolver.ifs.solver.Solver in project cpsolver by UniTime.

the class Test method test.

private static void test(DataProperties properties) {
    try {
        int tests = properties.getPropertyInt("Rpp.NrTests", 10);
        int min = properties.getPropertyInt("Rpp.Min", 0);
        int max = properties.getPropertyInt("Rpp.Max", -1);
        PrintWriter res = new PrintWriter(new FileWriter(properties.getProperty("General.Output") + File.separator + "result.pl"));
        PrintWriter stat = new PrintWriter(new FileWriter(properties.getProperty("General.Output") + File.separator + "stat.pl"));
        PrintWriter txt = new PrintWriter(new FileWriter(properties.getProperty("General.Output") + File.separator + "stat.csv"));
        txt.println("gen;time[s];timeRMS;assigned;assignedRMS;iters;itersRMS");
        java.text.DecimalFormat nf = new java.text.DecimalFormat("0.000", new java.text.DecimalFormatSymbols(Locale.US));
        for (int genNr = min; genNr <= max; genNr++) {
            FileInputStream fis = new FileInputStream(properties.getProperty("General.Input") + File.separator + "gen" + genNr + ".pl");
            List<PrologFile.Term> v1 = PrologFile.readTermsFromStream(fis, "objects");
            fis.close();
            double time = 0;
            long assigned = 0;
            long iters = 0;
            double time2 = 0;
            long assigned2 = 0;
            long iters2 = 0;
            for (int t = 1; t <= tests; t++) {
                RPPModel m = loadModel(properties.getPropertyInt("Rpp.ProblemWidth", 40), properties.getPropertyInt("Rpp.ProblemHeight", 14), v1);
                Solver<Rectangle, Location> s = new Solver<Rectangle, Location>(properties);
                s.setInitalSolution(m);
                s.start();
                s.getSolverThread().join();
                Solution<Rectangle, Location> best = s.currentSolution();
                best.restoreBest();
                iters += best.getBestIteration();
                iters2 += (best.getBestIteration() * best.getBestIteration());
                time += best.getBestTime();
                time2 += (best.getBestTime() * best.getBestTime());
                assigned += (best.getModel().variables().size() - best.getModel().getBestUnassignedVariables());
                assigned2 += (best.getModel().variables().size() - best.getModel().getBestUnassignedVariables()) * (best.getModel().variables().size() - best.getModel().getBestUnassignedVariables());
                res.println("result(" + genNr + "," + t + "," + nf.format(best.getBestTime()) + "," + (best.getModel().variables().size() - best.getModel().getBestUnassignedVariables()) + "," + best.getBestIteration() + ",");
                Collection<Rectangle> notPlaced = best.getModel().bestUnassignedVariables(best.getAssignment());
                if (notPlaced == null)
                    notPlaced = new ArrayList<Rectangle>();
                res.print("  unassigned(" + (2 * notPlaced.size()) + "/[");
                for (Iterator<Rectangle> it = notPlaced.iterator(); it.hasNext(); ) {
                    Rectangle rect = it.next();
                    res.print(rect.getName() + "X," + rect.getName() + "Y" + (it.hasNext() ? "," : ""));
                }
                res.println("]),");
                int perts = 0;
                StringBuffer sb = new StringBuffer();
                for (Rectangle rect : ((RPPModel) best.getModel()).variables()) {
                    if (rect.getBestAssignment() != null) {
                        sb.append(sb.length() == 0 ? "" : ",");
                        sb.append(rect.getName() + "X-" + (rect.getBestAssignment()).getX());
                        sb.append(sb.length() == 0 ? "" : ",");
                        sb.append(rect.getName() + "Y-" + (rect.getBestAssignment()).getY());
                        perts++;
                    }
                }
                res.println("  assigned(" + (2 * perts) + "/[" + sb + "])");
                res.println(").");
                res.flush();
            }
            txt.println(genNr + ";" + nf.format(time / tests) + ";" + nf.format(ToolBox.rms(tests, time, time2)) + ";" + nf.format(((double) assigned) / tests) + ";" + nf.format(ToolBox.rms(tests, assigned, assigned2)) + ";" + nf.format(((double) iters) / tests) + ";" + nf.format(ToolBox.rms(tests, iters, iters2)));
            txt.flush();
            stat.println("averages( problem( " + genNr + " ), time( " + nf.format(time / tests) + " ), assigned( " + nf.format(((double) assigned) / tests) + " ) ).");
            stat.println("deviations( problem( " + genNr + " ), time( " + nf.format(ToolBox.rms(tests, time, time2)) + " ), assigned( " + nf.format(ToolBox.rms(tests, assigned, assigned2)) + " ) ).");
            stat.flush();
        }
        res.close();
        txt.close();
        stat.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Solver(org.cpsolver.ifs.solver.Solver) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) FileInputStream(java.io.FileInputStream) PrintWriter(java.io.PrintWriter)

Example 7 with Solver

use of org.cpsolver.ifs.solver.Solver in project cpsolver by UniTime.

the class Test method test.

private static void test(DataProperties properties) throws Exception {
    boolean sameProblemStep = properties.getPropertyBoolean("CSP.SameProblemEachStep", false);
    boolean sameProblemTest = properties.getPropertyBoolean("CSP.SameProblemEachTest", false);
    int nrVars = properties.getPropertyInt("CSP.NrVariables", 20);
    int nrKernels = properties.getPropertyInt("CSP.NrKernels", 2);
    int nrKernelVariables = properties.getPropertyInt("CSP.KernelSize", 8);
    int nrVariablesMin = properties.getPropertyInt("CSP.NrVariablesMin", nrVars);
    int nrVariablesMax = properties.getPropertyInt("CSP.NrVariablesMax", nrVars);
    int nrVariablesStep = properties.getPropertyInt("CSP.NrVariablesStep", 1);
    int nrValues = properties.getPropertyInt("CSP.DomainSize", 10);
    double nrValuesRatio = properties.getPropertyDouble("CSP.DomainSizeRatio", -1);
    float kernelTightness = properties.getPropertyFloat("CSP.KernelTightness", 0.097f);
    float kernelDensity = properties.getPropertyFloat("CSP.KernelDensity", 0.097f);
    float tightnessInit = properties.getPropertyFloat("CSP.Tightness", 0.4f);
    float tightnessMin = properties.getPropertyFloat("CSP.TightnessMin", tightnessInit);
    float tightnessMax = properties.getPropertyFloat("CSP.TightnessMax", tightnessInit) + 1e-6f;
    float tightnessStep = properties.getPropertyFloat("CSP.TightnessStep", 0.1f);
    float densityInit = properties.getPropertyFloat("CSP.Density", 0.4f);
    float densityMin = properties.getPropertyFloat("CSP.DensityMin", densityInit);
    float densityMax = properties.getPropertyFloat("CSP.DensityMax", densityInit) + 1e-6f;
    float densityStep = properties.getPropertyFloat("CSP.DensityStep", 0.1f);
    long seed = properties.getPropertyLong("CSP.Seed", System.currentTimeMillis());
    int nrTests = properties.getPropertyInt("CPS.NrTests", 10);
    boolean mpp = properties.getPropertyBoolean("General.MPP", false);
    PrintWriter logStat = new PrintWriter(new FileWriter(properties.getProperty("General.Output") + File.separator + "rcsp_" + nrVariablesMin + "_" + nrValues + ".csv"));
    PrintWriter logAvgStat = new PrintWriter(new FileWriter(properties.getProperty("General.Output") + File.separator + "avg_stat.csv"));
    PrintWriter log = new PrintWriter(new FileWriter(properties.getProperty("General.Output") + File.separator + "info.txt"));
    logStat.println("testNr;nrVars;nrVals;density[%];tightness[%];time[s];iters;speed[it/s];unassConstr;assigned;assigned[%]" + (mpp ? ";perts;perts[%]" : "") + ";value;totalValue");
    logAvgStat.println("nrVars;nrVals;density[%];tightness[%];time[s];RMStime[s];iters;RMSiters;speed[it/s];unassConst;assigned;RMSassigned;assigned[%]" + (mpp ? ";perts;RMSperts;perts[%]" : "") + ";value;RMSvalue;totalValue;RMStotalValue");
    System.out.println("Number of variables: " + nrVariablesMin + " .. " + nrVariablesMax + "  (step=" + nrVariablesStep + ")");
    System.out.println("Density:             " + densityMin + " .. " + densityMax + "  (step=" + densityStep + ")");
    System.out.println("Tightness:           " + tightnessMin + " .. " + tightnessMax + "  (step=" + tightnessStep + ")");
    for (int nrVariables = nrVariablesMin; nrVariables <= nrVariablesMax; nrVariables += nrVariablesStep) {
        if (nrValuesRatio > 0.0)
            nrValues = (int) Math.round(nrValuesRatio * nrVariables);
        for (float density = densityMin; density <= densityMax; density += densityStep) {
            for (float tightness = tightnessMin; tightness <= tightnessMax; tightness += tightnessStep) {
                log.println("CSP{#Var=" + nrVariables + ", #Val=" + nrValues + ", P(density)=" + sDoubleFormat.format(100.0 * density) + "%, P(tighness)=" + sDoubleFormat.format(100.0 * tightness) + ", " + nrKernels + "x Kernel{#Var=" + nrKernelVariables + ", P(density)=" + sDoubleFormat.format(100.0 * kernelDensity) + "%, P(tighness)=" + sDoubleFormat.format(100.0 * kernelTightness) + "%}}");
                double sumTime = 0;
                double sumTime2 = 0;
                int sumIters = 0;
                int sumIters2 = 0;
                int sumConfl = 0;
                int sumAssign = 0;
                int sumAssign2 = 0;
                int sumPert = 0;
                int sumPert2 = 0;
                int sumVal = 0;
                int sumVal2 = 0;
                int sumTotalVal = 0;
                int sumTotalVal2 = 0;
                for (int test = 1; test <= nrTests; test++) {
                    log.println("  " + test + ". test");
                    log.flush();
                    properties.setProperty("CSP.NrVariables", String.valueOf(nrVariables));
                    properties.setProperty("CSP.Tightness", String.valueOf(tightness));
                    properties.setProperty("CSP.Density", String.valueOf(density));
                    long currentSeed = (seed * 1000000L) + (1000 * (long) ((sameProblemStep ? densityMin : density) * 1000.0)) + ((long) ((sameProblemStep ? tightnessMin : tightness) * 1000.0));
                    currentSeed = (currentSeed * nrTests) + (sameProblemTest ? 0 : test - 1);
                    sLogger.debug("Seed: " + currentSeed);
                    StructuredCSPModel csp = new StructuredCSPModel(properties, currentSeed);
                    Solver<CSPVariable, CSPValue> s = new Solver<CSPVariable, CSPValue>(properties);
                    s.setInitalSolution(csp);
                    s.currentSolution().clearBest();
                    s.start();
                    try {
                        s.getSolverThread().join();
                    } catch (NullPointerException npe) {
                    }
                    if (s.lastSolution().getBestInfo() == null)
                        sLogger.error("No solution found :-(");
                    sLogger.debug("Last solution:" + s.lastSolution().getInfo());
                    Solution<CSPVariable, CSPValue> best = s.lastSolution();
                    sLogger.debug("Best solution:" + s.lastSolution().getBestInfo());
                    best.restoreBest();
                    int val = 0;
                    for (CSPValue v : best.getAssignment().assignedValues()) val += (int) v.toDouble();
                    int totalVal = val + (best.getModel().unassignedVariables(best.getAssignment()).size() * nrValues);
                    sLogger.debug("Last solution:" + best.getInfo());
                    logStat.println(test + ";" + nrVariables + ";" + nrValues + ";" + sDoubleFormat.format(density) + ";" + sDoubleFormat.format(tightness) + ";" + sDoubleFormat.format(best.getTime()) + ";" + best.getIteration() + ";" + sDoubleFormat.format((best.getIteration()) / best.getTime()) + ";" + best.getModel().unassignedHardConstraints(best.getAssignment()).size() + ";" + best.getModel().assignedVariables(best.getAssignment()).size() + ";" + sDoubleFormat.format(100.0 * best.getModel().assignedVariables(best.getAssignment()).size() / best.getModel().variables().size()) + (mpp ? ";" + (best.getModel().perturbVariables(best.getAssignment()).size() + best.getModel().unassignedVariables(best.getAssignment()).size()) + ";" + sDoubleFormat.format(100.0 * (best.getModel().perturbVariables(best.getAssignment()).size() + best.getModel().unassignedVariables(best.getAssignment()).size()) / best.getModel().variables().size()) : "") + ";" + val + ";" + totalVal);
                    log.println("    seed:         " + currentSeed);
                    log.println("    constraints:  " + best.getModel().constraints().size());
                    for (Iterator<Constraint<CSPVariable, CSPValue>> i = best.getModel().constraints().iterator(); i.hasNext(); ) {
                        CSPBinaryConstraint c = (CSPBinaryConstraint) i.next();
                        log.println("      " + c.getName() + " (" + c.first().getName() + "," + c.second().getName() + ")");
                        for (CSPValue v0 : c.first().values(best.getAssignment())) {
                            log.print("        ");
                            for (CSPValue v1 : c.second().values(best.getAssignment())) log.print(c.isConsistent(v0, v1) ? "1 " : "0 ");
                        }
                        log.println();
                    }
                    log.println("    time:         " + sDoubleFormat.format(best.getTime()) + " s");
                    log.println("    iteration:    " + best.getIteration());
                    log.println("    speed:        " + sDoubleFormat.format((best.getIteration()) / best.getTime()) + " it/s");
                    log.println("    assigned:     " + best.getModel().assignedVariables(best.getAssignment()).size() + " (" + sDoubleFormat.format(100.0 * best.getModel().assignedVariables(best.getAssignment()).size() / best.getModel().variables().size()) + "%)");
                    log.println("    total value:  " + val);
                    if (mpp)
                        log.println("    perturbations:" + (best.getModel().perturbVariables(best.getAssignment()).size() + best.getModel().unassignedVariables(best.getAssignment()).size()) + " (" + sDoubleFormat.format(100.0 * (best.getModel().perturbVariables(best.getAssignment()).size() + best.getModel().unassignedVariables(best.getAssignment()).size()) / best.getModel().variables().size()) + "%)");
                    log.print("    solution:     ");
                    for (CSPVariable v : ((CSPModel) best.getModel()).variables()) {
                        if (v.getBestAssignment() == null)
                            continue;
                        log.print(v.getName() + "=" + v.getBestAssignment().getName());
                        log.print(", ");
                    }
                    log.println();
                    sumTime += best.getTime();
                    sumTime2 += best.getTime() * best.getTime();
                    sumIters += best.getIteration();
                    sumIters2 += best.getIteration() * best.getIteration();
                    sumConfl += best.getModel().unassignedHardConstraints(best.getAssignment()).size();
                    sumAssign += best.getModel().assignedVariables(best.getAssignment()).size();
                    sumAssign2 += best.getModel().assignedVariables(best.getAssignment()).size() * best.getModel().assignedVariables(best.getAssignment()).size();
                    sumVal += val;
                    sumVal2 += val * val;
                    sumTotalVal += totalVal;
                    sumTotalVal2 += totalVal * totalVal;
                    if (mpp) {
                        sumPert += (best.getModel().perturbVariables(best.getAssignment()).size() + best.getModel().unassignedVariables(best.getAssignment()).size());
                        sumPert2 += (best.getModel().perturbVariables(best.getAssignment()).size() + best.getModel().unassignedVariables(best.getAssignment()).size()) * (best.getModel().perturbVariables(best.getAssignment()).size() + best.getModel().unassignedVariables(best.getAssignment()).size());
                    }
                    log.flush();
                    logStat.flush();
                }
                logAvgStat.println(nrVariables + ";" + nrValues + ";" + sDoubleFormat.format(density) + ";" + sDoubleFormat.format(tightness) + ";" + sDoubleFormat.format(sumTime / nrTests) + ";" + sDoubleFormat.format(ToolBox.rms(nrTests, sumTime, sumTime2)) + ";" + sDoubleFormat.format(((double) sumIters) / nrTests) + ";" + sDoubleFormat.format(ToolBox.rms(nrTests, sumIters, sumIters2)) + ";" + sDoubleFormat.format((sumIters) / sumTime) + ";" + sDoubleFormat.format(((double) sumConfl) / nrTests) + ";" + sDoubleFormat.format(((double) sumAssign) / nrTests) + ";" + sDoubleFormat.format(ToolBox.rms(nrTests, sumAssign, sumAssign2)) + ";" + sDoubleFormat.format(100.0 * (sumAssign) / (nrVariables * nrTests)) + (mpp ? ";" + sDoubleFormat.format(((double) sumPert) / nrTests) + ";" + sDoubleFormat.format(ToolBox.rms(nrTests, sumPert, sumPert2)) + ";" + sDoubleFormat.format(100.0 * (sumPert) / (nrVariables * nrTests)) : "") + ";" + sDoubleFormat.format(((double) sumVal) / (nrTests * nrVariables)) + ";" + sDoubleFormat.format(ToolBox.rms(nrTests, (double) sumVal / nrVariables, (double) sumVal2 / (nrVariables * nrVariables))) + ";" + sDoubleFormat.format(((double) sumTotalVal) / nrTests) + ";" + sDoubleFormat.format(ToolBox.rms(nrTests, sumTotalVal, sumTotalVal2)));
                logAvgStat.flush();
            }
        }
    }
    log.flush();
    log.close();
    logStat.flush();
    logStat.close();
    logAvgStat.flush();
    logAvgStat.close();
}
Also used : Solver(org.cpsolver.ifs.solver.Solver) Constraint(org.cpsolver.ifs.model.Constraint) FileWriter(java.io.FileWriter) Constraint(org.cpsolver.ifs.model.Constraint) PrintWriter(java.io.PrintWriter)

Example 8 with Solver

use of org.cpsolver.ifs.solver.Solver in project cpsolver by UniTime.

the class Test method test3.

public static void test3(DataProperties properties, File xmlFile) throws Exception {
    int nrTests = properties.getPropertyInt("Test.NrTests", 1);
    PrintWriter logStat = new PrintWriter(new FileWriter(properties.getProperty("General.Output") + File.separator + "output.csv"));
    logStat.println("fillFact;nrResources;testNr;time[s];iters;speed[it/s];assigned;assigned[%];value;totalValue");
    boolean saveSol = properties.getPropertyBoolean("General.SaveSolutionXML", true);
    boolean assign = properties.getPropertyBoolean("General.InitialAssignment", true);
    int forcedPerturbances = properties.getPropertyInt("General.ForcedPerturbances", 0);
    for (int test = 1; test <= nrTests; test++) {
        Assignment<Activity, Location> assignment = new DefaultSingleAssignment<Activity, Location>();
        TimetableModel m = TimetableModel.loadFromXML(xmlFile, assign ? assignment : null);
        if (forcedPerturbances > 0) {
            List<Activity> initialVariables = new ArrayList<Activity>();
            for (Activity v : m.variables()) {
                if (v.getInitialAssignment() != null)
                    initialVariables.add(v);
            }
            for (int i = 0; i < forcedPerturbances; i++) {
                if (initialVariables.isEmpty())
                    break;
                Activity var = ToolBox.random(initialVariables);
                initialVariables.remove(var);
                var.removeInitialValue();
            }
        }
        Solver<Activity, Location> s = new Solver<Activity, Location>(properties);
        s.setInitalSolution(new Solution<Activity, Location>(m, assignment));
        s.currentSolution().clearBest();
        s.start();
        try {
            s.getSolverThread().join();
        } catch (NullPointerException npe) {
        }
        if (s.lastSolution().getBestInfo() == null)
            sLogger.error("No solution found :-(");
        sLogger.debug("Last solution:" + s.lastSolution().getInfo());
        Solution<Activity, Location> best = s.lastSolution();
        sLogger.debug("Best solution:" + s.lastSolution().getBestInfo());
        best.restoreBest();
        int val = 0;
        for (Location loc : best.getAssignment().assignedValues()) val += (int) loc.toDouble();
        if (saveSol)
            m.saveAsXML(properties, false, best, best.getAssignment(), new File(properties.getProperty("General.Output") + File.separator + "solution_" + test + ".xml"));
        sLogger.debug("Last solution:" + best.getInfo());
        logStat.println(sDoubleFormat.format(properties.getPropertyDouble("Generator.FillFactor", 0.0)) + ";" + sDoubleFormat.format(properties.getPropertyInt("Generator.NrRooms", 0)) + ";" + test + ";" + sDoubleFormat.format(best.getTime()) + ";" + best.getIteration() + ";" + sDoubleFormat.format((best.getIteration()) / best.getTime()) + ";" + best.getAssignment().nrAssignedVariables() + ";" + sDoubleFormat.format(100.0 * best.getAssignment().nrAssignedVariables() / best.getModel().variables().size()) + ";" + val);
        sLogger.debug("    time:         " + sDoubleFormat.format(best.getTime()) + " s");
        sLogger.debug("    iteration:    " + best.getIteration());
        sLogger.debug("    speed:        " + sDoubleFormat.format((best.getIteration()) / best.getTime()) + " it/s");
        sLogger.debug("    assigned:     " + best.getAssignment().nrAssignedVariables() + " (" + sDoubleFormat.format(100.0 * best.getAssignment().nrAssignedVariables() / best.getModel().variables().size()) + "%)");
        sLogger.debug("    value:        " + val);
        logStat.flush();
    }
    logStat.close();
}
Also used : Solver(org.cpsolver.ifs.solver.Solver) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) DefaultSingleAssignment(org.cpsolver.ifs.assignment.DefaultSingleAssignment) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 9 with Solver

use of org.cpsolver.ifs.solver.Solver in project cpsolver by UniTime.

the class Test method onlineSectioning.

/** Online sectioning test 
     * @param cfg solver configuration
     * @return resultant solution
     * @throws Exception thrown when the sectioning fails
     **/
public static Solution<Request, Enrollment> onlineSectioning(DataProperties cfg) throws Exception {
    Solution<Request, Enrollment> solution = load(cfg);
    if (solution == null)
        return null;
    StudentSectioningModel model = (StudentSectioningModel) solution.getModel();
    Assignment<Request, Enrollment> assignment = solution.getAssignment();
    solution.addSolutionListener(new TestSolutionListener());
    double startTime = JProf.currentTimeSec();
    Solver<Request, Enrollment> solver = new Solver<Request, Enrollment>(cfg);
    solver.setInitalSolution(solution);
    solver.initSolver();
    OnlineSelection onlineSelection = new OnlineSelection(cfg);
    onlineSelection.init(solver);
    double totalPenalty = 0, minPenalty = 0, maxPenalty = 0;
    double minAvEnrlPenalty = 0, maxAvEnrlPenalty = 0;
    double totalPrefPenalty = 0, minPrefPenalty = 0, maxPrefPenalty = 0;
    double minAvEnrlPrefPenalty = 0, maxAvEnrlPrefPenalty = 0;
    int nrChoices = 0, nrEnrollments = 0, nrCourseRequests = 0;
    int chChoices = 0, chCourseRequests = 0, chStudents = 0;
    int choiceLimit = model.getProperties().getPropertyInt("Test.ChoicesLimit", -1);
    File outDir = new File(model.getProperties().getProperty("General.Output", "."));
    outDir.mkdirs();
    PrintWriter pw = new PrintWriter(new FileWriter(new File(outDir, "choices.csv")));
    List<Student> students = model.getStudents();
    try {
        @SuppressWarnings("rawtypes") Class studentOrdClass = Class.forName(model.getProperties().getProperty("Test.StudentOrder", StudentRandomOrder.class.getName()));
        @SuppressWarnings("unchecked") StudentOrder studentOrd = (StudentOrder) studentOrdClass.getConstructor(new Class[] { DataProperties.class }).newInstance(new Object[] { model.getProperties() });
        students = studentOrd.order(model.getStudents());
    } catch (Exception e) {
        sLog.error("Unable to reorder students, reason: " + e.getMessage(), e);
    }
    ShutdownHook hook = new ShutdownHook(solver);
    Runtime.getRuntime().addShutdownHook(hook);
    for (Student student : students) {
        if (student.nrAssignedRequests(assignment) > 0)
            // skip students with assigned courses (i.e., students
            continue;
        // already assigned by a batch sectioning process)
        sLog.info("Sectioning student: " + student);
        BranchBoundSelection.Selection selection = onlineSelection.getSelection(assignment, student);
        BranchBoundNeighbour neighbour = selection.select();
        if (neighbour != null) {
            StudentPreferencePenalties penalties = null;
            if (selection instanceof OnlineSelection.EpsilonSelection) {
                OnlineSelection.EpsilonSelection epsSelection = (OnlineSelection.EpsilonSelection) selection;
                penalties = epsSelection.getPenalties();
                for (int i = 0; i < neighbour.getAssignment().length; i++) {
                    Request r = student.getRequests().get(i);
                    if (r instanceof CourseRequest) {
                        nrCourseRequests++;
                        chCourseRequests++;
                        int chChoicesThisRq = 0;
                        CourseRequest request = (CourseRequest) r;
                        for (Enrollment x : request.getAvaiableEnrollments(assignment)) {
                            nrEnrollments++;
                            if (epsSelection.isAllowed(i, x)) {
                                nrChoices++;
                                if (choiceLimit <= 0 || chChoicesThisRq < choiceLimit) {
                                    chChoices++;
                                    chChoicesThisRq++;
                                }
                            }
                        }
                    }
                }
                chStudents++;
                if (chStudents == 100) {
                    pw.println(sDF.format(((double) chChoices) / chCourseRequests));
                    pw.flush();
                    chStudents = 0;
                    chChoices = 0;
                    chCourseRequests = 0;
                }
            }
            for (int i = 0; i < neighbour.getAssignment().length; i++) {
                if (neighbour.getAssignment()[i] == null)
                    continue;
                Enrollment enrollment = neighbour.getAssignment()[i];
                if (enrollment.getRequest() instanceof CourseRequest) {
                    CourseRequest request = (CourseRequest) enrollment.getRequest();
                    double[] avEnrlMinMax = getMinMaxAvailableEnrollmentPenalty(assignment, request);
                    minAvEnrlPenalty += avEnrlMinMax[0];
                    maxAvEnrlPenalty += avEnrlMinMax[1];
                    totalPenalty += enrollment.getPenalty();
                    minPenalty += request.getMinPenalty();
                    maxPenalty += request.getMaxPenalty();
                    if (penalties != null) {
                        double[] avEnrlPrefMinMax = penalties.getMinMaxAvailableEnrollmentPenalty(assignment, enrollment.getRequest());
                        minAvEnrlPrefPenalty += avEnrlPrefMinMax[0];
                        maxAvEnrlPrefPenalty += avEnrlPrefMinMax[1];
                        totalPrefPenalty += penalties.getPenalty(enrollment);
                        minPrefPenalty += penalties.getMinPenalty(enrollment.getRequest());
                        maxPrefPenalty += penalties.getMaxPenalty(enrollment.getRequest());
                    }
                }
            }
            neighbour.assign(assignment, solution.getIteration());
            sLog.info("Student " + student + " enrolls into " + neighbour);
            onlineSelection.updateSpace(assignment, student);
        } else {
            sLog.warn("No solution found.");
        }
        solution.update(JProf.currentTimeSec() - startTime);
    }
    if (chCourseRequests > 0)
        pw.println(sDF.format(((double) chChoices) / chCourseRequests));
    pw.flush();
    pw.close();
    HashMap<String, String> extra = new HashMap<String, String>();
    sLog.info("Overall penalty is " + getPerc(totalPenalty, minPenalty, maxPenalty) + "% (" + sDF.format(totalPenalty) + "/" + sDF.format(minPenalty) + ".." + sDF.format(maxPenalty) + ")");
    extra.put("Overall penalty", getPerc(totalPenalty, minPenalty, maxPenalty) + "% (" + sDF.format(totalPenalty) + "/" + sDF.format(minPenalty) + ".." + sDF.format(maxPenalty) + ")");
    extra.put("Overall available enrollment penalty", getPerc(totalPenalty, minAvEnrlPenalty, maxAvEnrlPenalty) + "% (" + sDF.format(totalPenalty) + "/" + sDF.format(minAvEnrlPenalty) + ".." + sDF.format(maxAvEnrlPenalty) + ")");
    if (onlineSelection.isUseStudentPrefPenalties()) {
        sLog.info("Overall preference penalty is " + getPerc(totalPrefPenalty, minPrefPenalty, maxPrefPenalty) + "% (" + sDF.format(totalPrefPenalty) + "/" + sDF.format(minPrefPenalty) + ".." + sDF.format(maxPrefPenalty) + ")");
        extra.put("Overall preference penalty", getPerc(totalPrefPenalty, minPrefPenalty, maxPrefPenalty) + "% (" + sDF.format(totalPrefPenalty) + "/" + sDF.format(minPrefPenalty) + ".." + sDF.format(maxPrefPenalty) + ")");
        extra.put("Overall preference available enrollment penalty", getPerc(totalPrefPenalty, minAvEnrlPrefPenalty, maxAvEnrlPrefPenalty) + "% (" + sDF.format(totalPrefPenalty) + "/" + sDF.format(minAvEnrlPrefPenalty) + ".." + sDF.format(maxAvEnrlPrefPenalty) + ")");
        extra.put("Average number of choices", sDF.format(((double) nrChoices) / nrCourseRequests) + " (" + nrChoices + "/" + nrCourseRequests + ")");
        extra.put("Average number of enrollments", sDF.format(((double) nrEnrollments) / nrCourseRequests) + " (" + nrEnrollments + "/" + nrCourseRequests + ")");
    }
    hook.setExtra(extra);
    return solution;
}
Also used : Solver(org.cpsolver.ifs.solver.Solver) ParallelSolver(org.cpsolver.ifs.solver.ParallelSolver) HashMap(java.util.HashMap) FileWriter(java.io.FileWriter) OnlineSelection(org.cpsolver.studentsct.heuristics.selection.OnlineSelection) Enrollment(org.cpsolver.studentsct.model.Enrollment) PrintWriter(java.io.PrintWriter) BranchBoundSelection(org.cpsolver.studentsct.heuristics.selection.BranchBoundSelection) Request(org.cpsolver.studentsct.model.Request) CourseRequest(org.cpsolver.studentsct.model.CourseRequest) Student(org.cpsolver.studentsct.model.Student) IOException(java.io.IOException) CourseRequest(org.cpsolver.studentsct.model.CourseRequest) BranchBoundNeighbour(org.cpsolver.studentsct.heuristics.selection.BranchBoundSelection.BranchBoundNeighbour) StudentOrder(org.cpsolver.studentsct.heuristics.studentord.StudentOrder) File(java.io.File)

Example 10 with Solver

use of org.cpsolver.ifs.solver.Solver 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

Solver (org.cpsolver.ifs.solver.Solver)11 File (java.io.File)8 FileWriter (java.io.FileWriter)7 PrintWriter (java.io.PrintWriter)7 DefaultSingleAssignment (org.cpsolver.ifs.assignment.DefaultSingleAssignment)6 IOException (java.io.IOException)5 ParallelSolver (org.cpsolver.ifs.solver.ParallelSolver)4 Enrollment (org.cpsolver.studentsct.model.Enrollment)4 Request (org.cpsolver.studentsct.model.Request)4 FileInputStream (java.io.FileInputStream)3 ArrayList (java.util.ArrayList)3 Assignment (org.cpsolver.ifs.assignment.Assignment)3 DataProperties (org.cpsolver.ifs.util.DataProperties)3 CourseRequest (org.cpsolver.studentsct.model.CourseRequest)3 DefaultParallelAssignment (org.cpsolver.ifs.assignment.DefaultParallelAssignment)2 Student (org.cpsolver.studentsct.model.Student)2 DecimalFormat (java.text.DecimalFormat)1 HashMap (java.util.HashMap)1 NoSuchElementException (java.util.NoSuchElementException)1 StringTokenizer (java.util.StringTokenizer)1