Example usage for org.apache.mahout.cf.taste.common NoSuchUserException NoSuchUserException

List of usage examples for org.apache.mahout.cf.taste.common NoSuchUserException NoSuchUserException

Introduction

In this page you can find the example usage for org.apache.mahout.cf.taste.common NoSuchUserException NoSuchUserException.

Prototype

public NoSuchUserException(String message) 

Source Link

Usage

From source file:net.myrrix.client.ClientRecommender.java

License:Apache License

/**
 * @param userID user for which recommendations are to be computed
 * @param howMany desired number of recommendations
 * @param considerKnownItems if true, items that the user is already associated to are candidates
 *  for recommendation. Normally this is {@code false}.
 * @param rescorerParams optional parameters to send to the server's {@code RescorerProvider}
 * @return {@link List} of recommended {@link RecommendedItem}s, ordered from most strongly recommend to least
 * @throws NoSuchUserException if the user is not known in the model
 * @throws NotReadyException if the recommender has no model available yet
 * @throws TasteException if another error occurs
 * @throws UnsupportedOperationException if rescorer is not null
 *///from w  w  w  .j a  v  a  2 s  . c  o m
public List<RecommendedItem> recommend(long userID, int howMany, boolean considerKnownItems,
        String[] rescorerParams) throws TasteException {

    StringBuilder urlPath = new StringBuilder();
    urlPath.append("/recommend/");
    urlPath.append(userID);
    appendCommonQueryParams(howMany, considerKnownItems, rescorerParams, urlPath);

    TasteException savedException = null;
    for (HostAndPort replica : choosePartitionAndReplicas(userID)) {
        HttpURLConnection connection = null;
        try {
            connection = buildConnectionToReplica(replica, urlPath.toString(), "GET");
            switch (connection.getResponseCode()) {
            case HttpURLConnection.HTTP_OK:
                return consumeItems(connection);
            case HttpURLConnection.HTTP_NOT_FOUND:
                throw new NoSuchUserException(userID);
            case HttpURLConnection.HTTP_UNAVAILABLE:
                throw new NotReadyException();
            default:
                throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage());
            }
        } catch (TasteException te) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString());
            savedException = te;
        } catch (IOException ioe) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString());
            savedException = new TasteException(ioe);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    throw savedException;
}

From source file:net.myrrix.client.ClientRecommender.java

License:Apache License

/**
 * @param userIDs users for which recommendations are to be computed
 * @param howMany desired number of recommendations
 * @param considerKnownItems if true, items that the user is already associated to are candidates
 *  for recommendation. Normally this is {@code false}.
 * @param rescorerParams optional parameters to send to the server's {@code RescorerProvider}
 * @return {@link List} of recommended {@link RecommendedItem}s, ordered from most strongly recommend to least
 * @throws NoSuchUserException if <em>none</em> of {@code userIDs} are known in the model. Otherwise unknown
 *  user IDs are ignored.//from   ww w .ja  va2 s .c o  m
 * @throws NotReadyException if the recommender has no model available yet
 * @throws TasteException if another error occurs
 * @throws UnsupportedOperationException if rescorer is not null
 */
public List<RecommendedItem> recommendToMany(long[] userIDs, int howMany, boolean considerKnownItems,
        String[] rescorerParams) throws TasteException {

    StringBuilder urlPath = new StringBuilder(32);
    urlPath.append("/recommendToMany");
    for (long userID : userIDs) {
        urlPath.append('/').append(userID);
    }
    appendCommonQueryParams(howMany, considerKnownItems, rescorerParams, urlPath);

    // Note that this assumes that all user IDs are on the same partition. It will fail at request
    // time if not since the partition of the first user doesn't contain the others.
    TasteException savedException = null;
    for (HostAndPort replica : choosePartitionAndReplicas(userIDs[0])) {
        HttpURLConnection connection = null;
        try {
            connection = buildConnectionToReplica(replica, urlPath.toString(), "GET");
            switch (connection.getResponseCode()) {
            case HttpURLConnection.HTTP_OK:
                return consumeItems(connection);
            case HttpURLConnection.HTTP_NOT_FOUND:
                throw new NoSuchUserException(Arrays.toString(userIDs));
            case HttpURLConnection.HTTP_UNAVAILABLE:
                throw new NotReadyException();
            default:
                throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage());
            }
        } catch (TasteException te) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString());
            savedException = te;
        } catch (IOException ioe) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString());
            savedException = new TasteException(ioe);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    throw savedException;
}

From source file:net.myrrix.client.ClientRecommender.java

License:Apache License

/**
 * <p>Lists the items that were most influential in recommending a given item to a given user. Exactly how this
 * is determined is left to the implementation, but, generally this will return items that the user prefers
 * and that are similar to the given item.</p>
 *
 * <p>These values by which the results are ordered are opaque values and have no interpretation
 * other than that larger means stronger.</p>
 *
 * @param userID ID of user who was recommended the item
 * @param itemID ID of item that was recommended
 * @param howMany maximum number of items to return
 * @return {@link List} of {@link RecommendedItem}, ordered from most influential in recommended the given
 *  item to least/*from   w  w w.ja  v  a2  s.  c o  m*/
 * @throws NoSuchUserException if the user is not known in the model
 * @throws NoSuchItemException if the item is not known in the model
 * @throws NotReadyException if the recommender has no model available yet
 * @throws TasteException if another error occurs
 */
