001package es.ucm.fdi.gaia.jcolibri.method.retrieve.NNretrieval.similarity.local; 002 003 004import es.ucm.fdi.gaia.jcolibri.exception.NoApplicableSimilarityFunctionException; 005import es.ucm.fdi.gaia.jcolibri.method.retrieve.NNretrieval.similarity.LocalSimilarityFunction; 006 007/** 008 * This function computes the similarity between two enum values as their cyclic 009 * distance. 010 * 011 * @author Juan A. Recio-Garc�a 012 */ 013public class EnumCyclicDistance implements LocalSimilarityFunction { 014 015 016 017 /** 018 * Applies the similarity. 019 * 020 * @param o1 021 * Enum. 022 * @param o2 023 * Enum. 024 * @return the result to apply the similarity. 025 */ 026 public double compute(Object o1, Object o2) throws NoApplicableSimilarityFunctionException { 027 if ((o1 == null) || (o2 == null)) 028 return 0; 029 if(!(o1 instanceof Enum)) 030 throw new NoApplicableSimilarityFunctionException(this.getClass(), o1.getClass()); 031 if(!(o2 instanceof Enum)) 032 throw new NoApplicableSimilarityFunctionException(this.getClass(), o2.getClass()); 033 034 Enum<?> e1 = (Enum<?>)o1; 035 Enum<?> e2 = (Enum<?>)o2; 036 037 double size = e1.getDeclaringClass().getEnumConstants().length; 038 double distance = Math.abs(e1.ordinal() - e2.ordinal()); 039 double cyclicDistance = size - distance; 040 041 if(distance <= cyclicDistance) 042 return 1 - distance / size; 043 else 044 return 1 - cyclicDistance / size; 045 } 046 047 /** Applicable to Enum */ 048 public boolean isApplicable(Object o1, Object o2) 049 { 050 if((o1==null)&&(o2==null)) 051 return true; 052 else if(o1==null) 053 return o2 instanceof Enum; 054 else if(o2==null) 055 return o1 instanceof Enum; 056 else 057 return (o1 instanceof Enum)&&(o2 instanceof Enum); 058 } 059 060}