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

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

Introduction

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

Prototype

int add(@Nullable E element, int occurrences);

Source Link

Document

Adds a number of occurrences of an element to this multiset.

Usage

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

/**
 * This runs a single time-step of the particle filter, given a single
 * timestep's worth of sensor readings.//from ww w . java2  s  .  c o  m
 * 
 * @param timestamp
 * @param obs
 * @param moveParticles
 * @throws ParticleFilterException
 */
private void runSingleTimeStep(double timestamp, OBS obs, boolean moveParticles)
        throws ParticleFilterException {

    Multiset<Particle> particles = _particles;

    /*
     * perform movement and weighing separately
     */
    if (moveParticles) {
        final double elapsed = timestamp - _timeOfLastUpdate;
        particles = _motionModel.move(_particles, timestamp, elapsed, obs, _previouslyResampled);
    }

    /**
     * 3. track the weighted particles (before resampling and normalization)
     */
    _weightedParticles = particles;

    /**
     * 4. store the most likely particle's information
     */
    computeBestState(particles);

    if (getEffectiveSampleSize(particles)
            / ParticleFactoryImpl.getInitialNumberOfParticles() < _resampleThreshold) {

        /**
         * 5. resample
         */
        final Multiset<Particle> resampled = lowVarianceSampler(particles, particles.size());

        final Multiset<Particle> reweighted = HashMultiset.create(resampled.size());
        for (final Entry<Particle> pEntry : resampled.entrySet()) {
            final Particle p = pEntry.getElement().cloneParticle();
            p.setWeight(((double) pEntry.getCount()) / resampled.size());
            reweighted.add(p, pEntry.getCount());
        }
        _particles = reweighted;
        _previouslyResampled = true;
    } else {
        _particles = particles;
        _previouslyResampled = false;
    }

}

From source file:org.onosproject.store.primitives.resources.impl.AtomixConsistentSetMultimapService.java

/**
 * Handles a Keys commit./*from   www . ja  v  a2  s  . com*/
 *
 * @param commit Keys commit
 * @return a multiset of keys with each key included an equal number of
 * times to the total key-value pairs in which that key participates
 */
protected Multiset<String> keys(Commit<Void> commit) {
    Multiset keys = HashMultiset.create();
    backingMap.forEach((key, mapEntryValue) -> {
        keys.add(key, mapEntryValue.values().size());
    });
    return keys;
}

From source file:org.onosproject.store.primitives.resources.impl.AtomixConsistentSetMultimapState.java

/**
 * Handles a Keys commit./*from   w  ww.  j a v a 2  s.  com*/
 *
 * @param commit Keys commit
 * @return a multiset of keys with each key included an equal number of
 * times to the total key-value pairs in which that key participates
 */
protected Multiset<String> keys(Commit<? extends Keys> commit) {
    try {
        Multiset keys = HashMultiset.create();
        backingMap.forEach((key, mapEntryValue) -> {
            keys.add(key, mapEntryValue.values().size());
        });
        return keys;
    } finally {
        commit.close();
    }
}

From source file:org.onebusaway.nyc.vehicle_tracking.impl.simulator.SimulatorTask.java

public VehicleLocationDetails getParticleDetails(int particleId, int recordIndex) {
    final VehicleLocationDetails details = new VehicleLocationDetails();
    details.setId(_id);/*w ww.ja v  a  2  s . com*/

    final Collection<Multiset.Entry<Particle>> particles;
    if (recordIndex < 0) {
        details.setLastObservation(
                RecordLibrary.getNycTestInferredLocationRecordAsNycRawLocationRecord(_mostRecentRecord));
        particles = _vehicleLocationInferenceService.getCurrentParticlesForVehicleId(_vehicleId).entrySet();
    } else {
        details.setLastObservation(getDetails(recordIndex).getLastObservation());
        particles = getDetails(recordIndex).getParticles();
    }

    if (particles != null) {
        for (final Multiset.Entry<Particle> pEntry : particles) {
            Particle p = pEntry.getElement();
            if (p.getIndex() == particleId) {
                final Multiset<Particle> history = TreeMultiset.create(Ordering.natural());
                while (p != null && history.elementSet().size() <= _particleParentSize) {
                    history.add(p, pEntry.getCount());
                    p = p.getParent();
                }
                details.setParticles(history);
                details.setHistory(true);
                break;
            }
        }
    }
    return details;
}

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

