001    package net.sf.cpsolver.exam.heuristics;
002    
003    import java.text.DecimalFormat;
004    import java.util.ArrayList;
005    import java.util.Collection;
006    import java.util.List;
007    import java.util.Map;
008    
009    import net.sf.cpsolver.exam.model.Exam;
010    import net.sf.cpsolver.exam.model.ExamPlacement;
011    import net.sf.cpsolver.exam.neighbours.ExamRandomMove;
012    import net.sf.cpsolver.exam.neighbours.ExamRoomMove;
013    import net.sf.cpsolver.exam.neighbours.ExamTimeMove;
014    import net.sf.cpsolver.ifs.heuristics.NeighbourSelection;
015    import net.sf.cpsolver.ifs.model.Neighbour;
016    import net.sf.cpsolver.ifs.solution.Solution;
017    import net.sf.cpsolver.ifs.solution.SolutionListener;
018    import net.sf.cpsolver.ifs.solver.Solver;
019    import net.sf.cpsolver.ifs.util.DataProperties;
020    import net.sf.cpsolver.ifs.util.JProf;
021    import net.sf.cpsolver.ifs.util.Progress;
022    import net.sf.cpsolver.ifs.util.ToolBox;
023    
024    import org.apache.log4j.Logger;
025    
026    /**
027     * Greate deluge. In each iteration, one of the following three neighbourhoods
028     * is selected first
029     * <ul>
030     * <li>random move ({@link ExamRandomMove})
031     * <li>period swap ({@link ExamTimeMove})
032     * <li>room swap ({@link ExamRoomMove})
033     * </ul>
034     * , then a neighbour is generated and it is accepted if the value of the new
035     * solution is below certain bound. This bound is initialized to the
036     * GreatDeluge.UpperBoundRate &times; value of the best solution ever found.
037     * After each iteration, the bound is decreased by GreatDeluge.CoolRate (new
038     * bound equals to old bound &times; GreatDeluge.CoolRate). If the bound gets
039     * bellow GreatDeluge.LowerBoundRate &times; value of the best solution ever
040     * found, it is changed back to GreatDeluge.UpperBoundRate &times; value of the
041     * best solution ever found.
042     * 
043     * If there was no improvement found between the bounds, the new bounds are
044     * changed to GreatDeluge.UpperBoundRate^2 and GreatDeluge.LowerBoundRate^2,
045     * GreatDeluge.UpperBoundRate^3 and GreatDeluge.LowerBoundRate^3, etc. till
046     * there is an improvement found. <br>
047     * <br>
048     * 
049     * @version ExamTT 1.2 (Examination Timetabling)<br>
050     *          Copyright (C) 2008 - 2010 Tomas Muller<br>
051     *          <a href="mailto:muller@unitime.org">muller@unitime.org</a><br>
052     *          <a href="http://muller.unitime.org">http://muller.unitime.org</a><br>
053     * <br>
054     *          This library is free software; you can redistribute it and/or modify
055     *          it under the terms of the GNU Lesser General Public License as
056     *          published by the Free Software Foundation; either version 3 of the
057     *          License, or (at your option) any later version. <br>
058     * <br>
059     *          This library is distributed in the hope that it will be useful, but
060     *          WITHOUT ANY WARRANTY; without even the implied warranty of
061     *          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
062     *          Lesser General Public License for more details. <br>
063     * <br>
064     *          You should have received a copy of the GNU Lesser General Public
065     *          License along with this library; if not see
066     *          <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>.
067     */
068    public class ExamGreatDeluge implements NeighbourSelection<Exam, ExamPlacement>, SolutionListener<Exam, ExamPlacement> {
069        private static Logger sLog = Logger.getLogger(ExamGreatDeluge.class);
070        private static DecimalFormat sDF2 = new DecimalFormat("0.00");
071        private static DecimalFormat sDF5 = new DecimalFormat("0.00000");
072        private double iBound = 0.0;
073        private double iCoolRate = 0.99999995;
074        private long iIter;
075        private double iUpperBound;
076        private double iUpperBoundRate = 1.05;
077        private double iLowerBoundRate = 0.95;
078        private int iMoves = 0;
079        private int iAcceptedMoves = 0;
080        private int iNrIdle = 0;
081        private long iT0 = -1;
082        private long iLastImprovingIter = 0;
083        private double iBestValue = 0;
084        private Progress iProgress = null;
085    
086        private List<NeighbourSelection<Exam, ExamPlacement>> iNeighbours = null;
087    
088        /**
089         * Constructor. Following problem properties are considered:
090         * <ul>
091         * <li>GreatDeluge.CoolRate ... bound cooling rate (default 0.99999995)
092         * <li>GreatDeluge.UpperBoundRate ... bound upper bound relative to best
093         * solution ever found (default 1.05)
094         * <li>GreatDeluge.LowerBoundRate ... bound lower bound relative to best
095         * solution ever found (default 0.95)
096         * </ul>
097         * 
098         * @param properties
099         *            problem properties
100         */
101        @SuppressWarnings("unchecked")
102        public ExamGreatDeluge(DataProperties properties) {
103            iCoolRate = properties.getPropertyDouble("GreatDeluge.CoolRate", iCoolRate);
104            iUpperBoundRate = properties.getPropertyDouble("GreatDeluge.UpperBoundRate", iUpperBoundRate);
105            iLowerBoundRate = properties.getPropertyDouble("GreatDeluge.LowerBoundRate", iLowerBoundRate);
106            String neighbours = properties.getProperty("GreatDeluge.Neighbours", 
107                    ExamRandomMove.class.getName() + ";" +
108                    ExamRoomMove.class.getName() + ";" +
109                    ExamTimeMove.class.getName());
110            neighbours += ";" + properties.getProperty("GreatDeluge.AdditionalNeighbours", "");
111            iNeighbours = new ArrayList<NeighbourSelection<Exam,ExamPlacement>>();
112            for (String neighbour: neighbours.split("\\;")) {
113                if (neighbour == null || neighbour.isEmpty()) continue;
114                try {
115                    Class<NeighbourSelection<Exam, ExamPlacement>> clazz = (Class<NeighbourSelection<Exam, ExamPlacement>>)Class.forName(neighbour);
116                    iNeighbours.add(clazz.getConstructor(DataProperties.class).newInstance(properties));
117                } catch (Exception e) {
118                    sLog.error("Unable to use " + neighbour + ": " + e.getMessage());
119                }
120            }
121        }
122    
123        /** Initialization */
124        @Override
125        public void init(Solver<Exam, ExamPlacement> solver) {
126            iIter = -1;
127            solver.currentSolution().addSolutionListener(this);
128            for (NeighbourSelection<Exam, ExamPlacement> neighbour: iNeighbours)
129                neighbour.init(solver);
130            solver.setUpdateProgress(false);
131            iProgress = Progress.getInstance(solver.currentSolution().getModel());
132        }
133    
134        /** Print some information */
135        protected void info(Solution<Exam, ExamPlacement> solution) {
136            sLog.info("Iter=" + iIter / 1000 + "k, NonImpIter=" + sDF2.format((iIter - iLastImprovingIter) / 1000.0)
137                    + "k, Speed=" + sDF2.format(1000.0 * iIter / (JProf.currentTimeMillis() - iT0)) + " it/s");
138            sLog.info("Bound is " + sDF2.format(iBound) + ", " + "best value is " + sDF2.format(solution.getBestValue())
139                    + " (" + sDF2.format(100.0 * iBound / solution.getBestValue()) + "%), " + "current value is "
140                    + sDF2.format(solution.getModel().getTotalValue()) + " ("
141                    + sDF2.format(100.0 * iBound / solution.getModel().getTotalValue()) + "%), " + "#idle=" + iNrIdle
142                    + ", " + "Pacc=" + sDF5.format(100.0 * iAcceptedMoves / iMoves) + "%");
143            iAcceptedMoves = iMoves = 0;
144        }
145    
146        /**
147         * Generate neighbour -- select neighbourhood randomly, select neighbour
148         */
149        public Neighbour<Exam, ExamPlacement> genMove(Solution<Exam, ExamPlacement> solution) {
150            while (true) {
151                incIter(solution);
152                NeighbourSelection<Exam, ExamPlacement> ns = iNeighbours.get(ToolBox.random(iNeighbours.size()));
153                Neighbour<Exam, ExamPlacement> n = ns.selectNeighbour(solution);
154                if (n != null)
155                    return n;
156            }
157        }
158    
159        /** Accept neighbour */
160        protected boolean accept(Solution<Exam, ExamPlacement> solution, Neighbour<Exam, ExamPlacement> neighbour) {
161            return (neighbour.value() <= 0 || solution.getModel().getTotalValue() + neighbour.value() <= iBound);
162        }
163    
164        /** Increment iteration count, update bound */
165        protected void incIter(Solution<Exam, ExamPlacement> solution) {
166            if (iIter < 0) {
167                iIter = 0;
168                iLastImprovingIter = 0;
169                iT0 = JProf.currentTimeMillis();
170                iBound = (solution.getBestValue() > 0.0 ? iUpperBoundRate * solution.getBestValue() : solution
171                        .getBestValue()
172                        / iUpperBoundRate);
173                iUpperBound = iBound;
174                iNrIdle = 0;
175                iProgress.setPhase("Great deluge [" + (1 + iNrIdle) + "]...");
176            } else {
177                iIter++;
178                if (solution.getBestValue() >= 0.0)
179                    iBound *= iCoolRate;
180                else
181                    iBound /= iCoolRate;
182            }
183            if (iIter % 100000 == 0) {
184                info(solution);
185            }
186            double lowerBound = (solution.getBestValue() >= 0.0 ? Math.pow(iLowerBoundRate, 1 + iNrIdle)
187                    * solution.getBestValue() : solution.getBestValue() / Math.pow(iLowerBoundRate, 1 + iNrIdle));
188            if (iBound < lowerBound) {
189                iNrIdle++;
190                sLog.info(" -<[" + iNrIdle + "]>- ");
191                iBound = Math.max(solution.getBestValue() + 2.0, (solution.getBestValue() >= 0.0 ? Math.pow(
192                        iUpperBoundRate, iNrIdle)
193                        * solution.getBestValue() : solution.getBestValue() / Math.pow(iUpperBoundRate, iNrIdle)));
194                iUpperBound = iBound;
195                iProgress.setPhase("Great deluge [" + (1 + iNrIdle) + "]...");
196            }
197            iProgress.setProgress(100 - Math.round(100.0 * (iBound - lowerBound) / (iUpperBound - lowerBound)));
198        }
199    
200        /**
201         * A neighbour is generated randomly untill an acceptable one is found.
202         */
203        @Override
204        public Neighbour<Exam, ExamPlacement> selectNeighbour(Solution<Exam, ExamPlacement> solution) {
205            Neighbour<Exam, ExamPlacement> neighbour = null;
206            while ((neighbour = genMove(solution)) != null) {
207                iMoves++;
208                if (accept(solution, neighbour)) {
209                    iAcceptedMoves++;
210                    break;
211                }
212            }
213            return (neighbour == null ? null : neighbour);
214        }
215    
216        /** Update last improving iteration count */
217        @Override
218        public void bestSaved(Solution<Exam, ExamPlacement> solution) {
219            if (Math.abs(iBestValue - solution.getBestValue()) >= 1.0) {
220                iLastImprovingIter = iIter;
221                iNrIdle = 0;
222                iBestValue = solution.getBestValue();
223            }
224        }
225    
226        @Override
227        public void solutionUpdated(Solution<Exam, ExamPlacement> solution) {
228        }
229    
230        @Override
231        public void getInfo(Solution<Exam, ExamPlacement> solution, Map<String, String> info) {
232        }
233    
234        @Override
235        public void getInfo(Solution<Exam, ExamPlacement> solution, Map<String, String> info, Collection<Exam> variables) {
236        }
237    
238        @Override
239        public void bestCleared(Solution<Exam, ExamPlacement> solution) {
240        }
241    
242        @Override
243        public void bestRestored(Solution<Exam, ExamPlacement> solution) {
244        }
245    
246    }