Example usage for com.google.common.collect SetMultimap get

List of usage examples for com.google.common.collect SetMultimap get

Introduction

In this page you can find the example usage for com.google.common.collect SetMultimap get.

Prototype

@Override
Set<V> get(@Nullable K key);

Source Link

Document

Because a SetMultimap has unique values for a given key, this method returns a Set , instead of the java.util.Collection specified in the Multimap interface.

Usage

From source file:org.onosproject.net.intent.impl.LinkCollectionIntentInstaller.java

private List<FlowRuleBatchOperation> generateBatchOperations(LinkCollectionIntent intent,
        FlowRuleOperation operation) {/*from   w  w w .  ja  v  a 2  s . c  om*/

    SetMultimap<DeviceId, PortNumber> outputPorts = HashMultimap.create();

    for (Link link : intent.links()) {
        outputPorts.put(link.src().deviceId(), link.src().port());
    }

    for (ConnectPoint egressPoint : intent.egressPoints()) {
        outputPorts.put(egressPoint.deviceId(), egressPoint.port());
    }

    FlowRuleBatchOperation batchOperation = new FlowRuleBatchOperation(outputPorts.keys().stream()
            .map(deviceId -> createBatchEntry(operation, intent, deviceId, outputPorts.get(deviceId)))
            .collect(Collectors.toList()));

    return Collections.singletonList(batchOperation);
}

From source file:edu.cmu.lti.oaqa.baseqa.answer.collective_score.scorers.EditDistanceCollectiveAnswerScorer.java

@SuppressWarnings("unchecked")
@Override//from w  w w .j  a  v  a2 s. c  o m
public void prepare(JCas jcas) {
    answers = TypeUtil.getRankedAnswers(jcas);
    distances = HashBasedTable.create();
    ImmutableSet<Answer> answerSet = ImmutableSet.copyOf(answers);
    SetMultimap<Answer, String> answer2names = HashMultimap.create();
    answers.forEach(answer -> TypeUtil.getCandidateAnswerVariantNames(answer).stream().map(String::toLowerCase)
            .forEach(name -> answer2names.put(answer, name)));
    for (List<Answer> pair : Sets.cartesianProduct(answerSet, answerSet)) {
        Answer answer1 = pair.get(0);
        Answer answer2 = pair.get(1);
        if (answer1.equals(answer2)) {
            distances.put(answer1, answer2, 1.0);
        } else {
            Sets.cartesianProduct(answer2names.get(answer1), answer2names.get(answer2)).stream()
                    .mapToDouble(namepair -> getDistance(namepair.get(0), namepair.get(1))).min()
                    .ifPresent(x -> distances.put(answer1, answer2, 1.0 - x));
        }
    }
}

From source file:com.continuuity.loom.scheduler.dag.TaskDag.java

@Override
public String toString() {
    StringBuilder output = new StringBuilder();
    Comparator<TaskNode> comparator = new TaskNodeComparator();
    TreeSet<TaskNode> nodes = Sets.newTreeSet(comparator);
    nodes.addAll(this.nodes);
    SetMultimap<TaskNode, TaskNode> edges = TreeMultimap.create(comparator, comparator);
    edges.putAll(this.edges);
    output.append("services:\n");
    for (TaskNode node : nodes) {
        output.append(node);/*w  w  w  . ja  v a 2  s .  com*/
        output.append("\n");
    }
    output.append("edges:\n");
    for (TaskNode startNode : edges.keySet()) {
        output.append("  ");
        output.append(startNode);
        output.append("\n");
        for (TaskNode endNode : edges.get(startNode)) {
            output.append("    -> ");
            output.append(endNode);
            output.append("\n");
        }
    }
    return output.toString();
}

From source file:com.google.devtools.cyclefinder.ReferenceGraph.java

/**
 * Runs a version of Dijkstra's algorithm to find a tight cycle in the given
 * strongly connected component./*from  w  w  w.  j a v  a  2  s  .  c  om*/
 */
private List<Edge> runDijkstras(SetMultimap<String, Edge> graph, String root) {
    Map<String, Edge> backlinks = Maps.newHashMap();
    Set<String> visited = Sets.newHashSet();
    List<String> toVisit = Lists.newArrayList(root);
    outer: while (true) {
        List<String> visitNext = Lists.newArrayList();
        for (String source : toVisit) {
            visited.add(source);
            for (Edge e : graph.get(source)) {
                String target = e.getTarget().getKey();
                if (!visited.contains(target)) {
                    visitNext.add(target);
                    backlinks.put(target, e);
                } else if (target.equals(root)) {
                    backlinks.put(root, e);
                    break outer;
                }
            }
        }
        toVisit = visitNext;
    }
    List<Edge> cycle = Lists.newArrayList();
    String curNode = root;
    while (!curNode.equals(root) || cycle.size() == 0) {
        Edge nextEdge = backlinks.get(curNode);
        cycle.add(nextEdge);
        curNode = nextEdge.getOrigin().getKey();
    }
    return Lists.newArrayList(Lists.reverse(cycle));
}

