Example usage for com.google.common.base Functions forMap

List of usage examples for com.google.common.base Functions forMap

Introduction

In this page you can find the example usage for com.google.common.base Functions forMap.

Prototype

public static <K, V> Function<K, V> forMap(Map<K, V> map) 

Source Link

Document

Returns a function which performs a map lookup.

Usage

From source file:org.eclipse.recommenders.jayes.transformation.LatentDeterministicDecomposition.java

private List<double[]> getBest(final Map<double[], Integer> counts, int basisSize, int minTotalCounts) {
    PriorityQueue<double[]> q = new PriorityQueue<double[]>(basisSize,
            Ordering.natural().onResultOf(Functions.forMap(counts)));

    for (Entry<double[], Integer> e : counts.entrySet()) {
        if (q.isEmpty() || q.size() < basisSize) {
            q.add(e.getKey());//from w w  w  .  j a v  a 2 s . c  o  m
        } else {
            double[] head = q.peek();
            if (counts.get(head) < counts.get(e.getKey())) {
                q.remove();
                q.add(e.getKey());
            }
        }
    }

    int totalcounts = 0;
    for (double[] v : q) {
        totalcounts += counts.get(v);
    }
    if (totalcounts < minTotalCounts)
        return null;

    return new ArrayList<double[]>(q);
}

From source file:com.facebook.buck.core.cell.AbstractCellConfig.java

/**
 * Translates the 'cell name'->override map into a 'Path'->override map.
 *
 * @param pathMapping a map containing paths to all of the cells we want to query.
 * @return 'Path'->override map// w ww . ja  v a2  s. c  om
 */
public ImmutableMap<Path, RawConfig> getOverridesByPath(ImmutableMap<CellName, Path> pathMapping)
        throws InvalidCellOverrideException {

    ImmutableSet<CellName> relativeNamesOfCellsWithOverrides = FluentIterable.from(getValues().keySet())
            .filter(Predicates.not(CellName.ALL_CELLS_SPECIAL_NAME::equals)).toSet();
    ImmutableSet.Builder<Path> pathsWithOverrides = ImmutableSet.builder();
    for (CellName cellWithOverride : relativeNamesOfCellsWithOverrides) {
        if (!pathMapping.containsKey(cellWithOverride)) {
            throw new InvalidCellOverrideException(
                    String.format("Trying to override settings for unknown cell %s", cellWithOverride));
        }
        pathsWithOverrides.add(pathMapping.get(cellWithOverride));
    }

    ImmutableMultimap<Path, CellName> pathToRelativeName = Multimaps.index(pathMapping.keySet(),
            Functions.forMap(pathMapping));

    for (Path pathWithOverrides : pathsWithOverrides.build()) {
        ImmutableList<CellName> namesForPath = RichStream.from(pathToRelativeName.get(pathWithOverrides))
                .filter(name -> name.getLegacyName().isPresent()).toImmutableList();
        if (namesForPath.size() > 1) {
            throw new InvalidCellOverrideException(
                    String.format("Configuration override is ambiguous: cell rooted at %s is reachable "
                            + "as [%s]. Please override the config by placing a .buckconfig.local file in the "
                            + "cell's root folder.", pathWithOverrides, Joiner.on(',').join(namesForPath)));
        }
    }

    Map<Path, RawConfig> overridesByPath = new HashMap<>();
    for (Map.Entry<CellName, Path> entry : pathMapping.entrySet()) {
        CellName cellRelativeName = entry.getKey();
        Path cellPath = entry.getValue();
        RawConfig configFromOtherRelativeName = overridesByPath.get(cellPath);
        RawConfig config = getForCell(cellRelativeName);
        if (configFromOtherRelativeName != null) {
            // Merge configs
            RawConfig mergedConfig = RawConfig.builder().putAll(configFromOtherRelativeName).putAll(config)
                    .build();
            overridesByPath.put(cellPath, mergedConfig);
        } else {
            overridesByPath.put(cellPath, config);
        }
    }

    return ImmutableMap.copyOf(overridesByPath);
}

From source file:edu.isi.karma.reserach.alignment.WeightTuning.java