private VehicleLocationDetails findParticle(VehicleLocationDetails details, int particleId) {
    final List<Entry<Particle>> particles = details.getParticles();
    if (particles != null) {
        for (final Entry<Particle> pEntry : particles) {
            Particle p = pEntry.getElement();
            if (p.getIndex() == particleId) {
                final Multiset<Particle> history = TreeMultiset.create();
                while (p != null) {
                    history.add(p, pEntry.getCount());
                    p = p.getParent();//w w w.  j ava  2  s.  co  m
                }
                details.setParticles(history);
                details.setHistory(true);
                return details;
            }
        }
    }
    return null;
}

From source file:eu.lp0.cursus.scoring.scores.impl.GenericRaceLapsData.java

@Override
protected List<Pilot> calculateRaceLapsInOrder(Race race, Map<Pilot, Integer> laps) {
    ListMultimap<Integer, Pilot> raceOrder = ArrayListMultimap.create(EXPECTED_MAXIMUM_LAPS,
            scores.getPilots().size());//w w w .  j av a 2 s . c o m

    extractRaceLaps(race, laps, raceOrder, null);

    // Get penalties for each pilot
    ListMultimap<Pilot, Penalty> cancelLaps = ArrayListMultimap.create(EXPECTED_MAXIMUM_PENALTIES,
            scores.getPilots().size());
    ListMultimap<Pilot, Penalty> adjustLaps = ArrayListMultimap.create(EXPECTED_MAXIMUM_PENALTIES,
            scores.getPilots().size());
    for (RaceAttendee attendee : Maps.filterKeys(race.getAttendees(), Predicates.in(scores.getPilots()))
            .values()) {
        for (Penalty penalty : Iterables.concat(Ordering.natural().immutableSortedCopy(attendee.getPenalties()),
                scores.getSimulatedRacePenalties(attendee.getPilot(), race))) {
            if (penalty.getValue() != 0) {
                switch (penalty.getType()) {
                case CANCEL_LAPS:
                    cancelLaps.put(attendee.getPilot(), penalty);
                    break;

                case ADJUST_LAPS:
                    adjustLaps.put(attendee.getPilot(), penalty);
                    break;

                default:
                    break;
                }
            }
        }
    }

    // Apply lap cancellation penalties
    if (!cancelLaps.isEmpty()) {
        final Multiset<Pilot> pilotLaps = HashMultiset.create(laps.size());

        for (Map.Entry<Pilot, Integer> pilotLapCount : laps.entrySet()) {
            pilotLaps.setCount(pilotLapCount.getKey(), pilotLapCount.getValue());
        }

        for (Map.Entry<Pilot, Penalty> entry : cancelLaps.entries()) {
            int value = entry.getValue().getValue();
            if (value > 0) {
                pilotLaps.remove(entry.getKey(), value);
            } else {
                pilotLaps.add(entry.getKey(), Math.abs(value));
            }
        }

        extractRaceLaps(race, laps, raceOrder, new Predicate<Pilot>() {
            @Override
            public boolean apply(@Nullable Pilot pilot) {
                return pilotLaps.remove(pilot);
            }
        });
    }

    // Save pilot order
    List<Pilot> origPilotOrder = getPilotOrder(raceOrder);
    SortedSet<Pilot> noLaps = new TreeSet<Pilot>(new PilotRaceNumberComparator());
    Set<Integer> changed = new HashSet<Integer>();

    // It is intentional that pilots can end up having 0 laps but be considered to have completed the race
    for (Map.Entry<Pilot, Penalty> entry : adjustLaps.entries()) {
        Pilot pilot = entry.getKey();
        int lapCount = laps.get(pilot);

        raceOrder.remove(lapCount, pilot);
        changed.add(lapCount);

        lapCount += entry.getValue().getValue();
        if (lapCount <= 0) {
            lapCount = 0;
            noLaps.add(pilot);
        }
        laps.put(pilot, lapCount);

        raceOrder.put(lapCount, pilot);
        changed.add(lapCount);
    }

    // Apply original pilot order
    if (!changed.isEmpty()) {
        origPilotOrder.addAll(noLaps);

        for (Integer lapCount : changed) {
            raceOrder.replaceValues(lapCount,
                    Ordering.explicit(origPilotOrder).immutableSortedCopy(raceOrder.get(lapCount)));
        }

        return getPilotOrder(raceOrder);
    } else {
        return origPilotOrder;
    }
}

