Example usage for com.google.common.collect Multiset entrySet

List of usage examples for com.google.common.collect Multiset entrySet

Introduction

In this page you can find the example usage for com.google.common.collect Multiset entrySet.

Prototype

Set<Entry<E>> entrySet();

Source Link

Document

Returns a view of the contents of this multiset, grouped into Multiset.Entry instances, each providing an element of the multiset and the count of that element.

Usage

From source file:org.summer.dsl.xbase.typesystem.conformance.TypeConformanceComputer.java

/**
 * Keeps the cumulated distance for all the common raw super types of the given references.
 * Interfaces that are more directly implemented will get a lower total count than more general
 * interfaces.//w w  w. ja v a 2  s.c  om
 */
protected void cumulateDistance(final List<LightweightTypeReference> references,
        Multimap<JvmType, LightweightTypeReference> all, Multiset<JvmType> cumulatedDistance) {
    for (LightweightTypeReference other : references) {
        Multiset<JvmType> otherDistance = LinkedHashMultiset.create();
        initializeDistance(other, all, otherDistance);
        cumulatedDistance.retainAll(otherDistance);
        for (Multiset.Entry<JvmType> typeToDistance : otherDistance.entrySet()) {
            if (cumulatedDistance.contains(typeToDistance.getElement()))
                cumulatedDistance.add(typeToDistance.getElement(), typeToDistance.getCount());
        }
    }
}

From source file:org.summer.dsl.model.types.util.TypeConformanceComputer.java

/**
 * Compute the common super type for the given types.
 * /*from ww w .j a  v  a  2  s .c o m*/
 * May return <code>null</code> in case one of the types is primitive void but not all 
 * of them are.
 */
public JvmTypeReference getCommonSuperType(final List<JvmTypeReference> types) {
    if (types == null || types.isEmpty())
        throw new IllegalArgumentException("Types can't be null or empty " + types);
    if (types.size() == 1)
        return types.get(0);

    // Check the straight forward case - one of the types is a supertype of all the others.
    // Further more check if any of the types is Void.TYPE -> all have to be Void.TYPE
    for (JvmTypeReference type : types) {
        if (conformsToAll(type, types))
            return type;
        if (isPrimitiveVoid(type)) {
            // we saw void but was not conformant to all other
            return null;
        }
    }
    //      if (allTypesAreArrays(types)) {
    //         List<JvmTypeReference> componentTypes = getComponentTypes(types);
    //         JvmTypeReference resultComponent = doGetCommonSuperType(componentTypes, new TypeConformanceComputationArgument(false, false, false));
    //         if (resultComponent != null) {
    //            JvmGenericArrayTypeReference result = factory.createJvmGenericArrayTypeReference();
    //            result.setComponentType(resultComponent);
    //            return result;
    //         }
    //      }
    // TODO handle all primitives
    // TODO handle arrays
    if (containsPrimitiveOrAnyReferences(types)) {
        List<JvmTypeReference> withoutPrimitives = replacePrimitivesAndRemoveAnyReferences(types);
        if (withoutPrimitives.equals(types))
            return null;
        return getCommonSuperType(withoutPrimitives);
    }
    JvmTypeReference firstType = types.get(0);
    final List<JvmTypeReference> tail = types.subList(1, types.size());
    // mapping from rawtype to resolved parameterized types
    // used to determine the correct type arguments
    Multimap<JvmType, JvmTypeReference> all = LinkedHashMultimap.create();
    // cumulated rawtype to max distance (used for sorting)
    Multiset<JvmType> cumulatedDistance = LinkedHashMultiset.create();

    initializeDistance(firstType, all, cumulatedDistance);
    cumulateDistance(tail, all, cumulatedDistance);

    List<Entry<JvmType>> candidates = Lists.newArrayList(cumulatedDistance.entrySet());
    if (candidates.size() == 1) { // only one super type -> should be java.lang.Object
        JvmType firstRawType = candidates.get(0).getElement();
        return getFirstForRawType(all, firstRawType);
    }
    inplaceSortByDistanceAndName(candidates);
    // try to find a matching parameterized type for the raw types in ascending order
    List<JvmTypeReference> referencesWithSameDistance = Lists.newArrayListWithExpectedSize(2);
    int wasDistance = -1;
    boolean classSeen = false;
    outer: for (Entry<JvmType> rawTypeCandidate : candidates) {
        JvmType rawType = rawTypeCandidate.getElement();
        JvmTypeReference result = null;
        if (wasDistance == -1) {
            wasDistance = rawTypeCandidate.getCount();
        } else {
            if (wasDistance != rawTypeCandidate.getCount()) {
                if (classSeen)
                    break;
                result = getTypeParametersForSupertype(all, rawType, types);
                for (JvmTypeReference alreadyCollected : referencesWithSameDistance) {
                    if (isConformant(result, alreadyCollected, true)) {
                        classSeen = classSeen || isClass(rawType);
                        continue outer;
                    }
                }
                wasDistance = rawTypeCandidate.getCount();
            }
        }
        if (result == null)
            result = getTypeParametersForSupertype(all, rawType, types);
        if (result != null) {
            boolean isClass = isClass(rawType);
            classSeen = classSeen || isClass;
            if (isClass)
                referencesWithSameDistance.add(0, result);
            else
                referencesWithSameDistance.add(result);
        }
    }
    if (referencesWithSameDistance.size() == 1) {
        return referencesWithSameDistance.get(0);
    } else if (referencesWithSameDistance.size() > 1) {
        JvmMultiTypeReference result = typeReferences
                .createMultiTypeReference(referencesWithSameDistance.get(0).getType());
        if (result == null)
            return result;
        for (JvmTypeReference reference : referencesWithSameDistance) {
            result.getReferences().add(EcoreUtil2.cloneIfContained(reference));
        }
        return result;
    }
    return null;
}