public void updateWeights(List<SortableSemanticModel_Old> rankedSemanticModels, SemanticModel correctModel) {

    if (rankedSemanticModels == null || rankedSemanticModels.isEmpty())
        return;/* w  w w . j av  a 2 s. c om*/

    for (SortableSemanticModel_Old sm : rankedSemanticModels)
        System.out.println(sm.getId());

    HashMap<SortableSemanticModel_Old, Integer> modelRanking = new HashMap<SortableSemanticModel_Old, Integer>();

    for (int i = 0; i < rankedSemanticModels.size(); i++) {
        modelRanking.put(rankedSemanticModels.get(i), i + 1);
    }

    HashMap<SortableSemanticModel_Old, Double> modelDistance = new HashMap<SortableSemanticModel_Old, Double>();

    double distance = 0.0;
    for (SortableSemanticModel_Old sm : rankedSemanticModels) {
        distance = correctModel.evaluate(sm).getDistance();
        modelDistance.put(sm, distance);
    }

    //      Ordering<SortableSemanticModel> orderingByDistance = Ordering.natural().nullsLast().onResultOf(Functions.forMap(modelDistance));

    // To prevent duplicate keys - having two entries equal according to comparator function
    Ordering<SortableSemanticModel_Old> orderingByDistance = Ordering.natural().nullsLast()
            .onResultOf(Functions.forMap(modelDistance))
            .compound(Ordering.natural().nullsLast().onResultOf(Functions.forMap(modelRanking)))
            .compound(Ordering.natural());
    ;

    //      Ordering<Map.Entry<SortableSemanticModel, Double>> orderingByDistance = Ordering.natural().nullsLast().onResultOf(
    //            new Function<Map.Entry<SortableSemanticModel, Double>, Double>() {
    //               public Double apply(Entry<SortableSemanticModel, Double> entry) {
    //                  return entry.getValue();
    //          }

    Map<SortableSemanticModel_Old, Double> map = ImmutableSortedMap.copyOf(modelDistance, orderingByDistance);

    SortableSemanticModel_Old closestModel = map.entrySet().iterator().next().getKey();
    if (modelRanking.get(closestModel) == 1) {
        logger.info("best model is already the first suggested one!");
        return;
    }

    // update the weights
    logger.info("updating the weights ...");

}

From source file:org.jclouds.byon.functions.NodesFromYamlStream.java

@Override
public LoadingCache<String, Node> apply(InputStream source) {

    Constructor constructor = new Constructor(Config.class);

    TypeDescription nodeDesc = new TypeDescription(YamlNode.class);
    nodeDesc.putListPropertyType("tags", String.class);
    constructor.addTypeDescription(nodeDesc);

    TypeDescription configDesc = new TypeDescription(Config.class);
    configDesc.putListPropertyType("nodes", YamlNode.class);
    constructor.addTypeDescription(configDesc);
    // note that snakeyaml also throws nosuchmethod error when you use the
    // non-deprecated
    // constructor
    Yaml yaml = new Yaml(new Loader(constructor));
    Config config = (Config) yaml.load(source);
    checkState(config != null, "missing config: class");
    checkState(config.nodes != null, "missing nodes: collection");

    Map<String, Node> backingMap = Maps.uniqueIndex(Iterables.transform(config.nodes, YamlNode.toNode),
            new Function<Node, String>() {
                public String apply(Node node) {
                    return node.getId();
                }//from   ww w .java2s.c  om
            });
    LoadingCache<String, Node> cache = CacheBuilder.newBuilder()
            .build(CacheLoader.from(Functions.forMap(backingMap)));
    for (String node : backingMap.keySet())
        cache.getUnchecked(node);
    return cache;
}

From source file:com.google.errorprone.refaster.UPlaceholderStatement.java