From source file:org.summer.dsl.xbase.typesystem.references.LightweightTypeReference.java

/**
 * Returns the list of all super types which includes the super class and the 
 * implemented interfaces. The type parameters of the provided super types are resolved.
 * That means, the super types of <code>ArrayList&lt;String&gt;</code> includes
 * <code>List&lt;String&gt;</code> and <code>Collection&lt;String&gt;</code> 
 * rather than <code>Collection&lt;E&gt;</code>.
 * /*w w w  . j av a 2  s  .c om*/
 * @return the list of all super types, can be empty.
 */
public List<LightweightTypeReference> getAllSuperTypes() {
    final List<LightweightTypeReference> result = Lists.newArrayList();
    final Multiset<JvmType> distances = HashMultiset.create(7);
    final Multiset<JvmType> counterPerType = HashMultiset.create(7);
    collectSuperTypes(new SuperTypeAcceptor() {

        int counter = 0;

        public boolean accept(LightweightTypeReference superType, int distance) {
            JvmType type = superType.getType();
            counterPerType.add(type, counter++);
            if (distances.contains(type)) {
                int currentCount = distances.count(type);
                if (currentCount < distance + 1) {
                    distances.setCount(type, distance + 1);
                } else {
                    return false;
                }
            } else {
                result.add(superType);
                distances.add(type, distance + 1);
            }
            return true;
        }

    });
    Collections.sort(result, new Comparator<LightweightTypeReference>() {
        public int compare(@Nullable LightweightTypeReference o1, @Nullable LightweightTypeReference o2) {
            if (o1 == null || o2 == null) {
                throw new IllegalArgumentException();
            }
            JvmType type1 = o1.getType();
            JvmType type2 = o2.getType();
            if (type1 == null)
                return 1;
            if (type2 == null)
                return -1;
            int distanceCompare = Ints.compare(distances.count(type1), distances.count(type2));
            if (distanceCompare != 0)
                return distanceCompare;
            return Ints.compare(counterPerType.count(type1), counterPerType.count(type2));
        }
    });
    return result;
}

From source file:org.summer.dsl.model.types.util.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. j  av a 2  s  .  com*/
 */
protected void cumulateDistance(final List<JvmTypeReference> references,
        Multimap<JvmType, JvmTypeReference> all, Multiset<JvmType> cumulatedDistance) {
    for (JvmTypeReference 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.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference.java

/**
 * Returns the list of all super types which includes the super class and the 
 * implemented interfaces. The type parameters of the provided super types are resolved.
 * That means, the super types of <code>ArrayList&lt;String&gt;</code> includes
 * <code>List&lt;String&gt;</code> and <code>Collection&lt;String&gt;</code> 
 * rather than <code>Collection&lt;E&gt;</code>.
 * //from w ww  .  j a v  a2  s.c om
 * @return the list of all super types, can be empty.
 */
public List<LightweightTypeReference> getAllSuperTypes() {
    final List<LightweightTypeReference> result = Lists.newArrayList();
    final Multiset<JvmType> distances = HashMultiset.create(7);
    final Multiset<JvmType> counterPerType = HashMultiset.create(7);
    collectSuperTypes(new SuperTypeAcceptor() {

        int counter = 0;

        @Override
        public boolean accept(LightweightTypeReference superType, int distance) {
            JvmType type = superType.getType();
            counterPerType.add(type, counter++);
            if (distances.contains(type)) {
                int currentCount = distances.count(type);
                if (currentCount < distance + 1) {
                    distances.setCount(type, distance + 1);
                } else {
                    return false;
                }
            } else {
                result.add(superType);
                distances.add(type, distance + 1);
            }
            return true;
        }

    });
    Collections.sort(result, new Comparator<LightweightTypeReference>() {
        @Override
        public int compare(/* @Nullable */ LightweightTypeReference o1,
                /* @Nullable */ LightweightTypeReference o2) {
            if (o1 == null || o2 == null) {
                throw new IllegalArgumentException();
            }
            JvmType type1 = o1.getType();
            JvmType type2 = o2.getType();
            if (type1 == null)
                return 1;
            if (type2 == null)
                return -1;
            int distanceCompare = Ints.compare(distances.count(type1), distances.count(type2));
            if (distanceCompare != 0)
                return distanceCompare;
            return Ints.compare(counterPerType.count(type1), counterPerType.count(type2));
        }
    });
    return result;
}

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.// www.  j av  a2  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());
        }
    }
}