001/**
002 * ExpertClerkMedianScoring.java
003 * jCOLIBRI2 framework. 
004 * @author Juan A. Recio-Garc�a.
005 * GAIA - Group for Artificial Intelligence Applications
006 * http://gaia.fdi.ucm.es
007 * 04/11/2007
008 */
009package es.ucm.fdi.gaia.jcolibri.method.retrieve.DiverseByMedianRetrieval;
010
011import java.util.ArrayList;
012import java.util.Collection;
013import java.util.HashMap;
014
015import es.ucm.fdi.gaia.jcolibri.cbrcore.Attribute;
016import es.ucm.fdi.gaia.jcolibri.cbrcore.CBRCase;
017import es.ucm.fdi.gaia.jcolibri.cbrcore.CBRQuery;
018import es.ucm.fdi.gaia.jcolibri.cbrcore.CaseComponent;
019import es.ucm.fdi.gaia.jcolibri.method.retrieve.RetrievalResult;
020import es.ucm.fdi.gaia.jcolibri.method.retrieve.NNretrieval.NNConfig;
021import es.ucm.fdi.gaia.jcolibri.method.retrieve.NNretrieval.NNScoringMethod;
022import es.ucm.fdi.gaia.jcolibri.util.AttributeUtils;
023import es.ucm.fdi.gaia.jcolibri.util.CopyUtils;
024
025/**
026 * ExpertClerk Median algorithm. 
027 * This algorithm chooses the first case that is closed to the median of cases.
028 * Then the remaining are selected taking into account negative and possitive
029 * characteristics. A characteristic is an attribute that exceeds a predefined
030 * threshold. It is positive if is greater thatn the value of the median. And negative
031 * otherwise. The number of positive plus the negative characteristics is used
032 * to rank the cases and obtain the following k-1 cases.
033 * <p>See:
034 * <p>
035 * H. Shimazu. ExpertClerk: A Conversational Case-Based Reasoning Tool for 
036 * Developing Salesclerk Agents in E-Commerce Webshops. Artif. Intell. Rev., 
037 * 18(3-4):223-244, 2002.
038 * 
039 * @author Juan A. Recio-Garcia
040 * @author Developed at University College Cork (Ireland) in collaboration with Derek Bridge.
041 * @version 1.0
042 *
043 */
044public class ExpertClerkMedianScoring
045{
046    /******************************************************************************/
047    /**                           STATIC METHODS                                 **/
048    /******************************************************************************/    
049    
050    /**
051     * Returns diverse cases using the ExpertClerk median method.
052     * @param cases to retrieve from
053     * @param simConfig is the nn configuration
054     * @param thresholds to obtain the characteristics
055     * @return a collection of cases
056     */
057    public static Collection<RetrievalResult> getDiverseByMedian(Collection<CBRCase> cases, NNConfig simConfig, HashMap<Attribute,Double> thresholds)
058    {
059        CaseComponent median = calculateMedian(cases);
060        
061        CBRQuery query = new CBRQuery();
062        query.setDescription(median);
063        Collection<RetrievalResult> distancesToMedian = NNScoringMethod.evaluateSimilarity(cases,query,simConfig);
064        CBRCase first = distancesToMedian.iterator().next().get_case();
065        
066        ArrayList<RetrievalResult> characteristics = new ArrayList<RetrievalResult>();
067        double maxCharacteristics = AttributeUtils.getAttributes(cases.iterator().next().getDescription()).size();
068        for(CBRCase _case:cases)
069        {
070            if(_case.equals(first))
071                continue;
072            int chars = computeCharacteristics(_case, median, simConfig, thresholds);
073            characteristics.add(new RetrievalResult(_case, ((double)chars)/maxCharacteristics));
074        }
075        characteristics.add(new RetrievalResult(first,1.0));
076        java.util.Collections.sort(characteristics);
077
078        return characteristics;
079    }
080    
081    /**
082     * Computes the characteristics
083     */
084    private static int computeCharacteristics(CBRCase _case, CaseComponent median, NNConfig simConfig, HashMap<Attribute,Double> thresholds)
085    {
086        int characteristics = 0;
087        for(Attribute at: AttributeUtils.getAttributes(_case.getDescription()))
088        {
089            if(at.equals(_case.getDescription().getIdAttribute()))
090                continue;
091            
092            Object value = AttributeUtils.findValue(at, _case.getDescription());
093            Object medValue = AttributeUtils.findValue(at, median);
094            
095            if((value==null)||(medValue==null))
096                continue;
097            
098            if(value instanceof Number)
099            {
100                double v = ((Number)value).doubleValue();
101                double medV = ((Number)medValue).doubleValue();
102                double ad = simConfig.getWeight(at) * (v - medV);
103                
104                Double threshold = thresholds.get(at);
105                if(threshold == null)
106                    threshold = 0.5;
107                if(Math.abs(ad) > threshold)  
108                        characteristics++;
109            }
110            else if(value instanceof Enum)
111            {
112                double v = ((Enum<?>)value).ordinal();
113                double medV = ((Enum<?>)medValue).ordinal();
114                double ad = simConfig.getWeight(at) * (v - medV);
115                
116                Double threshold = thresholds.get(at);
117                if(threshold == null)
118                    threshold = 1.0;
119                if(Math.abs(ad) > threshold)   
120                        characteristics++;
121            }
122            else if(!value.equals(medValue))
123                characteristics++;
124
125        
126        }
127        return characteristics;
128    }
129    
130    /**
131     * Calculates the median
132     */
133    private static CaseComponent calculateMedian(Collection<CBRCase> cases)
134    {
135        HashMap<Attribute,HashMap<Object,Integer>> enumCount = new HashMap<Attribute, HashMap<Object,Integer>>();
136        HashMap<Attribute,Double> numValues = new HashMap<Attribute,Double>();
137        
138        for(CBRCase _case :cases)
139        {
140            for(Attribute at : AttributeUtils.getAttributes(_case.getDescription()))
141            {
142                if(at.equals(_case.getDescription().getIdAttribute()))
143                    continue;
144                Object value = AttributeUtils.findValue(at, _case.getDescription());
145                if(value == null)
146                    continue;
147                
148                if(value instanceof Number)
149                {
150                    Double sum = numValues.get(at);
151                    if(sum == null)
152                        numValues.put(at, ((Number)value).doubleValue());
153                    else
154                        numValues.put(at, sum+((Number)value).doubleValue());
155                }
156                else
157                {
158                    HashMap<Object,Integer> enumValues = enumCount.get(at);
159                    if(enumValues == null)
160                    {
161                        enumValues = new HashMap<Object,Integer>();
162                        enumCount.put(at, enumValues);
163                    }
164                    Integer count = enumValues.get(value);
165                    if(count == null)
166                        enumValues.put(value, new Integer(0));
167                    else
168                        enumValues.put(value, new Integer(count+1));
169                }
170            }
171        }
172        CaseComponent res = CopyUtils.copyCaseComponent(cases.iterator().next().getDescription());
173        for(Attribute at: AttributeUtils.getAttributes(res))
174        {
175            HashMap<Object,Integer> enumValues = enumCount.get(at);
176            if(enumValues != null)
177            {
178                Object maxObject = null;
179                int max = 0; 
180                for(Object value : enumValues.keySet())
181                {
182                    Integer appears = enumValues.get(value);
183                    if(appears > max)
184                    {
185                        max = appears;
186                        maxObject = value;
187                    }
188                }
189                AttributeUtils.setValue(at, res, maxObject);
190                continue;
191            }
192            Double sum = numValues.get(at);
193            if(sum != null)
194            {
195                if(at.getType().equals(Integer.class))
196                    AttributeUtils.setValue(at, res, ((Number)(sum/(double)cases.size())).intValue() );
197                else if(at.getType().equals(Double.class))
198                    AttributeUtils.setValue(at, res, (sum/(double)cases.size()) );
199                else if(at.getType().equals(Float.class))
200                    AttributeUtils.setValue(at, res, ((Number)(sum/(double)cases.size())).floatValue() );
201                else if(at.getType().equals(Long.class))
202                    AttributeUtils.setValue(at, res, ((Number)(sum/(double)cases.size())).longValue() );
203                else if(at.getType().equals(Short.class))
204                    AttributeUtils.setValue(at, res, ((Number)(sum/(double)cases.size())).shortValue() );
205            }
206            else
207                AttributeUtils.setValue(at, res, null);
208        }
209        return res;
210    }
211
212}