Example usage for com.google.common.collect Ordering leastOf

List of usage examples for com.google.common.collect Ordering leastOf

Introduction

In this page you can find the example usage for com.google.common.collect Ordering leastOf.

Prototype

public <E extends T> List<E> leastOf(Iterator<E> elements, int k) 

Source Link

Document

Returns the k least elements from the given iterator according to this ordering, in order from least to greatest.

Usage

From source file:com.google.gitiles.RefServlet.java

private static List<Map<String, Object>> getRefsSoyData(RefDatabase refdb, GitilesView view, String prefix,
        Ordering<Ref> ordering, @Nullable Ref headLeaf, int limit) throws IOException {
    Collection<Ref> refs = refdb.getRefs(prefix).values();
    refs = ordering.leastOf(refs, limit > 0 ? Ints.saturatedCast(limit + 1L) : refs.size());
    List<Map<String, Object>> result = Lists.newArrayListWithCapacity(refs.size());

    for (Ref ref : refs) {
        String name = ref.getName().substring(prefix.length());
        boolean needPrefix = !ref.getName().equals(refdb.getRef(name).getName());
        Map<String, Object> value = Maps.newHashMapWithExpectedSize(3);
        value.put("url", GitilesView.revision().copyFrom(view)
                .setRevision(Revision.unpeeled(needPrefix ? ref.getName() : name, ref.getObjectId())).toUrl());
        value.put("name", name);
        if (headLeaf != null) {
            value.put("isHead", headLeaf.equals(ref));
        }/*from www.  j  a v  a  2s  .co m*/
        result.add(value);
    }
    return result;
}

From source file:com.cloudera.oryx.ml.serving.als.MostSurprising.java

@GET
@Path("{userID}")
@Produces({ CSVMessageBodyWriter.TEXT_CSV, MediaType.APPLICATION_JSON })
public List<IDValue> get(@PathParam("userID") String userID,
        @DefaultValue("10") @QueryParam("howMany") int howMany,
        @DefaultValue("0") @QueryParam("offset") int offset) throws OryxServingException {

    check(howMany > 0, "howMany must be positive");
    check(offset >= 0, "offset must be nonnegative");

    ALSServingModel model = getALSServingModel();
    float[] userVector = model.getUserVector(userID);
    checkExists(userVector != null, userID);
    List<Pair<String, float[]>> knownItemVectors = model.getKnownItemVectorsForUser(userID);
    checkExists(knownItemVectors != null, userID);

    Iterable<Pair<String, Double>> idDots = Iterables.transform(knownItemVectors, new DotsFunction(userVector));

    Ordering<Pair<?, Double>> ordering = Ordering.from(PairComparators.<Double>bySecond());
    return toIDValueResponse(ordering.leastOf(idDots, howMany + offset), howMany, offset);
}

From source file:com.cloudera.oryx.app.serving.als.MostSurprising.java

@GET
@Path("{userID}")
@Produces({ MediaType.TEXT_PLAIN, CSVMessageBodyWriter.TEXT_CSV, MediaType.APPLICATION_JSON })
public List<IDValue> get(@PathParam("userID") String userID,
        @DefaultValue("10") @QueryParam("howMany") int howMany,
        @DefaultValue("0") @QueryParam("offset") int offset) throws OryxServingException {

    check(howMany > 0, "howMany must be positive");
    check(offset >= 0, "offset must be nonnegative");

    ALSServingModel model = getALSServingModel();
    float[] userVector = model.getUserVector(userID);
    checkExists(userVector != null, userID);
    List<Pair<String, float[]>> knownItemVectors = model.getKnownItemVectorsForUser(userID);
    checkExists(knownItemVectors != null, userID);

    Iterable<Pair<String, Double>> idDots = Iterables.transform(knownItemVectors, new DotsFunction(userVector));

    Ordering<Pair<?, Double>> ordering = Ordering.from(PairComparators.<Double>bySecond());
    return toIDValueResponse(ordering.leastOf(idDots, howMany + offset), howMany, offset);
}

