List of usage examples for com.google.common.collect Multiset count
int count(@Nullable Object element);
From source file:org.onebusaway.nyc.vehicle_tracking.impl.particlefilter.ParticleFilter.java
/** * Low variance sampler. Follows Thrun's example in Probabilistic Robots. * @throws ParticleFilterException //from ww w. java 2s . c om */ public static Multiset<Particle> lowVarianceSampler(Multiset<Particle> particles, double M) throws BadProbabilityParticleFilterException { Preconditions.checkArgument(particles.size() > 0); Preconditions.checkArgument(M > 0); final Multiset<Particle> resampled = HashMultiset.create((int) M); final double r = ParticleFactoryImpl.getLocalRng().nextDouble() / M; final Iterator<Particle> pIter = particles.iterator(); Particle p = pIter.next(); double c = p.getLogNormedWeight() - FastMath.log(particles.count(p)); for (int m = 0; m < M; ++m) { final double U = FastMath.log(r + m / M); while (U > c && pIter.hasNext()) { p = pIter.next(); c = LogMath.add(p.getLogNormedWeight() - FastMath.log(particles.count(p)), c); } resampled.add(p); } if (resampled.size() != M) throw new BadProbabilityParticleFilterException("low variance sampler did not return a valid sample"); return resampled; }
From source file:com.github.rinde.rinsim.central.Solvers.java
static GlobalStateObject fixRoutes(GlobalStateObject state) { boolean firstVehicle = true; final ImmutableList.Builder<VehicleStateObject> vehicleList = ImmutableList.builder(); for (int i = 0; i < state.getVehicles().size(); i++) { final VehicleStateObject vso = state.getVehicles().get(i); checkArgument(vso.getRoute().isPresent()); final List<Parcel> route = new ArrayList<>(vso.getRoute().get()); final Multiset<Parcel> routeContents = LinkedHashMultiset.create(route); for (final Parcel p : routeContents.elementSet()) { if (vso.getContents().contains(p)) { // should occur only once if (routeContents.count(p) > 1) { // remove route.remove(p);//w w w . j a v a 2s .c o m checkArgument(routeContents.count(p) == 2); } } else { // should occur twice if (routeContents.count(p) < 2) { route.add(p); } else { checkArgument(routeContents.count(p) == 2); } } } if (firstVehicle) { final Set<Parcel> unassigned = GlobalStateObjects.unassignedParcels(state); route.addAll(unassigned); route.addAll(unassigned); firstVehicle = false; } vehicleList.add(VehicleStateObject.create(vso.getDto(), vso.getLocation(), vso.getContents(), vso.getRemainingServiceTime(), vso.getDestination().orNull(), ImmutableList.copyOf(route))); } return GlobalStateObject.create(state.getAvailableParcels(), vehicleList.build(), state.getTime(), state.getTimeUnit(), state.getSpeedUnit(), state.getDistUnit()); }
From source file:com.googlecode.blaisemath.graph.mod.metrics.BetweenCentrality.java
/** * Breadth-first search algorithm for an unweighted graph to generate * betweenness scores, with specified starting vertex. From <i>Brandes</i>, * "A Faster Algorithm for Betweenness Centrality" * * @param graph the graph//from w w w . ja v a 2 s. c om * @param start the start vertex * @param between data structure storing existing betweenness centrality values * @param multiplier applied to all elements of resulting map * @return data structure encoding the result */ static <V> Map<V, Double> brandes(Graph<V> graph, V start, Map<V, Double> between, double multiplier) { Set<V> nodes = graph.nodes(); if (!nodes.contains(start)) { return new HashMap<V, Double>(); } // number of shortest paths to each vertex Multiset<V> numShortest = HashMultiset.create(); // length of shortest paths to each vertex Map<V, Integer> lengths = new HashMap<V, Integer>(); // tracks elements in non-increasing order for later use Deque<V> deque = Queues.newArrayDeque(); // tracks vertex predecessors in resulting tree Multimap<V, V> pred = HashMultimap.create(); GraphUtils.breadthFirstSearch(graph, start, numShortest, lengths, deque, pred); // compute betweenness Map<V, Double> dependencies = new HashMap<V, Double>(); for (V v : nodes) { dependencies.put(v, 0.0); } while (!deque.isEmpty()) { V w = deque.pollLast(); for (V v : pred.get(w)) { dependencies.put(v, dependencies.get(v) + (double) numShortest.count(v) / numShortest.count(w) * (1 + dependencies.get(w))); } if (w != start) { between.put(w, between.get(w) + multiplier * dependencies.get(w)); } } return between; }
From source file:edu.cornell.cs.nlp.spf.test.ccg.lambda.SingleSentencePartialCreditTestingStatistics.java
private static PartialCreditTriplet partialCompare(LogicalExpression gold, LogicalExpression label) { final Multiset<Pair<? extends LogicalExpression, ? extends LogicalExpression>> goldPairs = GetPredConstPairs .of(gold);//from w w w .j a va 2 s . 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:com.github.rinde.rinsim.scenario.measure.Metrics.java
/** * Computes the number of occurrences of each event type in the specified * {@link Scenario}./*from w w w . jav a2 s. c o m*/ * @param s The scenario to check. * @return A {@link ImmutableMultiset} of event types. */ public static ImmutableMultiset<Class<?>> getEventTypeCounts(Scenario s) { final Multiset<Class<?>> set = LinkedHashMultiset.create(); for (final TimedEvent te : s.getEvents()) { set.add(te.getClass()); } final List<Class<?>> toMove = new ArrayList<>(); for (final Class<?> c : set.elementSet()) { if (!Modifier.isPublic(c.getModifiers()) && TimedEvent.class.isAssignableFrom(c.getSuperclass()) && !set.contains(c.getSuperclass())) { toMove.add(c); } } for (final Class<?> c : toMove) { set.add(c.getSuperclass(), set.count(c)); set.remove(c, set.count(c)); } return ImmutableMultiset.copyOf(set); }
From source file:com.intellij.find.impl.FindInProjectTask.java
private static void logStats(Collection<PsiFile> otherFiles, long start) { long time = System.currentTimeMillis() - start; final Multiset<String> stats = HashMultiset.create(); for (PsiFile file : otherFiles) { //noinspection StringToUpperCaseOrToLowerCaseWithoutLocale stats.add(StringUtil.notNullize(file.getViewProvider().getVirtualFile().getExtension()).toLowerCase()); }/*from w w w . j a v a 2 s. com*/ List<String> extensions = ContainerUtil.newArrayList(stats.elementSet()); Collections.sort(extensions, new Comparator<String>() { @Override public int compare(String o1, String o2) { return stats.count(o2) - stats.count(o1); } }); String message = "Search in " + otherFiles.size() + " files with unknown types took " + time + "ms.\n" + "Mapping their extensions to an existing file type (e.g. Plain Text) might speed up the search.\n" + "Most frequent non-indexed file extensions: "; for (int i = 0; i < Math.min(10, extensions.size()); i++) { String extension = extensions.get(i); message += extension + "(" + stats.count(extension) + ") "; } LOG.info(message); }
From source file:com.google.javascript.jscomp.deps.SortedDependencies.java
private static <T> List<T> topologicalStableSort(List<T> items, Multimap<T, T> deps) { if (items.isEmpty()) { // Priority queue blows up if we give it a size of 0. Since we need // to special case this either way, just bail out. return new ArrayList<>(); }//from w w w . j av a2s.c om final Map<T, Integer> originalIndex = new HashMap<>(); for (int i = 0; i < items.size(); i++) { originalIndex.put(items.get(i), i); } PriorityQueue<T> inDegreeZero = new PriorityQueue<>(items.size(), new Comparator<T>() { @Override public int compare(T a, T b) { return originalIndex.get(a).intValue() - originalIndex.get(b).intValue(); } }); List<T> result = new ArrayList<>(); Multiset<T> inDegree = HashMultiset.create(); Multimap<T, T> reverseDeps = ArrayListMultimap.create(); Multimaps.invertFrom(deps, reverseDeps); // First, add all the inputs with in-degree 0. for (T item : items) { Collection<T> itemDeps = deps.get(item); inDegree.add(item, itemDeps.size()); if (itemDeps.isEmpty()) { inDegreeZero.add(item); } } // Then, iterate to a fixed point over the reverse dependency graph. while (!inDegreeZero.isEmpty()) { T item = inDegreeZero.remove(); result.add(item); for (T inWaiting : reverseDeps.get(item)) { inDegree.remove(inWaiting, 1); if (inDegree.count(inWaiting) == 0) { inDegreeZero.add(inWaiting); } } } return result; }
From source file:org.apache.mahout.math.stats.LogLikelihood.java
/** * Compares two sets of counts to see which items are interestingly over-represented in the first * set./* w w w.ja v a 2s. c om*/ * @param a The first counts. * @param b The reference counts. * @param maxReturn The maximum number of items to return. Use maxReturn >= a.elementSet.size() to return all * scores above the threshold. * @param threshold The minimum score for items to be returned. Use 0 to return all items more common * in a than b. Use -Double.MAX_VALUE (not Double.MIN_VALUE !) to not use a threshold. * @return A list of scored items with their scores. */ public static <T> List<ScoredItem<T>> compareFrequencies(Multiset<T> a, Multiset<T> b, int maxReturn, double threshold) { int totalA = a.size(); int totalB = b.size(); Ordering<ScoredItem<T>> byScoreAscending = new Ordering<ScoredItem<T>>() { @Override public int compare(ScoredItem<T> tScoredItem, ScoredItem<T> tScoredItem1) { return Double.compare(tScoredItem.score, tScoredItem1.score); } }; Queue<ScoredItem<T>> best = new PriorityQueue<ScoredItem<T>>(maxReturn + 1, byScoreAscending); for (T t : a.elementSet()) { compareAndAdd(a, b, maxReturn, threshold, totalA, totalB, best, t); } // if threshold >= 0 we only iterate through a because anything not there can't be as or more common than in b. if (threshold < 0) { for (T t : b.elementSet()) { // only items missing from a need be scored if (a.count(t) == 0) { compareAndAdd(a, b, maxReturn, threshold, totalA, totalB, best, t); } } } List<ScoredItem<T>> r = Lists.newArrayList(best); Collections.sort(r, byScoreAscending.reverse()); return r; }
From source file:io.ssc.trackthetrackers.analysis.stats.LogLikelihood.java
/** * Compares two sets of counts to see which items are interestingly over-represented in the first * set./* w ww . ja v a2s . co m*/ * @param a The first counts. * @param b The reference counts. * @param maxReturn The maximum number of items to return. Use maxReturn >= a.elementSet.size() to return all * scores above the threshold. * @param threshold The minimum score for items to be returned. Use 0 to return all items more common * in a than b. Use -Double.MAX_VALUE (not Double.MIN_VALUE !) to not use a threshold. * @return A list of scored items with their scores. */ public static <T> List<ScoredItem<T>> compareFrequencies(Multiset<T> a, Multiset<T> b, int maxReturn, double threshold) { int totalA = a.size(); int totalB = b.size(); Ordering<ScoredItem<T>> byScoreAscending = new Ordering<ScoredItem<T>>() { @Override public int compare(ScoredItem<T> tScoredItem, ScoredItem<T> tScoredItem1) { return Double.compare(tScoredItem.score, tScoredItem1.score); } }; Queue<ScoredItem<T>> best = new PriorityQueue<ScoredItem<T>>(maxReturn + 1, byScoreAscending); for (T t : a.elementSet()) { compareAndAdd(a, b, maxReturn, threshold, totalA, totalB, best, t); } // if threshold >= 0 we only iterate through a because anything not there can't be as or more common than in b. if (threshold < 0) { for (T t : b.elementSet()) { // only items missing from a need be scored if (a.count(t) == 0) { compareAndAdd(a, b, maxReturn, threshold, totalA, totalB, best, t); } } } List<ScoredItem<T>> r = new ArrayList<ScoredItem<T>>(best); Collections.sort(r, byScoreAscending.reverse()); return r; }
From source file:com.scaleunlimited.cascading.ml.LogLikelihood.java
/** * Compares two sets of counts to see which items are interestingly * over-represented in the first set.//from w ww . j a va 2s. co m * * @param a * The first counts. * @param b * The reference counts. * @param maxReturn * The maximum number of items to return. Use maxReturn >= * a.elementSet.size() to return all scores above the threshold. * @param threshold * The minimum score for items to be returned. Use 0 to return * all items more common in a than b. Use -Double.MAX_VALUE (not * Double.MIN_VALUE !) to not use a threshold. * @return A list of scored items with their scores. */ public static <T> List<ScoredItem<T>> compareFrequencies(Multiset<T> a, Multiset<T> b, int maxReturn, double threshold) { int totalA = a.size(); int totalB = b.size(); Ordering<ScoredItem<T>> byScoreAscending = new Ordering<ScoredItem<T>>() { @Override public int compare(ScoredItem<T> tScoredItem, ScoredItem<T> tScoredItem1) { return Double.compare(tScoredItem.score, tScoredItem1.score); } }; Queue<ScoredItem<T>> best = new PriorityQueue<ScoredItem<T>>(maxReturn + 1, byScoreAscending); for (T t : a.elementSet()) { compareAndAdd(a, b, maxReturn, threshold, totalA, totalB, best, t); } // if threshold >= 0 we only iterate through a because anything not // there can't be as or more common than in b. if (threshold < 0) { for (T t : b.elementSet()) { // only items missing from a need be scored if (a.count(t) == 0) { compareAndAdd(a, b, maxReturn, threshold, totalA, totalB, best, t); } } } List<ScoredItem<T>> r = Lists.newArrayList(best); Collections.sort(r, byScoreAscending.reverse()); return r; }