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 returns 1 if the difference between two numbers is less than a 009 * threshold, 0 in the other case. 010 */ 011public class Threshold implements LocalSimilarityFunction { 012 013 014 /** Threshold. */ 015 double _threshold; 016 017 /** 018 * Constructor. 019 */ 020 public Threshold(double threshold) { 021 _threshold = threshold; 022 } 023 024 /** 025 * Applies the similarity function. 026 */ 027 public int compare(int x, int y) { 028 if (Math.abs(x - y) > _threshold) 029 return 0; 030 else 031 return 1; 032 } 033 034 035 036 /** 037 * Applies the similarity function. 038 * 039 * @param o1 040 * Integer 041 * @param o2 042 * Integer 043 * @return result of apply the similarity function. 044 */ 045 public double compute(Object o1, Object o2) throws NoApplicableSimilarityFunctionException { 046 if ((o1 == null) || (o2 == null)) 047 return 0; 048 if (!(o1 instanceof Integer)) 049 throw new NoApplicableSimilarityFunctionException(this.getClass(), o1.getClass()); 050 if (!(o2 instanceof Integer)) 051 throw new NoApplicableSimilarityFunctionException(this.getClass(), o2.getClass()); 052 053 054 Integer i1 = (Integer) o1; 055 Integer i2 = (Integer) o2; 056 return (double) compare(i1.intValue(), i2.intValue()); 057 } 058 059 /** Applicable to Integer */ 060 public boolean isApplicable(Object o1, Object o2) 061 { 062 if((o1==null)&&(o2==null)) 063 return true; 064 else if(o1==null) 065 return o2 instanceof Integer; 066 else if(o2==null) 067 return o1 instanceof Integer; 068 else 069 return (o1 instanceof Integer)&&(o2 instanceof Integer); 070 } 071}