From source file:org.grouplens.samantha.server.ranker.EntityFieldRanker.java

public RankedResult rank(RetrievedResult retrievedResult, RequestContext requestContext) {
    List<ObjectNode> entityList = retrievedResult.getEntityList();
    int curLimit = limit;
    if (pageSize == 0 || limit > entityList.size()) {
        curLimit = entityList.size();/*from   ww  w .j a  v  a 2 s .c  o m*/
    }
    List<Prediction> scoredList = new ArrayList<>(entityList.size());
    for (ObjectNode entity : entityList) {
        scoredList.add(new Prediction(entity, null, 0.0));
    }
    List<Prediction> candidates;
    if (whetherOrder) {
        Ordering<Prediction> ordering = RankerUtilities.scoredResultFieldOrdering(orderField);
        if (ascending) {
            candidates = ordering.leastOf(scoredList, offset + curLimit);
        } else {
            candidates = ordering.greatestOf(scoredList, offset + curLimit);
        }
    } else {
        candidates = scoredList;
    }
    List<Prediction> recs;
    if (offset >= candidates.size()) {
        recs = new ArrayList<>();
    } else {
        recs = candidates.subList(offset, curLimit);
    }
    return new RankedResult(recs, offset, curLimit, retrievedResult.getMaxHits());
}

From source file:org.grouplens.samantha.modeler.knn.FeatureKnnModel.java

private List<double[]> getNeighbors(int curIndex, IntList svdIndices, SVDFeature svdFeature) {
    List<double[]> raw = new ArrayList<>(svdIndices.size());
    for (int target : svdIndices) {
        if (target != curIndex) {
            double[] pair = new double[2];
            pair[0] = target;/*  w  ww .  j a v  a  2  s  .c o m*/
            pair[1] = svdFeature.getVectorVarByNameIndex(SVDFeatureKey.FACTORS.get(), target)
                    .cosine(svdFeature.getVectorVarByNameIndex(SVDFeatureKey.FACTORS.get(), curIndex));
            raw.add(pair);
        }
    }
    Ordering<double[]> pairDoubleOrdering = SortingUtilities.pairDoubleSecondOrdering();
    List<double[]> neighbors;
    if (reverse) {
        neighbors = pairDoubleOrdering.leastOf(raw, numNeighbors);
    } else {
        neighbors = pairDoubleOrdering.greatestOf(raw, numNeighbors);
    }
    return neighbors;
}

From source file:pp1.KNNPositioner.java

@Override
public List<PositioningError> getPositions(List<TraceEntry> offline, List<TraceEntry> online,
        Distancer distancer) {/*from w  w  w .ja  v a  2s. c  o  m*/
    List<PositioningError> results = new ArrayList<>();

    /*online.stream().forEach((trace) -> {
     List<GeoPosition> bestTargets = offline.stream()
     .sorted((TraceEntry t1, TraceEntry t2) -> distancer.compareByDistance(t1, t2, trace))
     .limit(k).map(TraceEntry::getGeoPosition).collect(Collectors.toList());
     results.add(new PositioningError(trace.getGeoPosition(), Statistics.avgPosition(bestTargets) ));
     });*/ //Soooooo sloooow
    online.stream().forEach((TraceEntry trace) -> {
        //define ordering of TraceEntries by distance
        Ordering<TraceEntry> O = new Ordering<TraceEntry>() {
            public int compare(TraceEntry t1, TraceEntry t2) {
                return distancer.compareByDistance(t1, t2, trace);
            }
        };

        //find closest TraceEntries as a stream
        Stream<TraceEntry> leastDistanceTraceEntryStream = O.leastOf(offline, k).stream();
        //convert result of stream to a list of GeoPositions
        List<GeoPosition> leastDistancePositionsList = leastDistanceTraceEntryStream
                .map(TraceEntry::getGeoPosition).collect(Collectors.toList());
        //find average position
        GeoPosition avgPosition = Statistics.avgPosition(leastDistancePositionsList);
        //add to resultset
        results.add(new PositioningError(trace.getGeoPosition(), avgPosition));
    });

    return results;
}

