001    package net.sf.cpsolver.ifs.util;
002    
003    import java.util.HashMap;
004    import java.util.Map;
005    
006    /**
007     * Common class for computing distances and back-to-back instructor / student conflicts.
008     * 
009     * When property Distances.Ellipsoid is set, the distances are computed using the given (e.g., WGS84, see {@link Ellipsoid}).
010     * In the legacy mode (when ellipsoid is not set), distances are computed using Euclidian distance and 1 unit is considered 10 meters.
011     * <br><br>
012     * For student back-to-back conflicts, Distances.Speed (in meters per minute) is considered and compared with the break time
013     * of the earlier class.
014     * <br><br>
015     * For instructors, the preference is computed using the distance in meters and the three constants 
016     * Instructor.NoPreferenceLimit (distance <= limit -> no preference), Instructor.DiscouragedLimit (distance <= limit -> discouraged),
017     * Instructor.ProhibitedLimit (distance <= limit -> strongly discouraged), the back-to-back placement is prohibited when the distance is over the last limit.
018     * 
019     * @version IFS 1.2 (Iterative Forward Search)<br>
020     *          Copyright (C) 2006 - 2010 Tomas Muller<br>
021     *          <a href="mailto:muller@unitime.org">muller@unitime.org</a><br>
022     *          <a href="http://muller.unitime.org">http://muller.unitime.org</a><br>
023     * <br>
024     *          This library is free software; you can redistribute it and/or modify
025     *          it under the terms of the GNU Lesser General Public License as
026     *          published by the Free Software Foundation; either version 3 of the
027     *          License, or (at your option) any later version. <br>
028     * <br>
029     *          This library is distributed in the hope that it will be useful, but
030     *          WITHOUT ANY WARRANTY; without even the implied warranty of
031     *          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
032     *          Lesser General Public License for more details. <br>
033     * <br>
034     *          You should have received a copy of the GNU Lesser General Public
035     *          License along with this library; if not see
036     *          <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>.
037     */
038    public class DistanceMetric {
039        public static enum Ellipsoid {
040            LEGACY ("Euclidean metric (1 unit equals to 10 meters)", "X-Coordinate", "Y-Coordinate", 0, 0, 0),
041            WGS84 ("WGS-84 (GPS)", 6378137, 6356752.3142, 1.0 / 298.257223563),
042            GRS80 ("GRS-80", 6378137, 6356752.3141, 1.0 / 298.257222101),
043            Airy1830 ("Airy (1830)", 6377563.396, 6356256.909, 1.0 / 299.3249646),
044            Intl1924 ("Int'l 1924", 6378388, 6356911.946, 1.0 / 297),
045            Clarke1880 ("Clarke (1880)", 6378249.145, 6356514.86955, 1.0 / 293.465),
046            GRS67 ("GRS-67", 6378160, 6356774.719, 1.0 / 298.25);
047            
048            private double iA, iB, iF;
049            private String iName, iFirstCoord, iSecondCoord;
050            
051            Ellipsoid(String name, double a, double b) {
052                this(name, "Latitude", "Longitude", a, b, (a - b) / a);
053            }
054            Ellipsoid(String name, double a, double b, double f) {
055                this(name, "Latitude", "Longitude", a, b, f);
056            }
057            Ellipsoid(String name, String xCoord, String yCoord, double a, double b, double f) {
058                iName = name;
059                iFirstCoord = xCoord; iSecondCoord = yCoord;
060                iA = a; iB = b; iF = f;
061            }
062            
063            /** Major semiaxe A */
064            public double a() { return iA; }
065            /** Minor semiaxe B */
066            public double b() { return iB; }
067            /** Flattening (A-B) / A */
068            public double f() { return iF; }
069            
070            /** Name of this coordinate system */
071            public String getEclipsoindName() { return iName; }
072            /** Name of the fist coordinate (e.g., Latitude) */
073            public String getFirstCoordinateName() { return iFirstCoord; }
074            /** Name of the second coordinate (e.g., Longitude) */
075            public String getSecondCoordinateName() { return iSecondCoord; }
076        }
077        
078        /** Elliposid parameters, default to WGS-84 */
079        private Ellipsoid iModel = Ellipsoid.WGS84;
080        /** Student speed in meters per minute (defaults to 1000 meters in 15 minutes) */
081        private double iSpeed = 1000.0 / 15;
082        /** Back-to-back classes: maximal distance for no preference */
083        private double iInstructorNoPreferenceLimit = 0.0;
084        /** Back-to-back classes: maximal distance for discouraged preference */
085        private double iInstructorDiscouragedLimit = 50.0;
086        /**
087         * Back-to-back classes: maximal distance for strongly discouraged preference
088         * (everything above is prohibited)
089         */
090        private double iInstructorProhibitedLimit = 200.0;
091        /** Default distance when given coordinates are null. */
092        private double iNullDistance = 10000.0;
093        /** Maximal travel time in minutes when no coordinates are given. */
094        private int iMaxTravelTime = 60;
095        /** Travel times overriding the distances computed from coordintaes */
096        private Map<Long, Map<Long, Integer>> iTravelTimes = new HashMap<Long, Map<Long,Integer>>();
097        /** Distance cache  */
098        private HashMap<String, Double> iDistanceCache = new HashMap<String, Double>();
099        /** True if distances should be considered between classes that are NOT back-to-back */
100        private boolean iComputeDistanceConflictsBetweenNonBTBClasses = false;
101        
102        /** Default properties */
103        public DistanceMetric() {
104        }
105        
106        /** With provided ellipsoid */
107        public DistanceMetric(Ellipsoid model) {
108            iModel = model;
109            if (iModel == Ellipsoid.LEGACY) {
110                iSpeed = 100.0 / 15;
111                iInstructorDiscouragedLimit = 5.0;
112                iInstructorProhibitedLimit = 20.0;
113            }
114        }
115    
116        /** With provided ellipsoid and student speed */
117        public DistanceMetric(Ellipsoid model, double speed) {
118            iModel = model;
119            iSpeed = speed;
120        }
121        
122        /** Configured using properties */
123        public DistanceMetric(DataProperties properties) {
124            if (Ellipsoid.LEGACY.name().equals(properties.getProperty("Distances.Ellipsoid",Ellipsoid.LEGACY.name()))) {
125                //LEGACY MODE
126                iModel = Ellipsoid.LEGACY;
127                iSpeed = properties.getPropertyDouble("Student.DistanceLimit", 1000.0 / 15) / 10.0;
128                iInstructorNoPreferenceLimit = properties.getPropertyDouble("Instructor.NoPreferenceLimit", 0.0);
129                iInstructorDiscouragedLimit = properties.getPropertyDouble("Instructor.DiscouragedLimit", 5.0);
130                iInstructorProhibitedLimit = properties.getPropertyDouble("Instructor.ProhibitedLimit", 20.0);
131                iNullDistance = properties.getPropertyDouble("Distances.NullDistance", 1000.0);
132                iMaxTravelTime = properties.getPropertyInt("Distances.MaxTravelDistanceInMinutes", 60);
133            } else {
134                iModel = Ellipsoid.valueOf(properties.getProperty("Distances.Ellipsoid", Ellipsoid.WGS84.name()));
135                if (iModel == null) iModel = Ellipsoid.WGS84;
136                iSpeed = properties.getPropertyDouble("Distances.Speed", properties.getPropertyDouble("Student.DistanceLimit", 1000.0 / 15));
137                iInstructorNoPreferenceLimit = properties.getPropertyDouble("Instructor.NoPreferenceLimit", iInstructorNoPreferenceLimit);
138                iInstructorDiscouragedLimit = properties.getPropertyDouble("Instructor.DiscouragedLimit", iInstructorDiscouragedLimit);
139                iInstructorProhibitedLimit = properties.getPropertyDouble("Instructor.ProhibitedLimit", iInstructorProhibitedLimit);
140                iNullDistance = properties.getPropertyDouble("Distances.NullDistance", iNullDistance);
141                iMaxTravelTime = properties.getPropertyInt("Distances.MaxTravelDistanceInMinutes", 60);
142            }
143            iComputeDistanceConflictsBetweenNonBTBClasses = properties.getPropertyBoolean(
144                    "Distances.ComputeDistanceConflictsBetweenNonBTBClasses", iComputeDistanceConflictsBetweenNonBTBClasses);
145        }
146    
147        /** Degrees to radians */
148        protected double deg2rad(double deg) {
149            return deg * Math.PI / 180;
150        }
151        
152        /** Compute distance between the two given coordinates
153         * @deprecated Use @{link {@link DistanceMetric#getDistanceInMeters(Long, Double, Double, Long, Double, Double)} instead (to include travel time matrix when available).
154         */
155        @Deprecated
156        public double getDistanceInMeters(Double lat1, Double lon1, Double lat2, Double lon2) {
157            if (lat1 == null || lat2 == null || lon1 == null || lon2 == null)
158                return iNullDistance;
159            
160            if (lat1.equals(lat2) && lon1.equals(lon2)) return 0.0;
161            
162            // legacy mode -- euclidian distance, 1 unit is 10 meters
163            if (iModel == Ellipsoid.LEGACY) {
164                if (lat1 < 0 || lat2 < 0 || lon1 < 0 || lon2 < 0) return iNullDistance;
165                double dx = lat1 - lat2;
166                double dy = lon1 - lon2;
167                return Math.sqrt(dx * dx + dy * dy);
168            }
169            
170            String id = null;
171            if (lat1 < lat2 || (lat1 == lat2 && lon1 <= lon2)) {
172                id =
173                    Long.toHexString(Double.doubleToRawLongBits(lat1)) +
174                    Long.toHexString(Double.doubleToRawLongBits(lon1)) +
175                    Long.toHexString(Double.doubleToRawLongBits(lat2)) +
176                    Long.toHexString(Double.doubleToRawLongBits(lon2));
177            } else {
178                id =
179                    Long.toHexString(Double.doubleToRawLongBits(lat1)) +
180                    Long.toHexString(Double.doubleToRawLongBits(lon1)) +
181                    Long.toHexString(Double.doubleToRawLongBits(lat2)) +
182                    Long.toHexString(Double.doubleToRawLongBits(lon2));
183            }
184            Double distance = iDistanceCache.get(id);
185            
186            if (distance == null) {
187                double a = iModel.a(), b = iModel.b(),  f = iModel.f();  // ellipsoid params
188                double L = deg2rad(lon2-lon1);
189                double U1 = Math.atan((1-f) * Math.tan(deg2rad(lat1)));
190                double U2 = Math.atan((1-f) * Math.tan(deg2rad(lat2)));
191                double sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);
192                double sinU2 = Math.sin(U2), cosU2 = Math.cos(U2);
193                
194                double lambda = L, lambdaP, iterLimit = 100;
195                double cosSqAlpha, cos2SigmaM, sinSigma, cosSigma, sigma, sinLambda, cosLambda;
196                do {
197                  sinLambda = Math.sin(lambda);
198                  cosLambda = Math.cos(lambda);
199                  sinSigma = Math.sqrt((cosU2*sinLambda) * (cosU2*sinLambda) + 
200                    (cosU1*sinU2-sinU1*cosU2*cosLambda) * (cosU1*sinU2-sinU1*cosU2*cosLambda));
201                  if (sinSigma==0) return 0;  // co-incident points
202                  cosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda;
203                  sigma = Math.atan2(sinSigma, cosSigma);
204                  double sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
205                  cosSqAlpha = 1 - sinAlpha*sinAlpha;
206                  cos2SigmaM = cosSigma - 2*sinU1*sinU2/cosSqAlpha;
207                  if (Double.isNaN(cos2SigmaM)) cos2SigmaM = 0;  // equatorial line: cosSqAlpha=0 (�6)
208                  double C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));
209                  lambdaP = lambda;
210                  lambda = L + (1-C) * f * sinAlpha *
211                    (sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));
212                } while (Math.abs(lambda-lambdaP) > 1e-12 && --iterLimit>0);
213                if (iterLimit==0) return Double.NaN; // formula failed to converge
214               
215                double uSq = cosSqAlpha * (a*a - b*b) / (b*b);
216                double A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));
217                double B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));
218                double deltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-
219                  B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));
220                
221                // initial & final bearings
222                // double fwdAz = Math.atan2(cosU2*sinLambda, cosU1*sinU2-sinU1*cosU2*cosLambda);
223                // double revAz = Math.atan2(cosU1*sinLambda, -sinU1*cosU2+cosU1*sinU2*cosLambda);
224                
225                // s = s.toFixed(3); // round to 1mm precision
226    
227                distance = b*A*(sigma-deltaSigma);
228                iDistanceCache.put(id, distance);
229            }
230            
231            return distance;
232        }
233        
234        /**
235         * Compute distance in minutes.
236         * Property Distances.Speed (in meters per minute) is used to convert meters to minutes, defaults to 1000 meters per 15 minutes (that means 66.67 meters per minute).
237         * @deprecated Use @{link {@link DistanceMetric#getDistanceInMinutes(Long, Double, Double, Long, Double, Double)} instead (to include travel time matrix when available).
238         */
239        @Deprecated
240        public int getDistanceInMinutes(double lat1, double lon1, double lat2, double lon2) {
241            return (int) Math.round(getDistanceInMeters(lat1, lon1, lat2, lon2) / iSpeed);
242        }
243        
244        /**
245         * Converts minutes to meters.
246         * Property Distances.Speed (in meters per minute) is used, defaults to 1000 meters per 15 minutes.
247         */
248        public double minutes2meters(int min) {
249            return iSpeed * min;
250        }
251        
252    
253        /** Back-to-back classes in rooms within this limit have neutral preference */
254        public double getInstructorNoPreferenceLimit() {
255            return iInstructorNoPreferenceLimit;
256        }
257    
258        /** Back-to-back classes in rooms within this limit have discouraged preference */
259        public double getInstructorDiscouragedLimit() {
260            return iInstructorDiscouragedLimit;
261        }
262    
263        /** Back-to-back classes in rooms within this limit have strongly discouraged preference, it is prohibited to exceed this limit. */
264        public double getInstructorProhibitedLimit() {
265            return iInstructorProhibitedLimit;
266        }
267        
268        /** True if legacy mode is used (Euclidian distance where 1 unit is 10 meters) */
269        public boolean isLegacy() {
270            return iModel == Ellipsoid.LEGACY;
271        }
272        
273        /** Maximal travel distance between rooms when no coordinates are given */
274        public int getMaxTravelDistanceInMinutes() {
275            return iMaxTravelTime;
276        }
277    
278        /** Add travel time between two locations */
279        public void addTravelTime(Long roomId1, Long roomId2, Integer travelTimeInMinutes) {
280            if (roomId1 == null || roomId2 == null) return;
281            if (roomId1 < roomId2) {
282                Map<Long, Integer> times = iTravelTimes.get(roomId1);
283                if (times == null) { times = new HashMap<Long, Integer>(); iTravelTimes.put(roomId1, times); }
284                if (travelTimeInMinutes == null)
285                    times.remove(roomId2);
286                else
287                    times.put(roomId2, travelTimeInMinutes);
288            } else {
289                Map<Long, Integer> times = iTravelTimes.get(roomId2);
290                if (times == null) { times = new HashMap<Long, Integer>(); iTravelTimes.put(roomId2, times); }
291                if (travelTimeInMinutes == null)
292                    times.remove(roomId1);
293                else
294                    times.put(roomId1, travelTimeInMinutes);
295            }
296        }
297        
298        /** Return travel time between two locations. */
299        public Integer getTravelTimeInMinutes(Long roomId1, Long roomId2) {
300            if (roomId1 == null || roomId2 == null) return null;
301            if (roomId1 < roomId2) {
302                Map<Long, Integer> times = iTravelTimes.get(roomId1);
303                return (times == null ? null : times.get(roomId2));
304            } else {
305                Map<Long, Integer> times = iTravelTimes.get(roomId2);
306                return (times == null ? null : times.get(roomId1));
307            }
308        }
309        
310        /** Return travel time between two locations. Travel times are used when available, use coordinates otherwise. */
311        public Integer getDistanceInMinutes(Long roomId1, Double lat1, Double lon1, Long roomId2, Double lat2, Double lon2) {
312            Integer distance = getTravelTimeInMinutes(roomId1, roomId2);
313            if (distance != null) return distance;
314            
315            if (lat1 == null || lat2 == null || lon1 == null || lon2 == null)
316                return getMaxTravelDistanceInMinutes();
317            else 
318                return (int) Math.round(getDistanceInMeters(lat1, lon1, lat2, lon2) / iSpeed);
319        }
320        
321        /** Return travel distance between two locations.  Travel times are used when available, use coordinates otherwise. */
322        public double getDistanceInMeters(Long roomId1, Double lat1, Double lon1, Long roomId2, Double lat2, Double lon2) {
323            Integer distance = getTravelTimeInMinutes(roomId1, roomId2);
324            if (distance != null) return minutes2meters(distance);
325            
326            return getDistanceInMeters(lat1, lon1, lat2, lon2);
327        }
328        
329        /** Return travel times matrix */
330        public Map<Long, Map<Long, Integer>> getTravelTimes() { return iTravelTimes; }
331        
332        /**
333         * True if distances should be considered between classes that are NOT back-to-back. Distance in minutes is then 
334         * to be compared with the difference between end of the last class and start of the second class plus break time of the first class.
335         **/
336        public boolean doComputeDistanceConflictsBetweenNonBTBClasses() {
337            return iComputeDistanceConflictsBetweenNonBTBClasses;
338        }
339        
340        /** Few tests */
341        public static void main(String[] args) {
342            System.out.println("Distance between Prague and Zlin: " + new DistanceMetric().getDistanceInMeters(50.087661, 14.420535, 49.226736, 17.668856) / 1000.0 + " km");
343            System.out.println("Distance between ENAD and PMU: " + new DistanceMetric().getDistanceInMeters(40.428323, -86.912785, 40.425078, -86.911474) + " m");
344            System.out.println("Distance between ENAD and ME: " + new DistanceMetric().getDistanceInMeters(40.428323, -86.912785, 40.429338, -86.91267) + " m");
345            System.out.println("Distance between Prague and Zlin: " + new DistanceMetric().getDistanceInMinutes(50.087661, 14.420535, 49.226736, 17.668856) / 60 + " hours");
346            System.out.println("Distance between ENAD and PMU: " + new DistanceMetric().getDistanceInMinutes(40.428323, -86.912785, 40.425078, -86.911474) + " minutes");
347            System.out.println("Distance between ENAD and ME: " + new DistanceMetric().getDistanceInMinutes(40.428323, -86.912785, 40.429338, -86.91267) + " minutes");
348        }
349    
350    }