001/**
002 * MatrixCaseBase.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 org.apache.logging.log4j.LogManager;
012
013import es.ucm.fdi.gaia.jcolibri.cbrcore.*;
014import es.ucm.fdi.gaia.jcolibri.exception.AttributeAccessException;
015import es.ucm.fdi.gaia.jcolibri.util.ProgressController;
016
017import java.util.*;
018
019
020/**
021 * Specific implementation of CBRCaseBase to allow collaborative recommendations. 
022 * These kind of recommendations are based in the past experieces of other users.<br>
023 * This case base manages cases composed by a description, a solution and a result. 
024 * The description usually contains the information about the user that made the recommendation,
025 * the solution contains the information about the recommended item, and the 
026 * result stores the rating value for the item (the value that the user assigns to an item after evaluating it).<br>
027 * This way, this case base implementation stores cases as a table:<br>
028 * <table border="1" cellspacing="0" cellpadding="2" width="90">
029 *  <tr><td></td><td>Item1</td><td>Item2</td><td>Item3</td><td>Item4</td><td>Item5</td><td>...</td><td>ItemM</td></tr>
030 *  <tr><td>User1</td><td></td><td>rating12</td><td></td><td>rating14</td><td></td><td></td><td></td></tr>
031 *  <tr><td>User2</td><td>rating21</td><td></td><td>rating23</td><td></td><td></td><td></td><td>rating2N</td></tr>
032 *  <tr><td>User3</td><td></td><td></td><td>rating33</td><td>rating34</td><td></td><td></td><td>rating3N</td></tr>
033 *  <tr><td>...</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
034 *  <tr><td>UserN</td><td></td><td>ratingN2</td><td></td><td></td><td>ratingN5</td><td></td><td>ratingNN</td></tr>
035 * </table>
036 * The values of the users column and the items row are the ids of the description and solution parts of the case.
037 * These ids must be integer values.
038 * The ratings are obtained from an attribute of the result part.
039 * <br>
040 * Note that these cases base allows having different cases with the same description (because each user can make several recommendations).
041 * <p>
042 * Collaborative recommenders can be separated into three steps:
043 * <ol>
044 * <li>Weight all users with respect to similarity with the active user.
045 * <li>Select a subset of users as a set of predictors.
046 * <li>Normalize ratings and compute a prediction from a weighted combination of selected neighbors' ratings.
047 * </ol>
048 * There are several ways to compute first step. And it must be implemented by subclassing this class as in PearsonMatrixCaseBase.
049 * The subclasses must implement the abstract methods defined here that return the similarity among neighbors.
050 * The similarity among users is stored through SimilarityTuple objects.
051 * <p>
052 * To allow an efficient comparison, ratings must be sorted by neighbors. In the above table this means that cases
053 * are organized by rows. And that is done internally in this class through the
054 * organizeByDescriptionId() method. Then, the ratings of each user can be accessed through the getRatingTuples()
055 * method. A RatingTuple object stores the id of the item and its rating (id of the solution and id of the result).
056 * <p>
057 * There are also 2 internal classes (CommonRatingTuple and CommonRatingsIterator) that allow to obtain efficiently the common 
058 * ratings of two users. This will be used by subclasses when computing the neighbors similarity. The code of these classes
059 * is an adaptation of the one developed by Jerome Kelleher and Derek Bridge for the Collaborative Movie Recommender project at
060 * University College Cork (Ireland).
061 * <p>
062 * Recommender 12 shows how to use these classes.
063 * 
064 * @author Juan A. Recio-Garcia
065 * @author Developed at University College Cork (Ireland) in collaboration with Derek Bridge.
066 * @version 1.0
067 */
068public abstract class MatrixCaseBase implements CBRCaseBase
069{
070    
071    ///////////////// ABSTRACT METHODS ///////////////////////////////
072    
073    /**
074     * Computes the similarity of neighbors (each neighbor is defined by the description)
075     */
076    protected abstract void computeSimilarities();
077    
078    /**
079     * Returns the similarity of two neighbors.
080     * @param id1 of the first neighbor
081     * @param id2 of the second neighbor.
082     * @return a double between 0 and 1
083     */
084    public abstract double getSimil(Integer id1, Integer id2);
085    
086    /**
087     * Returns the list of similar neighbors for a given one
088     * @param id of the neighbor
089     * @return a list of SimilarTuple (other neighbor id + similarity value).
090     */
091    public abstract Collection<SimilarTuple> getSimilar(Integer id);
092    
093    //////////////////////////////////////////////////////////////////
094    
095    
096    // Connector
097    private Connector connector;
098    // Cases list
099    private Collection<CBRCase> cases;
100    
101    // Attribute of the result that stores the ratings
102    private Attribute value;
103    
104    /**
105     * Constructor. The value parameter defines the attribute of the result that stores the ratings.
106     * @param value
107     */
108    public MatrixCaseBase(Attribute value)
109    {
110        this.value = value;
111    }
112    
113    /**
114     * Initializes the case base. 
115     * Organizes ratings by the description id of the cases and calls the computeSimilarities() abstract method.
116     */
117    public void init(Connector connector) {
118        this.connector = connector;
119        ProgressController.init(MatrixCaseBase.class,"Organizing Collaborative Case Base", ProgressController.UNKNOWN_STEPS);
120        LogManager.getLogger().info("Loading cases from connector");
121        cases = this.connector.retrieveAllCases();
122        organizeByDescriptionId();
123        computeSimilarities();
124        ProgressController.finish(MatrixCaseBase.class);
125    }
126        
127    /**
128     * Utility method to obtain the description object given its id.
129     * @param id of the description object
130     * @return the description object
131     */
132    public CaseComponent getDescription(Integer id)
133    {
134        return descriptions.get(id);
135    }
136
137    /**
138     * Utility method to obtain all the descriptions stored in this case base
139     * @return a set of ids.
140     */
141    public Set<Integer> getDescriptions()
142    {
143        return descriptions.keySet();
144    }
145    
146    /**
147     * Utility method to obtain the solution object given its id.
148     * @param id of the solution object
149     * @return the solution object
150     */
151    public CaseComponent getSolution(Integer id)
152    {
153        return solutions.get(id);
154    }
155    
156    /**
157     * Utility method to obtain all the solutions stored in this case base
158     * @return a set of ids.
159     */
160    public Set<Integer> getSolutions()
161    {
162        return solutions.keySet();
163    }
164    
165    /**
166     * Returns the ratings that a user has done.
167     * @param descriptionId of the user
168     * @return collection of rating tuples (solution id + rating value)
169     */
170    public Collection<RatingTuple> getRatingTuples(int descriptionId)
171    {
172        return byDescriptionId.get(descriptionId);
173    }
174    
175    /** Table that stores the list of ratingTuples for each description id (user)*/
176    HashMap<Integer,ArrayList<RatingTuple>> byDescriptionId;
177    /** Table that organizes description components by id */
178    HashMap<Integer,CaseComponent> descriptions;
179    /** Table that organizes solution components by id */
180    HashMap<Integer,CaseComponent> solutions;
181    
182
183    /**
184     * Organizes cases by the description id.
185     */
186    private void organizeByDescriptionId()
187    {
188        LogManager.getLogger().info("Organizing cases");
189        try
190        {
191            byDescriptionId = new HashMap<Integer,ArrayList<RatingTuple>>();
192            descriptions = new HashMap<Integer, CaseComponent>();
193            solutions = new HashMap<Integer, CaseComponent>();
194            for(CBRCase c: cases)
195            {
196                Integer descId = (Integer)c.getID();
197                ArrayList<RatingTuple> list = byDescriptionId.get(descId);
198                if(list == null)
199                {
200                        list = new ArrayList<RatingTuple>();
201                        byDescriptionId.put(descId, list);
202                        descriptions.put(descId,c.getDescription());
203                }
204                Integer solId = (Integer) c.getSolution().getIdAttribute().getValue(c.getSolution());
205                solutions.put(solId, c.getSolution());
206                Number resId = (Number) value.getValue(c.getResult());
207                list.add(new RatingTuple(solId, resId.doubleValue()));
208                ProgressController.step(MatrixCaseBase.class);
209
210            }
211            for(ArrayList<RatingTuple> list: byDescriptionId.values())
212                java.util.Collections.sort(list);
213        } catch (AttributeAccessException e)
214        {
215            LogManager.getLogger().error(e);
216            
217        }
218    }
219    
220    /**
221     * Closes the case base
222     */
223    public void close()
224    {
225        connector.close();
226    }
227
228    /**
229     * Forgets cases. It does nothing in this implementation
230     */ 
231    public void forgetCases(Collection<CBRCase> cases)
232    {
233    }
234
235    /**
236     * Returns the stored cases
237     */
238    public Collection<CBRCase> getCases()
239    {
240        return cases;
241    }
242
243    /**
244     * Returns selected cases. It does nothing in this implementation.
245     */
246    public Collection<CBRCase> getCases(CaseBaseFilter filter)
247    {
248        return null;
249    }
250
251    /**
252     * Adds new cases to the case base, reorganizing the cases base and re-computing neighbors similarities.
253     */
254    public void learnCases(Collection<CBRCase> cases)
255    {
256        this.cases.addAll(cases);
257        connector.storeCases(cases);
258        organizeByDescriptionId();
259        computeSimilarities();
260    }
261    
262    
263    //////////////////////////////////////////////////////////////////////////////////////
264    ////////////                     Internal Classes                   //////////////////
265    //////////////////////////////////////////////////////////////////////////////////////
266    
267    /**
268     * Stores a rating for an item.
269     * @author Juan A. Recio-Garcia
270     * @version 1.0
271     */
272    public class RatingTuple implements Comparable<RatingTuple>
273    {
274        int solutionId;
275        double rating;
276        
277        public RatingTuple(int solutionId, double rating)
278        {
279            super();
280            this.solutionId = solutionId;
281            this.rating = rating;
282        }
283        
284        public boolean equals(Object o)
285        {
286            return solutionId == ((RatingTuple)o).getSolutionId();
287        }
288        
289        public int compareTo(RatingTuple o)
290        {
291            return solutionId - o.solutionId;
292        }
293        /**
294         * @return Returns the rating.
295         */
296        public double getRating()
297        {
298            return rating;
299        }
300        /**
301         * @return Returns the solutionId.
302         */
303        public int getSolutionId()
304        {
305            return solutionId;
306        }
307        
308        public String toString()
309        {
310            return "("+solutionId+"->"+rating+")";
311        }
312    }
313    
314    /**
315     * Stores the similarity among neighbors.
316     * @author Juan A. Recio-Garcia
317     * @version 1.0
318     *
319     */
320    public class SimilarTuple implements Comparable<SimilarTuple>
321    {
322        int similarId;
323        double similarity;
324
325        public SimilarTuple(int similarId, double similarity)
326        {
327            super();
328            this.similarId = similarId;
329            this.similarity = similarity;
330        }
331
332        /**
333         * @return Returns the similarId.
334         */
335        public int getSimilarId()
336        {
337            return similarId;
338        }
339
340        /**
341         * @return Returns the similarity.
342         */
343        public double getSimilarity()
344        {
345            return similarity;
346        }
347
348        public int compareTo(SimilarTuple o)
349        {
350            return (int) (1000*((o).similarity - similarity));
351        }
352        
353        public String toString()
354        {
355            return "["+similarId+","+similarity+"]";
356        }
357    }
358    
359    
360    ///////////////////////////////////////////////////////////////////////////////////
361    // Following code is an adaptation of the Collaborative Movie Recommender        //
362    // Project implemented by Jerome Kelleher at University College Cork (Ireland)   //
363    ///////////////////////////////////////////////////////////////////////////////////
364    
365    /**
366     * Stores the ratings of two different users for the same item.
367     * 
368     */
369    class CommonRatingTuple
370    {
371        int id1;
372        double rating1;
373        int id2;
374        double rating2;
375        int ratedId;
376        
377        /**
378         * Constructor
379         * @param id1 of user1
380         * @param rating1 of user1
381         * @param id2 of user 2
382         * @param rating2 of user2
383         * @param ratedId is the id of the rated object.
384         */
385        public CommonRatingTuple(int id1, double rating1, int id2, double rating2, int ratedId)
386        {
387            super();
388            this.id1 = id1;
389            this.rating1 = rating1;
390            this.id2 = id2;
391            this.rating2 = rating2;
392            this.ratedId = ratedId;
393        }
394        public int getId1()
395        {
396            return id1;
397        }
398        public int getId2()
399        {
400            return id2;
401        }
402        public int getRatedId()
403        {
404            return ratedId;
405        }
406        public double getRating1()
407        {
408            return rating1;
409        }
410        public double getRating2()
411        {
412            return rating2;
413        }
414    }
415    
416    /**
417     * Class that given two users returns an iterator over the common ratings.
418     * 
419     *
420     */
421    class CommonRatingsIterator implements Iterator<CommonRatingTuple>
422    {
423        int idA;
424        int idB;
425        Collection<RatingTuple> rtsA;
426        Collection<RatingTuple> rtsB;
427        Iterator<RatingTuple> iterA;
428        Iterator<RatingTuple> iterB;
429        
430        RatingTuple rka;
431        RatingTuple rkb;
432        boolean moreRatings;
433        CommonRatingTuple current;
434
435        public CommonRatingsIterator(int idA, int idB, Collection<RatingTuple> rtsA, Collection<RatingTuple> rtsB)
436        {
437            super();
438            this.idA = idA;
439            this.idB = idB;
440            this.rtsA = rtsA;
441            this.rtsB = rtsB;
442            
443              // initialise the iterators over the Correlatable's ratings
444              iterA = rtsA.iterator();
445              iterB = rtsB.iterator();
446              if (iterA.hasNext() && iterB.hasNext())
447              {  
448                 rka = (RatingTuple) iterA.next();
449                 rkb = (RatingTuple) iterB.next();
450                 moreRatings = true; // MUST be before the first call to getNextMatch!
451                 current = getNextMatch();
452              }
453              else
454              {  current = null;
455                 moreRatings = false;
456              }
457        }
458
459
460           /**
461            * Return true iff there are more common ratings
462            * in this CommonRatingsIterator.
463            *
464            * @return true iff more matches exist; false otherwise.
465            */
466           public boolean hasNext()
467           {  return current != null;
468           }
469
470           /**
471            * Return the next match in this CommonRatingsIterator.
472            * This is in the form of a CommonRatingTuple. This allows both
473            * ratings concerned be returned to the client code, thus
474            * saving a scan through the entire ratings collection.
475            *
476            * @return a RatingTuple of the next two common ratings.
477            * @throws NoSuchElementException if no more common ratings
478            * exist.
479            */
480           public CommonRatingTuple next()
481              throws NoSuchElementException
482           {  if (! hasNext())
483              {  throw new NoSuchElementException();
484              }
485              CommonRatingTuple temp = current;
486              current = getNextMatch();
487              return temp;
488           }
489        
490           /**
491            * Throws UnsupportedOperationException if called.
492            */
493           public void remove()
494              throws UnsupportedOperationException
495           {  throw new UnsupportedOperationException("remove not supported in " +
496                 "CommonRatingsIterator");
497           }
498           
499           
500           /**
501            * Return the next common rating between the two users.
502            * Return null if  no matches are left.
503            *
504            * @return a RatingTuple of the next match in the two user
505            * collections of ratings; null if no matches exist.
506            */
507           private CommonRatingTuple getNextMatch()
508           {  
509              CommonRatingTuple match = null;
510              while (moreRatings && match == null)
511              {  
512                 while (rka.compareTo(rkb) < 0 && moreRatings)
513                 {  
514                    if (iterA.hasNext())
515                    {  
516                        rka = (RatingTuple) iterA.next();
517                    }
518                    else
519                    {  
520                        moreRatings = false;
521                    }
522                 }
523                 if (rka.compareTo(rkb) == 0)
524                 {  
525                    /*
526                    * Match found.
527                    */
528                    match = new CommonRatingTuple(idA, rka.getRating(), idB, rkb.getRating(), rka.getSolutionId());
529
530                    if (iterA.hasNext() && iterB.hasNext())
531                    {  
532                        rka = (RatingTuple) iterA.next();
533                        rkb = (RatingTuple) iterB.next();
534                    }
535                    else
536                    {  
537                        moreRatings = false;
538                    }
539                 }
540                 while (rka.compareTo(rkb) > 0 && moreRatings)
541                 {  
542                     if (iterB.hasNext())
543                     {  
544                         rkb = (RatingTuple) iterB.next();
545                     }
546                     else
547                     {  
548                         moreRatings = false;
549                     }
550                 }
551              }
552              return match;
553           }
554    }
555    
556    
557    //////////////////////////////////////////////////////////////////////////////////////////
558    
559    
560}