From source file:msi.gama.metamodel.topology.CompoundSpatialIndex.java

private Collection<IAgent> firstAtDistance(final IScope scope, final IShape source, final IAgentFilter filter,
        int number, Collection<IAgent> alreadyChosen) {
    if (disposed) {
        return null;
    }/*  w w w.j a  v a 2s.c  o m*/
    final List<IAgent> shapes = new ArrayList<>(alreadyChosen);
    for (int i = 0; i < steps.length; i++) {
        for (final ISpatialIndex si : getAllSpatialIndexes()) {
            final Collection<IAgent> firsts = si.firstAtDistance(scope, source, steps[i], filter, number,
                    shapes);
            shapes.addAll(firsts);
        }
        if (shapes.size() >= number) {
            break;
        }
    }

    if (shapes.size() <= number)
        return shapes;
    scope.getRandom().shuffle(shapes);
    final Ordering<IShape> ordering = Ordering.natural().onResultOf(input -> source.euclidianDistanceTo(input));
    return ordering.leastOf(shapes, number);
}

From source file:msi.gama.metamodel.topology.GamaQuadTree.java

@Override
public Collection<IAgent> firstAtDistance(final IScope scope, final IShape source, final double dist,
        final IAgentFilter f, final int number, Collection<IAgent> alreadyChosen) {
    final double exp = dist * Maths.SQRT2;
    final Envelope3D env = new Envelope3D(source.getEnvelope());
    env.expandBy(exp);//  w  w  w. ja  v  a2  s  . c  o m
    final Collection<IAgent> in_square = findIntersects(scope, source, env, f);
    in_square.removeAll(alreadyChosen);
    if (in_square.isEmpty()) {
        return GamaListFactory.create();
    }

    if (in_square.size() <= number)
        return in_square;
    final Ordering<IShape> ordering = Ordering.natural().onResultOf(input -> source.euclidianDistanceTo(input));
    return ordering.leastOf(in_square, number);
}

From source file:msi.gama.metamodel.topology.AbstractTopology.java

@Override
public Collection<IAgent> getAgentClosestTo(final IScope scope, final IShape source, final IAgentFilter filter,
        final int number) {
    insertAgents(scope, filter);/*from w  ww  .j a va2  s.c o m*/
    if (!isTorus()) {
        return getSpatialIndex().firstAtDistance(scope, source, 0, filter, number, GamaListFactory.create());
    }
    final Geometry g0 = returnToroidalGeom(source.getGeometry());
    final Map<Geometry, IAgent> agents = getTororoidalAgents(scope, filter);
    agents.remove(g0);
    if (agents.keySet().size() <= number)
        return agents.values();
    List<Geometry> ggs = new ArrayList<>(agents.keySet());
    scope.getRandom().shuffle(ggs);
    final Ordering<Geometry> ordering = Ordering.natural().onResultOf(input -> g0.distance(input));
    IList<IAgent> shapes = GamaListFactory.create(Types.AGENT);
    for (Geometry g : ordering.leastOf(ggs, number)) {
        shapes.add(agents.get(g));
    }
    return shapes;
}

From source file:msi.gama.metamodel.topology.graph.GraphTopology.java

@Override
public Collection<IAgent> getAgentClosestTo(final IScope scope, final IShape source, final IAgentFilter filter,
        final int number) {
    // A better solution is required !!! this solution is just here to
    // ensure the consistency of the closest operator on graph !

    List<IAgent> listAgents = new ArrayList();
    listAgents.addAll(filter.getAgents(scope).listValue(scope, Types.AGENT, false));

    listAgents.remove(source);//from  ww  w .  ja v  a 2  s .  c o  m
    if (listAgents.size() <= number)
        return GamaListFactory.createWithoutCasting(Types.AGENT, listAgents);
    scope.getRandom().shuffle(listAgents);
    final Ordering<IAgent> ordering = Ordering.natural()
            .onResultOf(input -> distanceBetween(scope, source, input));
    return GamaListFactory.createWithoutCasting(Types.AGENT, ordering.leastOf(listAgents, number));

}