001/**
002 * PearsonMatrixCaseBase.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 * 11/11/2007
008 */
009package es.ucm.fdi.gaia.jcolibri.extensions.recommendation.collaborative;
010
011import java.util.*;
012import java.util.Map.Entry;
013
014import org.apache.logging.log4j.LogManager;
015
016import es.ucm.fdi.gaia.jcolibri.cbrcore.Attribute;
017
018/**
019 * Extension of the MatrixCaseBase that computes similarities among neighbors 
020 * using the Pearson Correlation.
021 * <br>
022 * It uses a minCorrelateItems Factor to weight similar neighbors that have
023 * few common correlate items.
024 * 
025 * @author Juan A. Recio-Garcia
026 * @author Developed at University College Cork (Ireland) in collaboration with Derek Bridge.
027 * @version 1.0
028 */
029public class PearsonMatrixCaseBase extends MatrixCaseBase
030{
031    /** 
032     * Factor that decreases the similarity between users 
033     * who have fewer than this number of co-rated items 
034     */
035    int minCorrelateItemsFactor;
036    
037    /**
038     * Constructor
039     * @param value is the attribute of the result part of the case that contains the rating
040     * @param minCorrelateItemsFactor factor that decreases the similarity between users 
041     * who have fewer than this number of co-rated items
042     */
043    public PearsonMatrixCaseBase(Attribute value, int minCorrelateItemsFactor)
044    {
045        super(value);
046        this.minCorrelateItemsFactor = minCorrelateItemsFactor;
047    }
048    
049    
050    @Override
051    /**
052     * Computes the similarity between users
053     */
054    protected void computeSimilarities()
055    {
056        this.computeAverages();
057        this.computeSimilarityByDescriptionId();
058        this.computeSimilarityLists();
059    }
060    
061    // stores the similarity lists
062    private HashMap<Integer,List<SimilarTuple>> similLists;
063    
064    private void computeSimilarityLists()
065    {
066        similLists = new HashMap<Integer,List<SimilarTuple>>();
067        for(Integer key: similarities.keySet())
068        {
069            ArrayList<SimilarTuple> list = new ArrayList<SimilarTuple>();
070            HashMap<Integer,Double> similMap = similarities.get(key);
071            for(Entry<Integer,Double> entry : similMap.entrySet())
072                list.add(new SimilarTuple(entry.getKey(), entry.getValue()));
073            java.util.Collections.sort(list);
074            similLists.put(key, list);
075        }
076    }
077    
078    @Override
079    /**
080     * Returns a list of similar users to a given one in decreasing order 
081     */
082    public List<SimilarTuple> getSimilar(Integer id)
083    {
084        return similLists.get(id);
085    }
086    
087    
088    @Override
089    /**
090     * Returns the similarity between two users
091     */
092    public double getSimil(Integer id1, Integer id2)
093    {
094        return similarities.get(id1).get(id2);
095    }
096    
097    
098    // table to store the similarities
099    private HashMap<Integer,HashMap<Integer,Double>> similarities;
100 
101    
102
103    /**
104     * Computes the Pearson Correlation between users in a smart and efficient way.
105     * This code is an adaptation of the one developed by Jerome Kelleher and Derek Bridge 
106     * for the Collaborative Movie Recommender project at University College Cork (Ireland).
107     */
108    private void computeSimilarityByDescriptionId()
109    {
110        LogManager.getLogger().info("Computing similarities");
111        similarities = new HashMap<Integer, HashMap<Integer,Double>>();
112        HashSet<Integer> keyCopy = new HashSet<Integer>(byDescriptionId.keySet());
113        for(Integer me : byDescriptionId.keySet())
114        {
115            keyCopy.remove(me);
116            for(Integer you : keyCopy)
117            {
118                
119                      Iterator<CommonRatingTuple> ratings = new CommonRatingsIterator(me, you, byDescriptionId.get(me), byDescriptionId.get(you));
120                      double sumX = 0.0;
121                      double sumXSquared = 0.0;
122                      double sumY = 0.0;
123                      double sumYSquared = 0.0;
124                      double sumXY = 0.0;
125                      double numDataPoints = 0;
126                      // X corresponds to active, Y to predictor.
127                      while (ratings.hasNext())
128                      {  
129                         CommonRatingTuple rt = (CommonRatingTuple) ratings.next();
130                         double x = rt.getRating1();
131                         double y = rt.getRating2();
132                         numDataPoints++;
133                         sumX += x;
134                         sumY += y;
135                         sumXSquared += square(x);
136                         sumYSquared += square(y);
137                         sumXY += (x * y);
138                      }
139                      // update AbstractMovieRecommender by the correct comparison count.
140                      // Modified to remove comparisons required for search
141                      // AbstractMovieRecommender.addToComparisonCount(numDataPoints);
142
143                      double correlation = 0.0;
144                      if (numDataPoints != 0 )
145                      {  double numerator = sumXY - ((sumX * sumY) / numDataPoints);
146                         double sqrt =
147                            (sumXSquared - (square(sumX) / numDataPoints)) *
148                            (sumYSquared - (square(sumY) / numDataPoints));
149                         double denominator = Math.sqrt(sqrt);
150
151                         // output 0 here according to Herlocker's recommendations,
152                         // also watch for negative square roots (extremely rare)
153                         correlation = denominator == 0.0 || sqrt < 0.0 ? 0.0 :
154                            numerator / denominator;
155                         correlation = correlation * numDataPoints / minCorrelateItemsFactor;
156                      }
157                
158                
159                
160                HashMap<Integer,Double> mySimilList = similarities.get(me);
161                if(mySimilList == null)
162                {
163                    mySimilList = new HashMap<Integer, Double>();
164                    similarities.put(me, mySimilList);
165                }
166                mySimilList.put(you, correlation);
167                
168                HashMap<Integer,Double> yourSimilList = similarities.get(you);
169                if(yourSimilList == null)
170                {
171                    yourSimilList = new HashMap<Integer, Double>();
172                    similarities.put(you, yourSimilList);
173                }
174                yourSimilList.put(me, correlation);
175                
176            }
177        }
178    }
179
180    // stores the averages
181    private HashMap<Integer,Double> averages;
182    
183    // computes the averages
184    private void computeAverages()
185    {
186        LogManager.getLogger().info("Computing Averages");
187        averages = new HashMap<Integer, Double>();
188        for(Integer i : byDescriptionId.keySet())
189        {
190            ArrayList<RatingTuple> list = byDescriptionId.get(i);
191            double acum = 0;
192            for(RatingTuple rt : list)
193                acum += rt.getRating();
194            double size = list.size();
195            averages.put(i, acum/size);
196        }
197    }
198    
199    /**
200     * returns the ratings average for a given user
201     * @param id is the user
202     * @return the ratings average
203     */
204    public double getAverage(int id)
205    {
206        return averages.get(id);
207    }
208    
209    
210    
211    /**
212     * Return the square of the parameter number.
213     *
214     * @param n the number to be squared.
215     * @return n*n.
216     */
217    private static double square(double n)
218    {  return n * n;
219    }
220
221}