@Override
public List<RecommendedItem> recommendedBecause(long userID, long itemID, int howMany) throws TasteException {
    String urlPath = "/because/" + userID + '/' + itemID + "?howMany=" + howMany;

    TasteException savedException = null;
    for (HostAndPort replica : choosePartitionAndReplicas(userID)) {
        HttpURLConnection connection = null;
        try {
            connection = buildConnectionToReplica(replica, urlPath, "GET");
            switch (connection.getResponseCode()) {
            case HttpURLConnection.HTTP_OK:
                return consumeItems(connection);
            case HttpURLConnection.HTTP_NOT_FOUND:
                String connectionMessage = connection.getResponseMessage();
                if (connectionMessage != null
                        && connectionMessage.contains(NoSuchUserException.class.getSimpleName())) {
                    throw new NoSuchUserException(userID);
                } else {
                    throw new NoSuchItemException(itemID);
                }
            case HttpURLConnection.HTTP_UNAVAILABLE:
                throw new NotReadyException();
            default:
                throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage());
            }
        } catch (TasteException te) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString());
            savedException = te;
        } catch (IOException ioe) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString());
            savedException = new TasteException(ioe);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    throw savedException;
}

From source file:net.myrrix.online.ServerRecommender.java

License:Apache License

@Override
public List<RecommendedItem> recommendToMany(long[] userIDs, int howMany, boolean considerKnownItems,
        IDRescorer rescorer) throws NoSuchUserException, NotReadyException {

    Preconditions.checkArgument(howMany > 0, "howMany must be positive");

    Generation generation = getCurrentGeneration();
    FastByIDMap<float[]> X = generation.getX();

    Lock xLock = generation.getXLock().readLock();
    List<float[]> userFeatures = Lists.newArrayListWithCapacity(userIDs.length);
    xLock.lock();//from www . j ava2s  .co  m
    try {
        for (long userID : userIDs) {
            float[] theUserFeatures = X.get(userID);
            if (theUserFeatures != null) {
                userFeatures.add(theUserFeatures);
            }
        }
    } finally {
        xLock.unlock();
    }
    if (userFeatures.isEmpty()) {
        throw new NoSuchUserException(Arrays.toString(userIDs));
    }

    FastByIDMap<FastIDSet> knownItemIDs = generation.getKnownItemIDs();
    if (knownItemIDs == null && !considerKnownItems) {
        throw new UnsupportedOperationException("Can't ignore known items because no known items available");
    }
    FastIDSet usersKnownItemIDs = null;
    if (!considerKnownItems) {
        Lock knownItemLock = generation.getKnownItemLock().readLock();
        knownItemLock.lock();
        try {
            for (long userID : userIDs) {
                FastIDSet theKnownItemIDs = knownItemIDs.get(userID);
                if (theKnownItemIDs == null) {
                    continue;
                }
                if (usersKnownItemIDs == null) {
                    usersKnownItemIDs = theKnownItemIDs;
                } else {
                    LongPrimitiveIterator it = usersKnownItemIDs.iterator();
                    while (it.hasNext()) {
                        if (!theKnownItemIDs.contains(it.nextLong())) {
                            it.remove();
                        }
                    }
                }
                if (usersKnownItemIDs.isEmpty()) {
                    break;
                }
            }
        } finally {
            knownItemLock.unlock();
        }
    }

    float[][] userFeaturesArray = userFeatures.toArray(new float[userFeatures.size()][]);
    Lock yLock = generation.getYLock().readLock();
    yLock.lock();
    try {
        return multithreadedTopN(userFeaturesArray, usersKnownItemIDs, generation.getUserTagIDs(), rescorer,
                howMany, generation.getCandidateFilter());
    } finally {
        yLock.unlock();
    }

}

From source file:net.myrrix.online.ServerRecommender.java

License:Apache License

/**
 * <p>Lists the items that were most influential in recommending a given item to a given user. Exactly how this
 * is determined is left to the implementation, but, generally this will return items that the user prefers
 * and that are similar to the given item.</p>
 *
 * <p>These values by which the results are ordered are opaque values and have no interpretation
 * other than that larger means stronger.</p>
 *
 * @param userID ID of user who was recommended the item
 * @param itemID ID of item that was recommended
 * @param howMany maximum number of items to return
 * @return {@link List} of {@link RecommendedItem}, ordered from most influential in recommended the given
 *  item to least/*from   ww w  . ja v  a 2  s.  co  m*/
 * @throws NoSuchUserException if the user is not known in the model
 * @throws NoSuchItemException if the item is not known in the model
 * @throws NotReadyException if the recommender has no model available yet
 */