From source file:org.summer.dsl.xbase.typesystem.conformance.TypeConformanceComputer.java

/**
 * Compute the common super type for the given types.
 * /* ww  w .j  a v a 2 s.  c o m*/
 * May return <code>null</code> in case one of the types is primitive void but not all 
 * of them are.
 */
@Nullable
public LightweightTypeReference getCommonSuperType(final @NonNull List<LightweightTypeReference> types,
        ITypeReferenceOwner owner) {
    if (types == null || types.isEmpty())
        throw new IllegalArgumentException("Types can't be null or empty " + types);
    if (types.size() == 1)
        return types.get(0);

    // Check the straight forward case - one of the types is a supertype of all the others.
    // Further more check if any of the types is Void.TYPE -> all have to be Void.TYPE
    boolean allVoid = true;
    for (LightweightTypeReference type : types) {
        if (!type.isPrimitiveVoid()) {
            allVoid = false;
            break;
        }
    }
    if (allVoid) {
        return types.get(0);
    }
    for (LightweightTypeReference type : types) {
        LightweightTypeReference conformantType = conformsToAll(type, types);
        if (conformantType != null)
            return conformantType;
        if (type.isPrimitiveVoid()) {
            // we saw void but was not all were void
            return null;
        }
    }
    if (containsPrimitiveOrAnyReferences(types)) {
        List<LightweightTypeReference> withoutPrimitives = replacePrimitivesAndRemoveAnyReferences(types);
        if (withoutPrimitives.equals(types))
            return null;
        return getCommonSuperType(withoutPrimitives, owner);
    }
    LightweightTypeReference firstType = types.get(0);
    final List<LightweightTypeReference> tail = types.subList(1, types.size());
    // mapping from rawtype to resolved parameterized types
    // used to determine the correct type arguments
    Multimap<JvmType, LightweightTypeReference> all = LinkedHashMultimap.create();
    // cumulated rawtype to max distance (used for sorting)
    Multiset<JvmType> cumulatedDistance = LinkedHashMultiset.create();

    initializeDistance(firstType, all, cumulatedDistance);
    cumulateDistance(tail, all, cumulatedDistance);

    List<Entry<JvmType>> candidates = Lists.newArrayList(cumulatedDistance.entrySet());
    if (candidates.size() == 1) { // only one super type -> should be java.lang.Object
        JvmType firstRawType = candidates.get(0).getElement();
        return getFirstForRawType(all, firstRawType);
    }
    inplaceSortByDistanceAndName(candidates);
    // try to find a matching parameterized type for the raw types in ascending order
    List<LightweightTypeReference> referencesWithSameDistance = Lists.newArrayListWithExpectedSize(2);
    int wasDistance = -1;
    boolean classSeen = false;
    outer: for (Entry<JvmType> rawTypeCandidate : candidates) {
        JvmType rawType = rawTypeCandidate.getElement();
        LightweightTypeReference result = null;
        if (wasDistance == -1) {
            wasDistance = rawTypeCandidate.getCount();
        } else {
            if (wasDistance != rawTypeCandidate.getCount()) {
                if (classSeen)
                    break;
                result = getTypeParametersForSupertype(all, rawType, owner, types);
                for (LightweightTypeReference alreadyCollected : referencesWithSameDistance) {
                    if ((isConformant(result, alreadyCollected,
                            RawTypeConformanceComputer.RAW_TYPE | ALLOW_BOXING_UNBOXING
                                    | ALLOW_PRIMITIVE_WIDENING | ALLOW_SYNONYMS | ALLOW_RAW_TYPE_CONVERSION)
                            & SUCCESS) != 0) {
                        classSeen = classSeen || isClass(rawType);
                        continue outer;
                    }
                }
                wasDistance = rawTypeCandidate.getCount();
            }
        }
        if (result == null)
            result = getTypeParametersForSupertype(all, rawType, owner, types);
        if (result != null) {
            boolean isClass = isClass(rawType);
            classSeen = classSeen || isClass;
            if (isClass)
                referencesWithSameDistance.add(0, result);
            else
                referencesWithSameDistance.add(result);
        }
    }
    if (referencesWithSameDistance.size() == 1) {
        return referencesWithSameDistance.get(0);
    } else if (referencesWithSameDistance.size() > 1) {
        CompoundTypeReference result = new CompoundTypeReference(owner, false);
        for (LightweightTypeReference reference : referencesWithSameDistance) {
            result.addComponent(reference);
        }
        return result;
    }
    return null;
}