From source file:com.google.devtools.build.xcode.xcodegen.PBXBuildFiles.java

/**
 * Returns new or cached instances of PBXBuildFiles corresponding to files that may or may not
 * belong to an aggregate reference (see {@link AggregateReferenceType}). Files specified by the
 * {@code paths} argument are grouped into individual PBXBuildFiles using the given
 * {@link AggregateReferenceType}. Files that are standalone are not put in an aggregate
 * reference, but are put in a standalone PBXBuildFile in the returned sequence.
 */// w w w.  j a v  a2s .c  om
public Iterable<PBXBuildFile> get(AggregateReferenceType type, Iterable<Path> paths) {
    ImmutableList.Builder<PBXBuildFile> result = new ImmutableList.Builder<>();
    SetMultimap<AggregateKey, Path> keyedPaths = type.aggregates(paths);
    for (Map.Entry<AggregateKey, Collection<Path>> aggregation : keyedPaths.asMap().entrySet()) {
        if (!aggregation.getKey().isStandalone()) {
            ImmutableSet<Path> itemPaths = ImmutableSet.copyOf(aggregation.getValue());
            result.add(aggregateBuildFile(itemPaths,
                    type.create(aggregation.getKey(), fileReferences(itemPaths))));
        }
    }
    for (Path generalResource : keyedPaths.get(AggregateKey.standalone())) {
        result.add(getStandalone(FileReference.of(generalResource.toString(), SourceTree.GROUP)));
    }

    return result.build();
}

From source file:com.google.devtools.build.lib.query2.output.ConditionalEdges.java

/** Builds ConditionalEdges from given graph. */
public ConditionalEdges(Digraph<Target> graph) {
    this.map = new HashMap<>();

    for (Node<Target> node : graph.getNodes()) {
        Rule rule = node.getLabel().getAssociatedRule();
        if (rule == null) {
            // rule is null for source files and package groups. Skip them.
            continue;
        }/*from ww w  .ja v  a2 s.  com*/

        SetMultimap<Label, Label> conditions = getAllConditions(rule, RawAttributeMapper.of(rule));
        if (conditions.isEmpty()) {
            // bail early for most common case of no conditions in the rule.
            continue;
        }

        Label nodeLabel = node.getLabel().getLabel();
        for (Node<Target> succ : node.getSuccessors()) {
            Label successorLabel = succ.getLabel().getLabel();
            if (conditions.containsKey(successorLabel)) {
                insert(nodeLabel, successorLabel, conditions.get(successorLabel));
            }
        }
    }
}

From source file:org.eclipse.gef4.mvc.examples.logo.parts.FXGeometricCurvePart.java

@SuppressWarnings("serial")
public ITransactionalOperation chainModelChanges(final ITransactionalOperation updateVisualOperation) {
    if (updateVisualOperation == null) {
        return null;
    }//from   ww  w . j  a  v  a2 s. co m

    // determine old and new points
    final FXGeometricCurve curve = getContent();
    final List<Point> oldWayPoints = curve.getWayPointsCopy();
    final List<Point> newWayPoints = getVisual().getWayPoints();

    // create model operation
    final ITransactionalOperation updateModelOperation = new ChangeWayPointsOperation("Update Model", curve,
            oldWayPoints, newWayPoints);

    // determine current content anchorages
    AbstractFXGeometricElement<?> sourceContentAnchorage = getAnchorageContent(getVisual().getStartAnchor());
    AbstractFXGeometricElement<?> targetContentAnchorage = getAnchorageContent(getVisual().getEndAnchor());

    // create anchorage operations, start with detaching all anchorages
    ContentPolicy<Node> contentPolicy = this.getAdapter(new TypeToken<ContentPolicy<Node>>() {
    });
    contentPolicy.init();
    SetMultimap<IVisualPart<Node, ? extends Node>, String> anchorages = HashMultimap.create(getAnchorages());
    for (IVisualPart<Node, ? extends Node> anchorage : anchorages.keySet()) {
        if (anchorage instanceof IContentPart) {
            for (String role : anchorages.get(anchorage)) {
                Object contentAnchorage = ((IContentPart<Node, ? extends Node>) anchorage).getContent();
                if (role.equals("START")) {
                    if (contentAnchorage != sourceContentAnchorage) {
                        // it changed => detach
                        contentPolicy.detachFromContentAnchorage(contentAnchorage, role);
                    } else {
                        // no change => keep it
                        sourceContentAnchorage = null;
                    }
                } else if (role.equals("END")) {
                    if (contentAnchorage != targetContentAnchorage) {
                        // it changed => detach
                        contentPolicy.detachFromContentAnchorage(contentAnchorage, role);
                    } else {
                        // no change => keep it
                        targetContentAnchorage = null;
                    }
                }
            }
        }
    }
    final ITransactionalOperation detachOperation = contentPolicy.commit();

    // then attach source and target (if available)
    contentPolicy.init();
    if (sourceContentAnchorage != null) {
        contentPolicy.attachToContentAnchorage(sourceContentAnchorage, "START");
    }
    if (targetContentAnchorage != null) {
        contentPolicy.attachToContentAnchorage(targetContentAnchorage, "END");
    }
    final ITransactionalOperation attachOperation = contentPolicy.commit();

    // compose operations
    return new ForwardUndoCompositeOperation(updateVisualOperation.getLabel()) {
        {
            add(updateVisualOperation);
            add(updateModelOperation);
            if (detachOperation != null || attachOperation != null) {
                add(new ReverseUndoCompositeOperation("Change Anchorages") {
                    {
                        if (detachOperation != null) {
                            add(detachOperation);
                        }
                        if (attachOperation != null) {
                            add(attachOperation);
                        }
                    }
                });
            }
        }
    };
}