@Override
public Choice<UnifierWithUnconsumedStatements> apply(final UnifierWithUnconsumedStatements initState) {
    final PlaceholderUnificationVisitor visitor = PlaceholderUnificationVisitor
            .create(TreeMaker.instance(initState.unifier().getContext()), arguments());

    PlaceholderVerificationVisitor verification = new PlaceholderVerificationVisitor(
            Collections2.transform(placeholder().requiredParameters(), Functions.forMap(arguments())),
            arguments().values());/* ww  w  . j a v a2s .  c  o m*/

    // The choices where we might conceivably have a completed placeholder match.
    Choice<State<ConsumptionState>> realOptions = Choice.none();

    // The choice of consumption states to this point in the block. 
    Choice<State<ConsumptionState>> choiceToHere = Choice
            .of(State.create(List.<UVariableDecl>nil(), initState.unifier(), ConsumptionState.empty()));

    if (verification.allRequiredMatched()) {
        realOptions = choiceToHere.or(realOptions);
    }
    for (final StatementTree targetStatement : initState.unconsumedStatements()) {
        if (!verification.scan(targetStatement, initState.unifier())) {
            break; // we saw a variable that's not allowed to be referenced
        }
        // Consume another statement, or if that fails, fall back to the previous choices...
        choiceToHere = choiceToHere
                .thenChoose(new Function<State<ConsumptionState>, Choice<State<ConsumptionState>>>() {
                    @Override
                    public Choice<State<ConsumptionState>> apply(
                            final State<ConsumptionState> consumptionState) {
                        return visitor.unifyStatement(targetStatement, consumptionState).transform(
                                new Function<State<? extends JCStatement>, State<ConsumptionState>>() {
                                    @Override
                                    public State<ConsumptionState> apply(
                                            State<? extends JCStatement> stmtState) {
                                        return stmtState.withResult(
                                                consumptionState.result().consume(stmtState.result()));
                                    }
                                });
                    }
                });
        if (verification.allRequiredMatched()) {
            realOptions = choiceToHere.or(realOptions);
        }
    }
    return realOptions
            .thenOption(new Function<State<ConsumptionState>, Optional<UnifierWithUnconsumedStatements>>() {
                @Override
                public Optional<UnifierWithUnconsumedStatements> apply(
                        State<ConsumptionState> consumptionState) {
                    if (ImmutableSet.copyOf(consumptionState.seenParameters())
                            .containsAll(placeholder().requiredParameters())) {
                        Unifier resultUnifier = consumptionState.unifier().fork();
                        int nConsumedStatements = consumptionState.result().consumedStatements();
                        java.util.List<? extends StatementTree> remainingStatements = initState
                                .unconsumedStatements()
                                .subList(nConsumedStatements, initState.unconsumedStatements().size());
                        UnifierWithUnconsumedStatements result = UnifierWithUnconsumedStatements
                                .create(resultUnifier, remainingStatements);
                        List<JCStatement> impl = consumptionState.result().placeholderImplInReverseOrder()
                                .reverse();
                        ControlFlowVisitor.Result implFlow = ControlFlowVisitor.INSTANCE.visitStatements(impl);
                        if (implFlow == implementationFlow()) {
                            List<JCStatement> prevBinding = resultUnifier.getBinding(placeholder().blockKey());
                            if (prevBinding != null && prevBinding.toString().equals(impl.toString())) {
                                return Optional.of(result);
                            } else if (prevBinding == null) {
                                resultUnifier.putBinding(placeholder().blockKey(), impl);
                                return Optional.of(result);
                            }
                        }
                    }
                    return Optional.absent();
                }
            });
}

From source file:com.facebook.buck.config.AbstractCellConfig.java

/**
 * Translates the 'cell name'->override map into a 'Path'->override map.
 * @param pathMapping a map containing paths to all of the cells we want to query.
 * @return 'Path'->override map//ww w.  ja  v  a  2  s . c om
 */