From source file:edu.uw.cs.lil.tiny.test.ccg.lambda.SingleSentencePartialCreditTestingStatistics.java

private PartialCreditTriplet partialCompare(LogicalExpression gold, LogicalExpression label) {
    final Multiset<Pair<? extends LogicalExpression, ? extends LogicalExpression>> goldPairs = GetPredConstPairs
            .of(gold);/*from  w  ww  . j ava  2s. c om*/
    final Multiset<Pair<? extends LogicalExpression, ? extends LogicalExpression>> labelPairs;
    if (label == null) {
        labelPairs = HashMultiset.create();
    } else {
        labelPairs = GetPredConstPairs.of(label);
    }

    // The "intersection" of the gold and label pair sets = the number of
    // matches
    final Multiset<Pair<? extends LogicalExpression, ? extends LogicalExpression>> intersection = HashMultiset
            .create();

    for (final Entry<Pair<? extends LogicalExpression, ? extends LogicalExpression>> entry : goldPairs
            .entrySet()) {
        intersection.setCount(entry.getElement(),
                Math.min(entry.getCount(), labelPairs.count(entry.getElement())));
    }

    return new PartialCreditTriplet(goldPairs.size(), labelPairs.size(), intersection.size());
}

From source file:org.onebusaway.nyc.vehicle_tracking.impl.inference.MotionModelImpl.java