From source file:org.sleuthkit.autopsy.timeline.db.EventDB.java

/**
 * merge the events in the given list if they are within the same period
 * General algorithm is as follows:// w  ww. j  a v  a2  s. c  o  m
 *
 * 1) sort them into a map from (type, description)-> List<aggevent>
 * 2) for each key in map, merge the events and accumulate them in a list to
 * return
 *
 * @param timeUnitLength
 * @param preMergedEvents
 *
 * @return
 */
static private List<EventStripe> mergeClustersToStripes(Period timeUnitLength,
        List<EventCluster> preMergedEvents) {

    //effectively map from type to (map from description to events)
    Map<EventType, SetMultimap<String, EventCluster>> typeMap = new HashMap<>();

    for (EventCluster aggregateEvent : preMergedEvents) {
        typeMap.computeIfAbsent(aggregateEvent.getEventType(), eventType -> HashMultimap.create())
                .put(aggregateEvent.getDescription(), aggregateEvent);
    }
    //result list to return
    ArrayList<EventCluster> aggEvents = new ArrayList<>();

    //For each (type, description) key, merge agg events
    for (SetMultimap<String, EventCluster> descrMap : typeMap.values()) {
        //for each description ...
        for (String descr : descrMap.keySet()) {
            //run through the sorted events, merging together adjacent events
            Iterator<EventCluster> iterator = descrMap.get(descr).stream()
                    .sorted(Comparator.comparing(event -> event.getSpan().getStartMillis())).iterator();
            EventCluster current = iterator.next();
            while (iterator.hasNext()) {
                EventCluster next = iterator.next();
                Interval gap = current.getSpan().gap(next.getSpan());

                //if they overlap or gap is less one quarter timeUnitLength
                //TODO: 1/4 factor is arbitrary. review! -jm
                if (gap == null || gap.toDuration()
                        .getMillis() <= timeUnitLength.toDurationFrom(gap.getStart()).getMillis() / 4) {
                    //merge them
                    current = EventCluster.merge(current, next);
                } else {
                    //done merging into current, set next as new current
                    aggEvents.add(current);
                    current = next;
                }
            }
            aggEvents.add(current);
        }
    }

    //merge clusters to stripes
    Map<ImmutablePair<EventType, String>, EventStripe> stripeDescMap = new HashMap<>();

    for (EventCluster eventCluster : aggEvents) {
        stripeDescMap.merge(ImmutablePair.of(eventCluster.getEventType(), eventCluster.getDescription()),
                new EventStripe(eventCluster), EventStripe::merge);
    }

    return stripeDescMap.values().stream().sorted(Comparator.comparing(EventStripe::getStartMillis))
            .collect(Collectors.toList());
}

From source file:org.sosy_lab.cpachecker.cpa.predicate.PredicateCPAGlobalRefiner.java

