001package org.cpsolver.ifs.util;
002
003import java.util.HashMap;
004import java.util.Map;
005import java.util.concurrent.locks.ReentrantReadWriteLock;
006
007/**
008 * Common class for computing distances and back-to-back instructor / student conflicts.
009 * 
010 * When property Distances.Ellipsoid is set, the distances are computed using the given (e.g., WGS84, see {@link Ellipsoid}).
011 * In the legacy mode (when ellipsoid is not set), distances are computed using Euclidian distance and 1 unit is considered 10 meters.
012 * <br><br>
013 * For student back-to-back conflicts, Distances.Speed (in meters per minute) is considered and compared with the break time
014 * of the earlier class.
015 * <br><br>
016 * For instructors, the preference is computed using the distance in meters and the three constants 
017 * Instructor.NoPreferenceLimit (distance &lt;= limit &rarr; no preference), Instructor.DiscouragedLimit (distance &lt;= limit &rarr; discouraged),
018 * Instructor.ProhibitedLimit (distance &lt;= limit &rarr; strongly discouraged), the back-to-back placement is prohibited when the distance is over the last limit.
019 * 
020 * @version IFS 1.3 (Iterative Forward Search)<br>
021 *          Copyright (C) 2006 - 2014 Tomáš Müller<br>
022 *          <a href="mailto:muller@unitime.org">muller@unitime.org</a><br>
023 *          <a href="http://muller.unitime.org">http://muller.unitime.org</a><br>
024 * <br>
025 *          This library is free software; you can redistribute it and/or modify
026 *          it under the terms of the GNU Lesser General Public License as
027 *          published by the Free Software Foundation; either version 3 of the
028 *          License, or (at your option) any later version. <br>
029 * <br>
030 *          This library is distributed in the hope that it will be useful, but
031 *          WITHOUT ANY WARRANTY; without even the implied warranty of
032 *          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
033 *          Lesser General Public License for more details. <br>
034 * <br>
035 *          You should have received a copy of the GNU Lesser General Public
036 *          License along with this library; if not see
037 *          <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>.
038 */
039public class DistanceMetric {
040    public static enum Ellipsoid {
041        LEGACY ("Euclidean metric (1 unit equals to 10 meters)", "X-Coordinate", "Y-Coordinate", 0, 0, 0),
042        WGS84 ("WGS-84 (GPS)", 6378137, 6356752.3142, 1.0 / 298.257223563),
043        GRS80 ("GRS-80", 6378137, 6356752.3141, 1.0 / 298.257222101),
044        Airy1830 ("Airy (1830)", 6377563.396, 6356256.909, 1.0 / 299.3249646),
045        Intl1924 ("Int'l 1924", 6378388, 6356911.946, 1.0 / 297),
046        Clarke1880 ("Clarke (1880)", 6378249.145, 6356514.86955, 1.0 / 293.465),
047        GRS67 ("GRS-67", 6378160, 6356774.719, 1.0 / 298.25);
048        
049        private double iA, iB, iF;
050        private String iName, iFirstCoord, iSecondCoord;
051        
052        Ellipsoid(String name, double a, double b) {
053            this(name, "Latitude", "Longitude", a, b, (a - b) / a);
054        }
055        Ellipsoid(String name, double a, double b, double f) {
056            this(name, "Latitude", "Longitude", a, b, f);
057        }
058        Ellipsoid(String name, String xCoord, String yCoord, double a, double b, double f) {
059            iName = name;
060            iFirstCoord = xCoord; iSecondCoord = yCoord;
061            iA = a; iB = b; iF = f;
062        }
063        
064        /** Major semiaxe A 
065         * @return major semiaxe A
066         **/
067        public double a() { return iA; }
068        /** Minor semiaxe B
069         * @return major semiaxe B
070         **/
071        public double b() { return iB; }
072        /** Flattening (A-B) / A
073         * @return Flattening (A-B) / A 
074         **/
075        public double f() { return iF; }
076        
077        /** Name of this coordinate system
078         * @return elipsoid name 
079         **/
080        public String getEclipsoindName() { return iName; }
081        /** Name of the fist coordinate (e.g., Latitude) 
082         * @return first coordinate's name 
083         **/
084        public String getFirstCoordinateName() { return iFirstCoord; }
085        /** Name of the second coordinate (e.g., Longitude)
086         * @return second coordinate's name
087         **/
088        public String getSecondCoordinateName() { return iSecondCoord; }
089    }
090    
091    /** Elliposid parameters, default to WGS-84 */
092    private Ellipsoid iModel = Ellipsoid.WGS84;
093    /** Student speed in meters per minute (defaults to 1000 meters in 15 minutes) */
094    private double iSpeed = 1000.0 / 15;
095    /** Back-to-back classes: maximal distance for no preference */
096    private double iInstructorNoPreferenceLimit = 0.0;
097    /** Back-to-back classes: maximal distance for discouraged preference */
098    private double iInstructorDiscouragedLimit = 50.0;
099    /**
100     * Back-to-back classes: maximal distance for strongly discouraged preference
101     * (everything above is prohibited)
102     */
103    private double iInstructorProhibitedLimit = 200.0;
104    /** 
105     * When Distances.ComputeDistanceConflictsBetweenNonBTBClasses is enabled, distance limit (in minutes)
106     * for a long travel.  
107     */
108    private double iInstructorLongTravelInMinutes = 30.0;
109    
110    /** Default distance when given coordinates are null. */
111    private double iNullDistance = 10000.0;
112    /** Maximal travel time in minutes when no coordinates are given. */
113    private int iMaxTravelTime = 60;
114    /** Travel times overriding the distances computed from coordintaes */
115    private Map<Long, Map<Long, Integer>> iTravelTimes = new HashMap<Long, Map<Long,Integer>>();
116    /** Distance cache  */
117    private Map<String, Double> iDistanceCache = new HashMap<String, Double>();
118    /** True if distances should be considered between classes that are NOT back-to-back */
119    private boolean iComputeDistanceConflictsBetweenNonBTBClasses = false;
120    /** Reference of the accommodation of students that need short distances */
121    private String iShortDistanceAccommodationReference = "SD";
122    
123    private final ReentrantReadWriteLock iLock = new ReentrantReadWriteLock();
124    
125    /** Default properties */
126    public DistanceMetric() {
127    }
128    
129    public DistanceMetric(DistanceMetric m) {
130        iModel = m.iModel;
131        iSpeed = m.iSpeed;
132        iInstructorNoPreferenceLimit = m.iInstructorNoPreferenceLimit;
133        iInstructorDiscouragedLimit = m.iInstructorDiscouragedLimit;
134        iInstructorProhibitedLimit = m.iInstructorProhibitedLimit;
135        iInstructorLongTravelInMinutes = m.iInstructorLongTravelInMinutes;
136        iNullDistance = m.iNullDistance;
137        iMaxTravelTime = m.iMaxTravelTime;
138        iComputeDistanceConflictsBetweenNonBTBClasses = m.iComputeDistanceConflictsBetweenNonBTBClasses;
139        iShortDistanceAccommodationReference = m.iShortDistanceAccommodationReference;
140        m.iLock.readLock().lock();
141        try {
142            for (Map.Entry<Long, Map<Long, Integer>> e: m.iTravelTimes.entrySet())
143                iTravelTimes.put(e.getKey(), new HashMap<Long, Integer>(e.getValue()));
144        } finally {
145            m.iLock.readLock().unlock();
146        }
147    }
148    
149    /** With provided ellipsoid 
150     * @param model ellipsoid model
151     **/
152    public DistanceMetric(Ellipsoid model) {
153        iModel = model;
154        if (iModel == Ellipsoid.LEGACY) {
155            iSpeed = 100.0 / 15;
156            iInstructorDiscouragedLimit = 5.0;
157            iInstructorProhibitedLimit = 20.0;
158        }
159    }
160
161    /** With provided ellipsoid and student speed
162     * @param model ellipsoid model
163     * @param speed student speed in meters per minute 
164     **/
165    public DistanceMetric(Ellipsoid model, double speed) {
166        iModel = model;
167        iSpeed = speed;
168    }
169    
170    /** Configured using properties 
171     * @param properties solver configuration
172     **/
173    public DistanceMetric(DataProperties properties) {
174        if (Ellipsoid.LEGACY.name().equals(properties.getProperty("Distances.Ellipsoid",Ellipsoid.LEGACY.name()))) {
175            //LEGACY MODE
176            iModel = Ellipsoid.LEGACY;
177            iSpeed = properties.getPropertyDouble("Student.DistanceLimit", 1000.0 / 15) / 10.0;
178            iInstructorNoPreferenceLimit = properties.getPropertyDouble("Instructor.NoPreferenceLimit", 0.0);
179            iInstructorDiscouragedLimit = properties.getPropertyDouble("Instructor.DiscouragedLimit", 5.0);
180            iInstructorProhibitedLimit = properties.getPropertyDouble("Instructor.ProhibitedLimit", 20.0);
181            iNullDistance = properties.getPropertyDouble("Distances.NullDistance", 1000.0);
182            iMaxTravelTime = properties.getPropertyInt("Distances.MaxTravelDistanceInMinutes", 60);
183        } else {
184            iModel = Ellipsoid.valueOf(properties.getProperty("Distances.Ellipsoid", Ellipsoid.WGS84.name()));
185            if (iModel == null) iModel = Ellipsoid.WGS84;
186            iSpeed = properties.getPropertyDouble("Distances.Speed", properties.getPropertyDouble("Student.DistanceLimit", 1000.0 / 15));
187            iInstructorNoPreferenceLimit = properties.getPropertyDouble("Instructor.NoPreferenceLimit", iInstructorNoPreferenceLimit);
188            iInstructorDiscouragedLimit = properties.getPropertyDouble("Instructor.DiscouragedLimit", iInstructorDiscouragedLimit);
189            iInstructorProhibitedLimit = properties.getPropertyDouble("Instructor.ProhibitedLimit", iInstructorProhibitedLimit);
190            iNullDistance = properties.getPropertyDouble("Distances.NullDistance", iNullDistance);
191            iMaxTravelTime = properties.getPropertyInt("Distances.MaxTravelDistanceInMinutes", 60);
192        }
193        iComputeDistanceConflictsBetweenNonBTBClasses = properties.getPropertyBoolean(
194                "Distances.ComputeDistanceConflictsBetweenNonBTBClasses", iComputeDistanceConflictsBetweenNonBTBClasses);
195        iShortDistanceAccommodationReference = properties.getProperty(
196                "Distances.ShortDistanceAccommodationReference", iShortDistanceAccommodationReference);
197        iInstructorLongTravelInMinutes = properties.getPropertyDouble("Instructor.InstructorLongTravelInMinutes", 30.0);
198    }
199
200    /** Degrees to radians 
201     * @param deg degrees
202     * @return radians
203     **/
204    protected double deg2rad(double deg) {
205        return deg * Math.PI / 180;
206    }
207    
208    /** Compute distance between the two given coordinates
209     * @param lat1 first coordinate's latitude
210     * @param lon1 first coordinate's longitude
211     * @param lat2 second coordinate's latitude
212     * @param lon2 second coordinate's longitude
213     * @return distance in meters
214     * @deprecated Use @{link {@link DistanceMetric#getDistanceInMeters(Long, Double, Double, Long, Double, Double)} instead (to include travel time matrix when available).
215     */
216    @Deprecated
217    public double getDistanceInMeters(Double lat1, Double lon1, Double lat2, Double lon2) {
218        if (lat1 == null || lat2 == null || lon1 == null || lon2 == null)
219            return iNullDistance;
220        
221        if (lat1.equals(lat2) && lon1.equals(lon2)) return 0.0;
222        
223        // legacy mode -- euclidian distance, 1 unit is 10 meters
224        if (iModel == Ellipsoid.LEGACY) {
225            if (lat1 < 0 || lat2 < 0 || lon1 < 0 || lon2 < 0) return iNullDistance;
226            double dx = lat1 - lat2;
227            double dy = lon1 - lon2;
228            return Math.sqrt(dx * dx + dy * dy);
229        }
230        
231        String id = null;
232        if (lat1 < lat2 || (lat1 == lat2 && lon1 <= lon2)) {
233            id =
234                Long.toHexString(Double.doubleToRawLongBits(lat1)) +
235                Long.toHexString(Double.doubleToRawLongBits(lon1)) +
236                Long.toHexString(Double.doubleToRawLongBits(lat2)) +
237                Long.toHexString(Double.doubleToRawLongBits(lon2));
238        } else {
239            id =
240                Long.toHexString(Double.doubleToRawLongBits(lat1)) +
241                Long.toHexString(Double.doubleToRawLongBits(lon1)) +
242                Long.toHexString(Double.doubleToRawLongBits(lat2)) +
243                Long.toHexString(Double.doubleToRawLongBits(lon2));
244        }
245        
246        iLock.readLock().lock();
247        try {
248            Double distance = iDistanceCache.get(id);
249            if (distance != null) return distance;
250        } finally {
251            iLock.readLock().unlock();
252        }
253        
254        iLock.writeLock().lock();
255        try {
256            Double distance = iDistanceCache.get(id);
257            if (distance != null) return distance;
258
259            double a = iModel.a(), b = iModel.b(),  f = iModel.f();  // ellipsoid params
260            double L = deg2rad(lon2-lon1);
261            double U1 = Math.atan((1-f) * Math.tan(deg2rad(lat1)));
262            double U2 = Math.atan((1-f) * Math.tan(deg2rad(lat2)));
263            double sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);
264            double sinU2 = Math.sin(U2), cosU2 = Math.cos(U2);
265            
266            double lambda = L, lambdaP, iterLimit = 100;
267            double cosSqAlpha, cos2SigmaM, sinSigma, cosSigma, sigma, sinLambda, cosLambda;
268            do {
269              sinLambda = Math.sin(lambda);
270              cosLambda = Math.cos(lambda);
271              sinSigma = Math.sqrt((cosU2*sinLambda) * (cosU2*sinLambda) + 
272                (cosU1*sinU2-sinU1*cosU2*cosLambda) * (cosU1*sinU2-sinU1*cosU2*cosLambda));
273              if (sinSigma==0) return 0;  // co-incident points
274              cosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda;
275              sigma = Math.atan2(sinSigma, cosSigma);
276              double sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
277              cosSqAlpha = 1 - sinAlpha*sinAlpha;
278              cos2SigmaM = cosSigma - 2*sinU1*sinU2/cosSqAlpha;
279              if (Double.isNaN(cos2SigmaM)) cos2SigmaM = 0;  // equatorial line: cosSqAlpha=0 (�6)
280              double C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));
281              lambdaP = lambda;
282              lambda = L + (1-C) * f * sinAlpha *
283                (sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));
284            } while (Math.abs(lambda-lambdaP) > 1e-12 && --iterLimit>0);
285            if (iterLimit==0) return Double.NaN; // formula failed to converge
286           
287            double uSq = cosSqAlpha * (a*a - b*b) / (b*b);
288            double A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));
289            double B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));
290            double deltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-
291              B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));
292            
293            // initial & final bearings
294            // double fwdAz = Math.atan2(cosU2*sinLambda, cosU1*sinU2-sinU1*cosU2*cosLambda);
295            // double revAz = Math.atan2(cosU1*sinLambda, -sinU1*cosU2+cosU1*sinU2*cosLambda);
296            
297            // s = s.toFixed(3); // round to 1mm precision
298
299            distance = b*A*(sigma-deltaSigma);
300            iDistanceCache.put(id, distance);
301            return distance;
302        } finally {
303            iLock.writeLock().unlock();
304        }
305    }
306    
307    /**
308     * Compute distance in minutes.
309     * 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).
310     * @param lat1 first coordinate's latitude
311     * @param lon1 first coordinate's longitude
312     * @param lat2 second coordinate's latitude
313     * @param lon2 second coordinate's longitude
314     * @return distance in minutes
315     * @deprecated Use @{link {@link DistanceMetric#getDistanceInMinutes(Long, Double, Double, Long, Double, Double)} instead (to include travel time matrix when available).
316     */
317    @Deprecated
318    public int getDistanceInMinutes(double lat1, double lon1, double lat2, double lon2) {
319        return (int) Math.round(getDistanceInMeters(lat1, lon1, lat2, lon2) / iSpeed);
320    }
321    
322    /**
323     * Converts minutes to meters.
324     * Property Distances.Speed (in meters per minute) is used, defaults to 1000 meters per 15 minutes.
325     * @param min minutes to travel
326     * @return meters to travel
327     */
328    public double minutes2meters(int min) {
329        return iSpeed * min;
330    }
331    
332
333    /** Back-to-back classes in rooms within this limit have neutral preference 
334     * @return limit in meters
335     **/
336    public double getInstructorNoPreferenceLimit() {
337        return iInstructorNoPreferenceLimit;
338    }
339
340    /** Back-to-back classes in rooms within this limit have discouraged preference 
341     * @return limit in meters
342     **/
343    public double getInstructorDiscouragedLimit() {
344        return iInstructorDiscouragedLimit;
345    }
346
347    /** Back-to-back classes in rooms within this limit have strongly discouraged preference, it is prohibited to exceed this limit.
348     * @return limit in meters 
349     **/
350    public double getInstructorProhibitedLimit() {
351        return iInstructorProhibitedLimit;
352    }
353    
354    /**
355     * When Distances.ComputeDistanceConflictsBetweenNonBTBClasses is enabled, distance limit (in minutes)
356     * for a long travel.
357     * @return travel time in minutes
358     */
359    public double getInstructorLongTravelInMinutes() {
360        return iInstructorLongTravelInMinutes;
361    }
362    
363    /** True if legacy mode is used (Euclidian distance where 1 unit is 10 meters) 
364     * @return true if the ellipsoid model is the old one
365     **/
366    public boolean isLegacy() {
367        return iModel == Ellipsoid.LEGACY;
368    }
369    
370    /** Maximal travel distance between rooms when no coordinates are given 
371     * @return travel time in minutes
372     **/
373    public int getMaxTravelDistanceInMinutes() {
374        return iMaxTravelTime;
375    }
376    
377    /** Set maximal travel distance between rooms when no coordinates are given
378     * @param maxTravelTime max travel time in minutes
379     */
380    public void setMaxTravelDistanceInMinutes(int maxTravelTime) {
381        iMaxTravelTime = maxTravelTime;
382    }
383
384    /** Add travel time between two locations 
385     * @param roomId1 first room's id
386     * @param roomId2 second room's id
387     * @param travelTimeInMinutes travel time in minutes 
388     **/
389    public void addTravelTime(Long roomId1, Long roomId2, Integer travelTimeInMinutes) {
390        iLock.writeLock().lock();
391        try {
392            if (roomId1 == null || roomId2 == null) return;
393            if (roomId1 < roomId2) {
394                Map<Long, Integer> times = iTravelTimes.get(roomId1);
395                if (times == null) { times = new HashMap<Long, Integer>(); iTravelTimes.put(roomId1, times); }
396                if (travelTimeInMinutes == null)
397                    times.remove(roomId2);
398                else
399                    times.put(roomId2, travelTimeInMinutes);
400            } else {
401                Map<Long, Integer> times = iTravelTimes.get(roomId2);
402                if (times == null) { times = new HashMap<Long, Integer>(); iTravelTimes.put(roomId2, times); }
403                if (travelTimeInMinutes == null)
404                    times.remove(roomId1);
405                else
406                    times.put(roomId1, travelTimeInMinutes);
407            }            
408        } finally {
409            iLock.writeLock().unlock();
410        }
411    }
412    
413    /** Return travel time between two locations. 
414     * @param roomId1 first room's id
415     * @param roomId2 second room's id
416     * @return travel time in minutes
417     **/
418    public Integer getTravelTimeInMinutes(Long roomId1, Long roomId2) {
419        iLock.readLock().lock();
420        try {
421            if (roomId1 == null || roomId2 == null) return null;
422            if (roomId1 < roomId2) {
423                Map<Long, Integer> times = iTravelTimes.get(roomId1);
424                return (times == null ? null : times.get(roomId2));
425            } else {
426                Map<Long, Integer> times = iTravelTimes.get(roomId2);
427                return (times == null ? null : times.get(roomId1));
428            }
429        } finally {
430            iLock.readLock().unlock();
431        }
432    }
433    
434    /** Return travel time between two locations. Travel times are used when available, use coordinates otherwise. 
435     * @param roomId1 first room's id
436     * @param lat1 first room's latitude
437     * @param lon1 first room's longitude
438     * @param roomId2 second room's id
439     * @param lat2 second room's latitude
440     * @param lon2 second room's longitude
441     * @return distance in minutes
442     **/
443    public Integer getDistanceInMinutes(Long roomId1, Double lat1, Double lon1, Long roomId2, Double lat2, Double lon2) {
444        Integer distance = getTravelTimeInMinutes(roomId1, roomId2);
445        if (distance != null) return distance;
446        
447        if (lat1 == null || lat2 == null || lon1 == null || lon2 == null)
448            return getMaxTravelDistanceInMinutes();
449        else 
450            return (int) Math.min(getMaxTravelDistanceInMinutes(), Math.round(getDistanceInMeters(lat1, lon1, lat2, lon2) / iSpeed));
451    }
452    
453    /** Return travel distance between two locations.  Travel times are used when available, use coordinates otherwise
454     * @param roomId1 first room's id
455     * @param lat1 first room's latitude
456     * @param lon1 first room's longitude
457     * @param roomId2 second room's id
458     * @param lat2 second room's latitude
459     * @param lon2 second room's longitude
460     * @return distance in meters
461     **/
462    public double getDistanceInMeters(Long roomId1, Double lat1, Double lon1, Long roomId2, Double lat2, Double lon2) {
463        Integer distance = getTravelTimeInMinutes(roomId1, roomId2);
464        if (distance != null) return minutes2meters(distance);
465        
466        return getDistanceInMeters(lat1, lon1, lat2, lon2);
467    }
468    
469    /** Return travel times matrix
470     * @return travel times matrix
471     **/
472    public Map<Long, Map<Long, Integer>> getTravelTimes() { return iTravelTimes; }
473    
474    /**
475     * True if distances should be considered between classes that are NOT back-to-back. Distance in minutes is then 
476     * 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.
477     * @return true if distances should be considered between classes that are NOT back-to-back
478     **/
479    public boolean doComputeDistanceConflictsBetweenNonBTBClasses() {
480        return iComputeDistanceConflictsBetweenNonBTBClasses;
481    }
482    
483    /**
484     * Reference of the accommodation of students that need short distances
485     */
486    public String getShortDistanceAccommodationReference() {
487        return iShortDistanceAccommodationReference;
488    }
489    
490    /** Few tests 
491     * @param args program arguments
492     **/
493    public static void main(String[] args) {
494        System.out.println("Distance between Prague and Zlin: " + new DistanceMetric().getDistanceInMeters(50.087661, 14.420535, 49.226736, 17.668856) / 1000.0 + " km");
495        System.out.println("Distance between ENAD and PMU: " + new DistanceMetric().getDistanceInMeters(40.428323, -86.912785, 40.425078, -86.911474) + " m");
496        System.out.println("Distance between ENAD and ME: " + new DistanceMetric().getDistanceInMeters(40.428323, -86.912785, 40.429338, -86.91267) + " m");
497        System.out.println("Distance between Prague and Zlin: " + new DistanceMetric().getDistanceInMinutes(50.087661, 14.420535, 49.226736, 17.668856) / 60 + " hours");
498        System.out.println("Distance between ENAD and PMU: " + new DistanceMetric().getDistanceInMinutes(40.428323, -86.912785, 40.425078, -86.911474) + " minutes");
499        System.out.println("Distance between ENAD and ME: " + new DistanceMetric().getDistanceInMinutes(40.428323, -86.912785, 40.429338, -86.91267) + " minutes");
500    }
501
502}