@Override
public Multiset<Particle> move(Multiset<Particle> particles, double timestamp, double timeElapsed,
        Observation obs, boolean previouslyResampled) throws ParticleFilterException {

    final Multiset<Particle> results = HashMultiset.create();

    boolean anySnapped = false;
    /*//from  w  ww  . j  a  v a2s.c  o  m
     * TODO FIXME could keep a particle-set-info record...
     */
    for (final Multiset.Entry<Particle> parent : particles.entrySet()) {
        final VehicleState state = parent.getElement().getData();
        if (state.getBlockStateObservation() != null && state.getBlockStateObservation().isSnapped()) {
            anySnapped = true;
            break;
        }
    }
    final double ess = ParticleFilter.getEffectiveSampleSize(particles);
    final boolean generalBlockTransition = allowGeneralBlockTransition(obs, ess, previouslyResampled,
            anySnapped);
    double normOffset = Double.NEGATIVE_INFINITY;

    for (final Multiset.Entry<Particle> parent : particles.entrySet()) {
        final VehicleState parentState = parent.getElement().getData();
        final BlockStateObservation parentBlockStateObs = parentState.getBlockStateObservation();

        final Set<BlockStateObservation> transitions = Sets.newHashSet();

        if (generalBlockTransition || allowParentBlockTransition(parentState, obs)) {
            /*
             * These are all the snapped and DSC/run blocks
             */
            transitions.addAll(_blocksFromObservationService.determinePotentialBlockStatesForObservation(obs));
        } else if (parentBlockStateObs != null) {

            /*
             * Only the snapped blocks.
             * We are also allowing changes to snapped in-progress states when
             * they were sampled well outside of allowed backward search distance.
             */
            final double backwardDistance = Double.NEGATIVE_INFINITY;
            transitions.addAll(_blocksFromObservationService.advanceState(obs, parentState.getBlockState(),
                    backwardDistance, Double.POSITIVE_INFINITY));
        }

        BlockStateObservation newParentBlockStateObs;
        if (parentBlockStateObs != null) {
            newParentBlockStateObs = _blocksFromObservationService.getBlockStateObservationFromDist(obs,
                    parentBlockStateObs.getBlockState().getBlockInstance(),
                    parentBlockStateObs.getBlockState().getBlockLocation().getDistanceAlongBlock());
        } else {
            newParentBlockStateObs = null;
        }
        transitions.add(newParentBlockStateObs);

        /*
         * We make a subtle distinction here, by allowing the previous state to
         * remain as a transition but unaltered. This helps in cases of
         * deadhead->in-progress transitions, since, later on, the block state we
         * create in the following will be treated differently, signaled by way of
         * pointer equality.
         */

        final double vehicleHasNotMovedProb = MovedLikelihood.computeVehicleHasNotMovedProbability(obs);

        for (int i = 0; i < parent.getCount(); ++i) {
            final Particle sampledParticle = sampleTransitionParticle(parent, newParentBlockStateObs, obs,
                    vehicleHasNotMovedProb, transitions);
            normOffset = LogMath.add(sampledParticle.getLogWeight(), normOffset);
            results.add(sampledParticle);
        }
    }

    /*
     * Normalize
     */
    for (final Entry<Particle> p : results.entrySet()) {
        final double thisTotalWeight = p.getElement().getLogWeight() + FastMath.log(p.getCount());
        double logNormed = thisTotalWeight - normOffset;
        if (logNormed > 0d)
            logNormed = 0d;
        p.getElement().setLogNormedWeight(logNormed);
    }

    return results;
}

From source file:org.onebusaway.nyc.vehicle_tracking.impl.particlefilter.ParticleFilter.java

/**
 * Finds the most likely/occurring trip & phase combination among the
 * particles, then chooses the particle with highest likelihood of that pair. <br>
 * /*from  ww  w  .j a  v  a  2 s  .c o  m*/
 * FIXME violates generic particle contract by assuming data is of type
 * VehicleState
 * 
 * @param particles
 */
private void computeBestState(Multiset<Particle> particles) {
    /**
     * We choose the "most likely" particle over the entire distribution w.r.t
     * the inferred trip.
     */
    final TObjectDoubleMap<String> tripPhaseToProb = new TObjectDoubleHashMap<String>();

    final HashMultimap<String, Particle> particlesIdMap = HashMultimap.create();
    final SortedSet<Particle> bestParticles = new TreeSet<Particle>();
    String bestId = null;

    if (!_maxLikelihoodParticle) {
        double highestTripProb = Double.MIN_VALUE;
        int index = 0;
        for (final Multiset.Entry<Particle> pEntry : particles.entrySet()) {
            final Particle p = pEntry.getElement();
            p.setIndex(index++);

            final double w = FastMath.exp(p.getLogWeight() + FastMath.log(pEntry.getCount()));

            if (Double.isInfinite(w))
                continue;

            final VehicleState vs = p.getData();
            final String tripId = vs.getBlockState() == null ? "NA"
                    : vs.getBlockState().getBlockLocation().getActiveTrip().getTrip().toString();
            final String phase = vs.getJourneyState().toString();
            final String id = tripId + "." + phase;

            final double newProb = tripPhaseToProb.adjustOrPutValue(id, w, w);

            particlesIdMap.put(id, p);

            /**
             * Check most likely new trip & phase pairs, then find the most likely
             * particle(s) within those.
             */
            if (bestId == null || newProb > highestTripProb) {
                bestId = id;
                highestTripProb = newProb;
            }
        }
        bestParticles.addAll(particlesIdMap.get(bestId));
    } else {
        bestParticles.addAll(particles);
    }

    /**
     * after we've found the best trip & phase pair, we choose the highest
     * likelihood particle among those.
     */
    final Particle bestParticle = bestParticles.first();

    _mostLikelyParticle = bestParticle.cloneParticle();

}