public ImmutableMap<Path, RawConfig> getOverridesByPath(ImmutableMap<RelativeCellName, Path> pathMapping)
        throws MalformedOverridesException {

    ImmutableSet<RelativeCellName> relativeNamesOfCellsWithOverrides = FluentIterable.from(getValues().keySet())
            .filter(Predicates.not(ALL_CELLS_OVERRIDE::equals)).toSet();
    ImmutableSet.Builder<Path> pathsWithOverrides = ImmutableSet.builder();
    for (RelativeCellName cellWithOverride : relativeNamesOfCellsWithOverrides) {
        if (!pathMapping.containsKey(cellWithOverride)) {
            throw new MalformedOverridesException(
                    String.format("Trying to override settings for unknown cell %s", cellWithOverride));
        }
        pathsWithOverrides.add(pathMapping.get(cellWithOverride));
    }

    ImmutableMultimap<Path, RelativeCellName> pathToRelativeName = Multimaps.index(pathMapping.keySet(),
            Functions.forMap(pathMapping));

    for (Path pathWithOverrides : pathsWithOverrides.build()) {
        ImmutableCollection<RelativeCellName> namesForPath = pathToRelativeName.get(pathWithOverrides);
        if (namesForPath.size() > 1) {
            throw new MalformedOverridesException(
                    String.format("Configuration override is ambiguous: cell rooted at %s is reachable "
                            + "as [%s]. Please override the config by placing a .buckconfig.local file in the "
                            + "cell's root folder.", pathWithOverrides, Joiner.on(',').join(namesForPath)));
        }
    }

    Map<Path, RawConfig> overridesByPath = new HashMap<>();
    for (Map.Entry<RelativeCellName, Path> entry : pathMapping.entrySet()) {
        RelativeCellName cellRelativeName = entry.getKey();
        Path cellPath = entry.getValue();
        RawConfig configFromOtherRelativeName = overridesByPath.get(cellPath);
        RawConfig config = getForCell(cellRelativeName);
        if (configFromOtherRelativeName != null) {
            Preconditions.checkState(configFromOtherRelativeName.equals(config),
                    "Attempting to create cell %s at %s with conflicting overrides [%s] vs [%s].",
                    cellRelativeName, cellPath, configFromOtherRelativeName, config);
        } else {
            overridesByPath.put(cellPath, config);
        }
    }

    return ImmutableMap.copyOf(overridesByPath);
}

From source file:org.grouplens.grapht.graph.MergePool.java

/**
 * Merge and simplify a graph.  This will coalesce redundant nodes (equivalent labels and
 * outgoing edge destinations), and will prefer to use nodes from graphs seen previously.
 * This allows deduplication across multiple graphs.
 *
 * <p><strong>Noteo:</strong> edge labels are ignored for the purpose of merging.</p>
 *
 * @param graph The graph to simplify./*from w  w  w.  j  a  va2  s .  c o m*/
 * @return The new simplified, merged graph.
 */
public DAGNode<V, E> merge(DAGNode<V, E> graph) {
    List<DAGNode<V, E>> sorted = graph.getSortedNodes();

    Map<Pair<V, Set<DAGNode<V, E>>>, DAGNode<V, E>> nodeTable = Maps.newHashMap();
    for (DAGNode<V, E> node : pool) {
        Pair<V, Set<DAGNode<V, E>>> key = Pair.of(node.getLabel(), node.getAdjacentNodes());
        assert !nodeTable.containsKey(key);
        nodeTable.put(key, node);
    }

    // We want to map nodes to their previous merged versions
    Map<DAGNode<V, E>, DAGNode<V, E>> mergedMap = Maps.newHashMap();
    // Now start processing nodes
    for (DAGNode<V, E> toMerge : sorted) {
        V sat = toMerge.getLabel();
        // Resolve the merged neighbors of this node.  They have already been
        // merged, since we are going in topological order.
        Set<DAGNode<V, E>> neighbors = FluentIterable.from(toMerge.getOutgoingEdges())
                .transform(DAGEdge.<V, E>extractTail()).transform(Functions.forMap(mergedMap)).toSet();

        // See if we have already created an equivalent to this node
        DAGNode<V, E> newNode = nodeTable.get(Pair.of(sat, neighbors));
        if (newNode == null) {
            // No, let's start building one
            DAGNodeBuilder<V, E> bld = DAGNode.newBuilder();

            boolean changed = false;
            bld.setLabel(sat);
            logger.debug("Adding new node to merged graph for satisfaction: {}", sat);

            for (DAGEdge<V, E> edge : toMerge.getOutgoingEdges()) {
                // create a new edge with the merged tail and same label
                DAGNode<V, E> filtered = mergedMap.get(edge.getTail());
                bld.addEdge(filtered, edge.getLabel());
                // have we made a change to this node?
                changed |= !filtered.equals(edge.getTail());
            }

            if (changed) {
                // one of the node's neighbors has been replaced with merged version
                // so use the new node
                newNode = bld.build();
            } else {
                // no edges were changed, leave the node unmodified
                newNode = toMerge;
            }
            nodeTable.put(Pair.of(sat, neighbors), newNode);
        } else {
            logger.debug("Node already in merged graph for satisfaction: {}", toMerge.getLabel());
        }

        // update merge map so future equivalent nodes get replaced with this one
        mergedMap.put(toMerge, newNode);
    }

    // now let's find our return value - what did we merge the graph root to?
    DAGNode<V, E> newRoot = mergedMap.get(graph);
    // remember all its nodes for future merge operations
    pool.addAll(newRoot.getReachableNodes());
    // and we're done
    return newRoot;
}

