/*
 * LensKit, an open source recommender systems toolkit.
 * Copyright 2010-2014 LensKit Contributors.  See CONTRIBUTORS.md.
 * Work on LensKit has been funded by the National Science Foundation under
 * grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
package org.grouplens.lenskit.knn.item;

import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import org.grouplens.lenskit.knn.MinNeighbors;
import org.grouplens.lenskit.knn.NeighborhoodSize;
import org.grouplens.lenskit.knn.item.model.ItemItemModel;
import org.grouplens.lenskit.scored.ScoredId;
import org.grouplens.lenskit.symbols.TypedSymbol;
import org.grouplens.lenskit.vectors.MutableSparseVector;
import org.grouplens.lenskit.vectors.SparseVector;
import org.grouplens.lenskit.vectors.VectorEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.List;

/**
 * Default item scoring algorithm. It uses up to {@link NeighborhoodSize} neighbors to
 * score each item.
 *
 * @author <a href="http://www.grouplens.org">GroupLens Research</a>
 */
public class DefaultItemScoreAlgorithm implements ItemScoreAlgorithm {
    private static Logger logger = LoggerFactory.getLogger(DefaultItemScoreAlgorithm.class);

    private final int neighborhoodSize;
    private final int minNeighbors;

    @Inject
    public DefaultItemScoreAlgorithm(@NeighborhoodSize int n, @MinNeighbors int min) {
        neighborhoodSize = n;
        minNeighbors = min <= 0 ? 1 : min;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public void scoreItems(ItemItemModel model, SparseVector userData,
                           MutableSparseVector scores,
                           NeighborhoodScorer scorer) {
        Predicate<ScoredId> usable = new VectorKeyPredicate(userData);
        List<ScoredId> neighbors = Lists.newArrayListWithCapacity(neighborhoodSize);

        // Create a channel for recording the neighborhoodsize
        MutableSparseVector sizeChannel = scores.getOrAddChannelVector(ItemItemScorer.NEIGHBORHOOD_SIZE_SYMBOL);
        sizeChannel.fill(0);
        // for each item, compute its prediction
        for (VectorEntry e : scores.view(VectorEntry.State.EITHER)) {
            final long item = e.getKey();

            for (ScoredId nbr: model.getNeighbors(item)) {
                if (userData.containsKey(nbr.getId())) {
                    neighbors.add(nbr);
                    if (neighbors.size() >= neighborhoodSize) {
                        break;
                    }
                }
            }

            // compute score & place in vector
            ScoredId score = null;

            if (neighbors.size() >= minNeighbors) {
                score = scorer.score(item, neighbors, userData);
            }

            if (score != null) {
                scores.set(e, score.getScore());
                // FIXME Scorers should not need to do this.
                for (TypedSymbol sym: score.getChannelSymbols()) {
                    scores.getOrAddChannel(sym).put(e.getKey(), score.getChannelValue(sym));
                }
            }

            sizeChannel.set(e, neighbors.size());
        }
    }

    private static class VectorKeyPredicate implements Predicate<ScoredId> {
        private final SparseVector vector;

        public VectorKeyPredicate(SparseVector v) {
            vector = v;
        }
        @Override
        public boolean apply(@Nullable ScoredId input) {
            return input != null && vector.containsKey(input.getId());
        }
    }
}

@@ -1031,49 +1031,8 @@
 m;%0A%0A
-import com.google.common.base.Predicate;%0A
 impo
@@ -1067,16 +1067,16 @@
 .Lists;%0A
+
 import o
@@ -1541,42 +1541,8 @@
 y;%0A%0A
-import javax.annotation.Nullable;%0A
 impo
@@ -2446,79 +2446,8 @@
 ) %7B%0A
-        Predicate%3CScoredId%3E usable = new VectorKeyPredicate(userData);%0A
     
@@ -3067,32 +3067,56 @@
             if (
+neighborhoodSize %3E 0 && 
 neighbors.size()
@@ -3768,32 +3768,32 @@
 %0A            %7D%0A%0A
+
             size
@@ -3845,377 +3845,7 @@
    %7D
-%0A%0A    private static class VectorKeyPredicate implements Predicate%3CScoredId%3E %7B%0A        private final SparseVector vector;%0A%0A        public VectorKeyPredicate(SparseVector v) %7B%0A            vector = v;%0A        %7D%0A        @Override%0A        public boolean apply(@Nullable ScoredId input) %7B%0A            return input != null && vector.containsKey(input.getId());%0A        %7D%0A    %7D
 %0A%7D%0A

Fix neighborhood size in optimized processing