From source file:org.eclipse.xtext.xbase.typesystem.conformance.TypeConformanceComputer.java

/**
 * Compute the common super type for the given types.
 * /* w  w  w .ja va 2  s  .  c  om*/
 * May return <code>null</code> in case one of the types is primitive void but not all 
 * of them are.
 */
/* @Nullable */
public LightweightTypeReference getCommonSuperType(final /* @NonNull */ List<LightweightTypeReference> types,
        ITypeReferenceOwner owner) {
    if (types == null || types.isEmpty())
        throw new IllegalArgumentException("Types can't be null or empty " + types);
    if (types.size() == 1)
        return types.get(0);

    // Check the straight forward case - one of the types is a supertype of all the others.
    // Further more check if any of the types is Void.TYPE -> all have to be Void.TYPE
    boolean allVoid = true;
    for (LightweightTypeReference type : types) {
        if (!type.isPrimitiveVoid()) {
            allVoid = false;
            break;
        }
    }
    if (allVoid) {
        return types.get(0);
    }
    for (LightweightTypeReference type : types) {
        LightweightTypeReference conformantType = conformsToAll(type, types);
        if (conformantType != null)
            return conformantType;
        if (type.isPrimitiveVoid()) {
            // we saw void but was not all were void
            return null;
        }
    }
    if (containsPrimitiveOrAnyReferences(types)) {
        List<LightweightTypeReference> withoutPrimitives = replacePrimitivesAndRemoveAnyReferences(types);
        if (withoutPrimitives.equals(types))
            return null;
        return getCommonSuperType(withoutPrimitives, owner);
    }
    LightweightTypeReference firstType = types.get(0);
    final List<LightweightTypeReference> tail = types.subList(1, types.size());
    // mapping from rawtype to resolved parameterized types
    // used to determine the correct type arguments
    Multimap<JvmType, LightweightTypeReference> all = LinkedHashMultimap.create();
    // cumulated rawtype to max distance (used for sorting)
    Multiset<JvmType> cumulatedDistance = LinkedHashMultiset.create();

    initializeDistance(firstType, all, cumulatedDistance);
    cumulateDistance(tail, all, cumulatedDistance);

    List<Entry<JvmType>> candidates = Lists.newArrayList(cumulatedDistance.entrySet());
    if (candidates.size() == 1) { // only one super type -> should be java.lang.Object
        JvmType firstRawType = candidates.get(0).getElement();
        return getFirstForRawType(all, firstRawType);
    }
    inplaceSortByDistanceAndName(candidates);
    // try to find a matching parameterized type for the raw types in ascending order
    List<LightweightTypeReference> referencesWithSameDistance = Lists.newArrayListWithExpectedSize(2);
    int wasDistance = -1;
    boolean classSeen = false;
    outer: for (Entry<JvmType> rawTypeCandidate : candidates) {
        JvmType rawType = rawTypeCandidate.getElement();
        LightweightTypeReference result = null;
        if (wasDistance == -1) {
            wasDistance = rawTypeCandidate.getCount();
        } else {
            if (wasDistance != rawTypeCandidate.getCount()) {
                if (classSeen)
                    break;
                result = getTypeParametersForSupertype(all, rawType, owner, types);
                for (LightweightTypeReference alreadyCollected : referencesWithSameDistance) {
                    if ((isConformant(result, alreadyCollected,
                            RawTypeConformanceComputer.RAW_TYPE | ALLOW_BOXING_UNBOXING
                                    | ALLOW_PRIMITIVE_WIDENING | ALLOW_SYNONYMS | ALLOW_FUNCTION_CONVERSION
                                    | ALLOW_RAW_TYPE_CONVERSION)
                            & SUCCESS) != 0) {
                        classSeen = classSeen || isClass(rawType);
                        continue outer;
                    }
                }
                wasDistance = rawTypeCandidate.getCount();
            }
        }
        if (result == null)
            result = getTypeParametersForSupertype(all, rawType, owner, types);
        if (result != null) {
            boolean isClass = isClass(rawType);
            classSeen = classSeen || isClass;
            if (isClass)
                referencesWithSameDistance.add(0, result);
            else
                referencesWithSameDistance.add(result);
        }
    }
    if (referencesWithSameDistance.size() == 1) {
        return referencesWithSameDistance.get(0);
    } else if (referencesWithSameDistance.size() > 1) {
        CompoundTypeReference result = owner.newCompoundTypeReference(false);
        for (LightweightTypeReference reference : referencesWithSameDistance) {
            result.addComponent(reference);
        }
        return result;
    }
    return null;
}