/**
 * Recursively perform refinement on the subgraph of the ARG starting with a given state.
 * Each recursion step corresponds to one "block" of the ARG. As one block
 * may have several successors, this is recursion on a tree.
 * We proceed in a DFS order./*from ww w.  ja  va2  s .  c o m*/
 * Recursion stops as soon as the path has been determined to be infeasible
 * (so we do refinement as soon as possible) or a target state is reached
 * (then we found a feasible counterexample).
 * When an infeasible state was found, we call
 * {@link #performRefinementOnPath(List, ARGState, List, ARGReachedSet, InterpolatingProverEnvironment)}
 * to do the actual refinement.
 *
 * Note that the successor and predecessor relation contains only states
 * that belong to paths to a target state, so we refine only such paths,
 * and not all paths in the ARG.
 *
 * @param currentPath The list of ARG states from the root to the current element.
 * @param itpStack The stack of interpolation groups added to the solver environment so far.
 * @param successors The successor relation between abstraction states.
 * @param predecessors The predecessor relation between abstraction states.
 * @param pReached The complete reached set.
 * @param targets The set of target states.
 * @return The feasible error location or absent
 */
private <T> Optional<ARGState> step(final LinkedList<ARGState> currentPath, final List<T> itpStack,
        final SetMultimap<ARGState, ARGState> successors, final Map<ARGState, ARGState> predecessors,
        final ARGReachedSet pReached, final List<AbstractState> targets,
        InterpolatingProverEnvironment<T> itpProver)
        throws InterruptedException, SolverException, CPAException {

    for (final ARGState succ : successors.get(currentPath.getLast())) {
        assert succ.getChildren().isEmpty() == targets.contains(succ);
        assert succ.mayCover();

        BooleanFormula blockFormula = getPredicateState(succ).getAbstractionFormula().getBlockFormula()
                .getFormula();
        itpStack.add(itpProver.push(blockFormula));
        currentPath.add(succ);
        try {
            satCheckTime.start();
            boolean isUnsat = itpProver.isUnsat();
            satCheckTime.stop();
            if (isUnsat) {
                logger.log(Level.FINE, "Found unreachable state", succ);
                List<ARGState> abstractionStatesTrace = new ArrayList<>(currentPath);

                ARGState cur = succ;
                while (successors.containsKey(cur)) {
                    // we just always use the first child, as every interpolant
                    // below the unreacheable state will be false anyway we don't need
                    // to have all paths to all reachable error states
                    ARGState tmp = successors.get(cur).iterator().next();
                    abstractionStatesTrace.add(tmp);
                    cur = tmp;
                }
                assert cur.isTarget() : "Last state in path has to be a target state";

                performRefinementOnPath(unmodifiableList(itpStack), succ, abstractionStatesTrace, pReached,
                        itpProver);

            } else if (targets.contains(succ)) {
                // We have found a reachable target state, immediately abort refinement.
                logger.log(Level.FINE, "Found reachable target state", succ);
                return Optional.of(succ);

            } else {
                // Not yet infeasible, but path is longer,
                // so descend recursively.
                Optional<ARGState> tmp = step(currentPath, itpStack, successors, predecessors, pReached,
                        targets, itpProver);

                if (tmp.isPresent()) {
                    return tmp;
                }
            }

        } finally {
            itpStack.remove(itpStack.size() - 1);
            itpProver.pop();
            currentPath.remove(currentPath.size() - 1);
        }
    }
    return Optional.empty();
}

From source file:edu.cmu.lti.oaqa.baseqa.answer.collective_score.scorers.DistanceCollectiveAnswerScorer.java

@SuppressWarnings("unchecked")
@Override//  w w w  .ja  va2  s.c o  m
public void prepare(JCas jcas) {
    answers = TypeUtil.getRankedAnswers(jcas);
    distances = HashBasedTable.create();
    ImmutableSet<Answer> answerSet = ImmutableSet.copyOf(answers);
    SetMultimap<Answer, CandidateAnswerOccurrence> answer2caos = HashMultimap.create();
    answers.forEach(answer -> TypeUtil.getCandidateAnswerVariants(answer).stream()
            .map(TypeUtil::getCandidateAnswerOccurrences).forEach(caos -> answer2caos.putAll(answer, caos)));
    for (List<Answer> pair : Sets.cartesianProduct(answerSet, answerSet)) {
        Answer answer1 = pair.get(0);
        Answer answer2 = pair.get(1);
        if (answer1.equals(answer2)) {
            distances.put(answer1, answer2, 1.0);
        } else {
            Sets.cartesianProduct(answer2caos.get(answer1), answer2caos.get(answer2)).stream()
                    .filter(DistanceCollectiveAnswerScorer::allInTheSameView)
                    .mapToInt(caopair -> getDistance(caopair.get(0), caopair.get(1))).min()
                    .ifPresent(x -> distances.put(answer1, answer2, 1.0 / (1.0 + x)));
        }
    }
    ndistances = normalize(distances);
}