@Override
public List<RecommendedItem> recommendedBecause(long userID, long itemID, int howMany)
        throws NoSuchUserException, NoSuchItemException, NotReadyException {

    Preconditions.checkArgument(howMany > 0, "howMany must be positive");

    Generation generation = getCurrentGeneration();
    FastByIDMap<FastIDSet> knownItemIDs = generation.getKnownItemIDs();
    if (knownItemIDs == null) {
        throw new UnsupportedOperationException("No known item IDs available");
    }

    Lock knownItemLock = generation.getKnownItemLock().readLock();
    FastIDSet userKnownItemIDs;
    knownItemLock.lock();
    try {
        userKnownItemIDs = knownItemIDs.get(userID);
    } finally {
        knownItemLock.unlock();
    }
    if (userKnownItemIDs == null) {
        throw new NoSuchUserException(userID);
    }

    FastByIDMap<float[]> Y = generation.getY();

    Lock yLock = generation.getYLock().readLock();
    yLock.lock();
    try {

        float[] features = Y.get(itemID);
        if (features == null) {
            throw new NoSuchItemException(itemID);
        }
        FastByIDMap<float[]> toFeatures;
        synchronized (userKnownItemIDs) {
            toFeatures = new FastByIDMap<float[]>(userKnownItemIDs.size(), 1.25f);
            LongPrimitiveIterator it = userKnownItemIDs.iterator();
            while (it.hasNext()) {
                long fromItemID = it.nextLong();
                float[] fromFeatures = Y.get(fromItemID);
                toFeatures.put(fromItemID, fromFeatures);
            }
        }

        return TopN.selectTopN(new RecommendedBecauseIterator(toFeatures.entrySet().iterator(),
                generation.getUserTagIDs(), features), howMany);
    } finally {
        yLock.unlock();
    }
}

From source file:org.easyrec.mahout.store.impl.MahoutDataModelMappingDAOMysqlImpl.java

License:Open Source License

@Override
public PreferenceArray getPreferencesFromUser(int tenantId, Date cutoffDate, long userID, int actionTypeId)
        throws TasteException {
    Object[] args = new Object[] { tenantId, cutoffDate, userID, actionTypeId };
    int[] argTypes = new int[] { Types.INTEGER, Types.TIMESTAMP, Types.INTEGER, Types.INTEGER };
    try {/*from  w w w .  ja  v a  2  s  .  com*/
        return new GenericUserPreferenceArray(getJdbcTemplate().query(getPreferencesFromUserQuery, args,
                argTypes, genericPreferenceRowMapper));
    } catch (EmptyResultDataAccessException e) {
        logger.warn("An error occurred!", e);
        throw new NoSuchUserException(userID);
    }
}

From source file:org.easyrec.mahout.store.impl.MahoutDataModelMappingDAOMysqlImpl.java

License:Open Source License

@Override
public PreferenceArray getBooleanPreferencesFromUser(int tenantId, Date cutoffDate, long userID,
        int actionTypeId) throws TasteException {
    Object[] args = new Object[] { tenantId, cutoffDate, userID, actionTypeId };
    int[] argTypes = new int[] { Types.INTEGER, Types.TIMESTAMP, Types.INTEGER, Types.INTEGER };
    try {//from w w w. ja  va 2 s  .c om
        return new GenericUserPreferenceArray(getJdbcTemplate().query(getPreferencesFromUserQuery, args,
                argTypes, genericBooleanPreferenceRowMapper));
    } catch (EmptyResultDataAccessException e) {
        logger.warn("An error occurred!", e);
        throw new NoSuchUserException(userID);
    }
}

From source file:org.easyrec.mahout.store.impl.MahoutDataModelMappingDAOMysqlImpl.java

License:Open Source License

@Override
public FastIDSet getItemIDsFromUser(int tenantId, Date cutoffDate, long userID, int actionTypeId)
        throws TasteException {
    Object[] args = new Object[] { tenantId, cutoffDate, userID, actionTypeId };
    int[] argTypes = new int[] { Types.INTEGER, Types.TIMESTAMP, Types.INTEGER, Types.INTEGER };

    try {//ww  w . ja  v  a  2 s.c  om
        return getJdbcTemplate().query(getItemIDsFromUserQuery, args, argTypes, fastIDSetExtractor);
    } catch (EmptyResultDataAccessException e) {
        logger.warn("An error occurred!", e);
        throw new NoSuchUserException(userID);
    }
}

From source file:org.zaizi.mahout.alfresco.datamodel.AlfrescoViewedDocumentDataModelImpl.java

License:Open Source License

public synchronized Long getPreferenceTime(long userID, long itemID) throws TasteException {
    if (timestamps == null) {
        return null;
    }//from ww  w .j  a v a 2s.c  o  m
    FastByIDMap<Long> itemTimestamps = timestamps.get(userID);
    if (itemTimestamps == null) {
        throw new NoSuchUserException(userID);
    }
    return itemTimestamps.get(itemID);
}