From source file:org.sonar.plugins.core.sensors.ViolationsDecorator.java

private void computeViolationsPerRules(DecoratorContext context) {
    Map<RulePriority, Multiset<Rule>> rulesPerSeverity = Maps.newHashMap();
    for (Violation violation : context.getViolations()) {
        Multiset<Rule> rulesBag = initRules(rulesPerSeverity, violation.getSeverity());
        rulesBag.add(violation.getRule());
    }/*from www . ja  v a  2  s. c o  m*/

    for (RulePriority severity : RulePriority.values()) {
        Metric metric = SeverityUtils.severityToViolationMetric(severity);

        Collection<Measure> children = context.getChildrenMeasures(MeasuresFilters.rules(metric));
        for (Measure child : children) {
            RuleMeasure childRuleMeasure = (RuleMeasure) child;
            Rule rule = childRuleMeasure.getRule();
            if (rule != null && MeasureUtils.hasValue(childRuleMeasure)) {
                Multiset<Rule> rulesBag = initRules(rulesPerSeverity, severity);
                rulesBag.add(rule, childRuleMeasure.getIntValue());
            }
        }

        Multiset<Rule> rulesBag = rulesPerSeverity.get(severity);
        if (rulesBag != null) {
            for (Multiset.Entry<Rule> entry : rulesBag.entrySet()) {
                RuleMeasure measure = RuleMeasure.createForRule(metric, entry.getElement(),
                        (double) entry.getCount());
                measure.setSeverity(severity);
                context.saveMeasure(measure);
            }
        }
    }
}

From source file:org.opentripplanner.routing.graph.Graph.java

public void summarizeBuilderAnnotations() {
    List<GraphBuilderAnnotation> gbas = this.graphBuilderAnnotations;
    Multiset<Class<? extends GraphBuilderAnnotation>> classes = HashMultiset.create();
    LOG.info("Summary (number of each type of annotation):");
    for (GraphBuilderAnnotation gba : gbas)
        classes.add(gba.getClass());//from www.  j  ava2s  .co m
    for (Multiset.Entry<Class<? extends GraphBuilderAnnotation>> e : classes.entrySet()) {
        String name = e.getElement().getSimpleName();
        int count = e.getCount();
        LOG.info("    {} - {}", name, count);
    }
}

From source file:com.trein.gtfs.otp.building.graph.osm.Graph.java

public void summarizeBuilderAnnotations() {
    List<GraphBuilderAnnotation> gbas = this.graphBuilderAnnotations;
    Multiset<Class<? extends GraphBuilderAnnotation>> classes = HashMultiset.create();
    LOG.info("Summary (number of each type of annotation):");
    for (GraphBuilderAnnotation gba : gbas) {
        classes.add(gba.getClass());//from   w ww .ja  v  a 2s. c o m
    }
    for (Multiset.Entry<Class<? extends GraphBuilderAnnotation>> e : classes.entrySet()) {
        String name = e.getElement().getSimpleName();
        int count = e.getCount();
        LOG.info("    {} - {}", name, count);
    }
}