From source file:org.apache.ctakes.relationextractor.ae.IdentifiedAnnotationExpander.java

public static String getEnclosingNP(JCas jCas, IdentifiedAnnotation identifiedAnnotation) {

    // map each covering treebank node to its character length
    Map<TreebankNode, Integer> treebankNodeSizes = new HashMap<TreebankNode, Integer>();
    for (TreebankNode treebankNode : JCasUtil.selectCovering(jCas, TreebankNode.class,
            identifiedAnnotation.getBegin(), identifiedAnnotation.getEnd())) {

        // only expand nouns (and not verbs or adjectives)
        if (treebankNode instanceof TerminalTreebankNode) {
            if (!treebankNode.getNodeType().startsWith("N")) {
                return identifiedAnnotation.getCoveredText();
            }/*w ww  .j  av  a  2  s. c  o  m*/
        }

        // because only nouns are expanded, look for covering NPs
        if (treebankNode.getNodeType().equals("NP")) {
            treebankNodeSizes.put(treebankNode, treebankNode.getCoveredText().length());
        }
    }

    // find the shortest covering treebank node
    List<TreebankNode> sortedTreebankNodes = new ArrayList<TreebankNode>(treebankNodeSizes.keySet());
    Function<TreebankNode, Integer> getValue = Functions.forMap(treebankNodeSizes);
    Collections.sort(sortedTreebankNodes, Ordering.natural().onResultOf(getValue));

    if (sortedTreebankNodes.size() > 0) {
        return sortedTreebankNodes.get(0).getCoveredText();
    }

    return identifiedAnnotation.getCoveredText();
}

From source file:edu.uci.ics.jung.algorithms.transformation.VertexPartitionCollapser.java

/**
 * @return a Function from vertex sets in the original graph to collapsed vertices
 * in the transformed graph./*from  w w  w .  j  a v a2 s .  co m*/
 */
public Function<Set<V>, CV> getSetToCollapsedVertexTransformer() {
    return Functions.forMap(set_collapsedv);
}

From source file:org.apache.ctakes.relationextractor.ae.baselines.Baseline3DegreeOfRelationExtractorAnnotator.java

private static EntityMention getNearestEntity(JCas jCas, Modifier modifier,
        List<EntityMention> entityMentions) {

    // token distance from modifier to other entity mentions
    Map<EntityMention, Integer> distanceToEntities = new HashMap<EntityMention, Integer>();

    for (EntityMention entityMention : entityMentions) {
        List<BaseToken> baseTokens = JCasUtil.selectBetween(jCas, BaseToken.class, modifier, entityMention);
        distanceToEntities.put(entityMention, baseTokens.size());
    }//from  ww  w .ja v a 2 s .co m

    List<EntityMention> sortedEntityMentions = new ArrayList<EntityMention>(distanceToEntities.keySet());
    Function<EntityMention, Integer> getValue = Functions.forMap(distanceToEntities);
    Collections.sort(sortedEntityMentions, Ordering.natural().onResultOf(getValue));

    return sortedEntityMentions.get(0);
}