Java Code Examples for com.google.common.collect.Multiset#Entry

The following examples show how to use com.google.common.collect.Multiset#Entry . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DiscreteElementwiseConditionalDistribution.java    From tassal with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Return the element with the maximum likelihood. If given is unkown, then
 * return null.
 * 
 * @param given
 * @return
 */
@Override
public Optional<A> getMaximumLikelihoodElement(final B given) {
	if (!table.containsKey(given)) {
		return Optional.absent();
	}
	int maxCount = 0;
	A maxLi = null;
	for (final Multiset.Entry<A> entry : table.get(given).entrySet()) {
		if (maxCount < entry.getCount()) {
			maxCount = entry.getCount();
			maxLi = entry.getElement();
		}
	}

	return Optional.of(maxLi);
}
 
Example 2
Source File: SpecValidations.java    From deploymentmanager-autogen with Apache License 2.0 6 votes vote down vote up
private static void validateMetadataKeyUniqueness(MultiVmDeploymentPackageSpec spec) {
  // Ensures that metadata keys are unique.
  Multiset<String> metadataKeyCounts = HashMultiset.create();
  for (PasswordSpec password : spec.getPasswordsList()) {
    metadataKeyCounts.add(password.getMetadataKey());
  }
  for (VmTierSpec tier : spec.getTiersList()) {
    Multiset<String> perTier = HashMultiset.create(metadataKeyCounts);
    for (GceMetadataItem metadataItem : tier.getGceMetadataItemsList()) {
      perTier.add(metadataItem.getKey());
    }
    for (Multiset.Entry<String> entry : perTier.entrySet()) {
      if (entry.getCount() > 1) {
        throw new IllegalArgumentException(
            String.format("Metadata key '%s' is not unique", entry.getElement()));
      }
    }
  }
}
 
Example 3
Source File: ValueTypeComposer.java    From immutables with Apache License 2.0 6 votes vote down vote up
private void checkAttributeNamesForDuplicates(ValueType type, Protoclass protoclass) {
  if (!type.attributes.isEmpty()) {
    Multiset<String> attributeNames = HashMultiset.create(type.attributes.size());
    for (ValueAttribute attribute : type.attributes) {
      if (attribute.isGenerateLazy) {
        attributeNames.add(attribute.name() + "$lazy"); // making lazy compare in it's own scope
      } else {
        attributeNames.add(attribute.name());
      }
    }

    List<String> duplicates = Lists.newArrayList();
    for (Multiset.Entry<String> entry : attributeNames.entrySet()) {
      if (entry.getCount() > 1) {
        duplicates.add(entry.getElement().replace("$lazy", ""));
      }
    }

    if (!duplicates.isEmpty()) {
      protoclass.report()
          .error("Duplicate attribute names %s. You should check if correct @Value.Style applied",
              duplicates);
    }
  }
}
 
Example 4
Source File: GetJobsAction.java    From spinach with Apache License 2.0 6 votes vote down vote up
private void reconnectToNearestProducer(DisqueConnection<K, V> disqueConnection, boolean forcedReconnect) {
    log.debug("reconnectToNearestProducer()");
    Set<Multiset.Entry<String>> stats = Multisets.copyHighestCountFirst(nodePrefixes).entrySet();
    nodePrefixes.clear();

    if (!isNodeSwitchNecessary(stats) && !forcedReconnect) {
        return;
    }

    String nodeIdPrefix = getNodeIdPrefix(stats);
    if (nodeIdPrefix != null) {
        log.debug("Set preferred node prefix to {}", nodeIdPrefix);
        socketAddressSupplier.setPreferredNodeIdPrefix(nodeIdPrefix);
    }

    if (disqueConnection.isOpen()) {
        if (nodeIdPrefix == null) {
            log.info("Initiating reconnect");
        } else {
            log.info("Initiating reconnect to preferred node with prefix {}", nodeIdPrefix);
        }
        disconnect((RedisChannelHandler<?, ?>) disqueConnection);
    }
}
 
Example 5
Source File: DiscreteElementwiseConditionalDistribution.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Return the element with the maximum likelihood. If given is unkown, then
 * return null.
 * 
 * @param given
 * @return
 */
@Override
public Optional<A> getMaximumLikelihoodElement(final B given) {
	if (!table.containsKey(given)) {
		return Optional.absent();
	}
	int maxCount = 0;
	A maxLi = null;
	for (final Multiset.Entry<A> entry : table.get(given).entrySet()) {
		if (maxCount < entry.getCount()) {
			maxCount = entry.getCount();
			maxLi = entry.getElement();
		}
	}

	return Optional.of(maxLi);
}
 
Example 6
Source File: ByEventTypeResultWriter.java    From tac-kbp-eal with MIT License 6 votes vote down vote up
@Override
public void writeResult(final List<EALScorer2015Style.Result> perDocResults,
    final File eventTypesDir) throws IOException {
  final Multiset<Symbol> eventTypesSeen = gatherEventTypesSeen(perDocResults);

  for (final Multiset.Entry<Symbol> typeEntry : Multisets.copyHighestCountFirst(eventTypesSeen)
      .entrySet()) {
    final Symbol type = typeEntry.getElement();
    final Function<EALScorer2015Style.ArgResult, EALScorer2015Style.ArgResult>
        filterFunction =
        new Function<EALScorer2015Style.ArgResult, EALScorer2015Style.ArgResult>() {
          @Override
          public EALScorer2015Style.ArgResult apply(final
          EALScorer2015Style.ArgResult input) {
            return input.copyFiltered(compose(equalTo(type), type()));
          }
        };
    final File eventTypeDir = new File(eventTypesDir, type.asString());
    eventTypeDir.mkdirs();
    writeOverallArgumentScoresForTransformedResults(perDocResults, filterFunction,
        eventTypeDir);
  }
}
 
Example 7
Source File: EntityScorer.java    From entity-fishing with Apache License 2.0 6 votes vote down vote up
public ScorerContext context(List<String> words) {
    Multiset<String> counter = TreeMultiset.create();
    counter.addAll(words);

    int word_dim = kb.getEmbeddingsSize();
    // word_vecs is the concatenation of all word vectors of the word list
    float[] word_vecs = new float[counter.size() * word_dim];
    IntArrayList word_counts = new IntArrayList();
    int n_words = 0;

    for(Multiset.Entry<String> entry : counter.entrySet()) {
        short[] vector = kb.getWordEmbeddings(entry.getElement());
        if (vector != null) {
            word_counts.add(entry.getCount());
            for (int i=0; i<kb.getEmbeddingsSize(); i++) {
                word_vecs[n_words * word_dim + i] = vector[i];
            }
            n_words += 1;
        }
    }
    word_counts.trim();

    return create_context(word_vecs, word_counts.elements());
}
 
Example 8
Source File: DefaultDistributedMultisetService.java    From atomix with Apache License 2.0 5 votes vote down vote up
@Override
public IteratorBatch<Multiset.Entry<String>> iterateEntries() {
  IteratorContext iterator = new IteratorContext(getCurrentSession().sessionId().id());
  if (!iterator.iterator.hasNext()) {
    return null;
  }

  long iteratorId = getCurrentIndex();
  entryIterators.put(iteratorId, iterator);
  IteratorBatch<Multiset.Entry<String>> batch = nextEntries(iteratorId, 0);
  if (batch.complete()) {
    entryIterators.remove(iteratorId);
  }
  return batch;
}
 
Example 9
Source File: ChaosConfig.java    From chaos-http-proxy with Apache License 2.0 5 votes vote down vote up
Properties getProperties() {
    Properties properties = new Properties();
    for (Multiset.Entry<Failure> entry :
            ImmutableMultiset.copyOf(failures).entrySet()) {
        properties.setProperty(entry.getElement().toPropertyName(),
                String.valueOf(entry.getCount()));
    }
    return properties;
}
 
Example 10
Source File: SampleUtils.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get a uniformly random element from a Multiset.
 * 
 * @param set
 * @return
 */
public static <T> T getRandomElement(final Multiset<T> set) {
	final int randPos = RandomUtils.nextInt(checkNotNull(set).size());

	T selected = null;
	int i = 0;
	for (final Multiset.Entry<T> entry : set.entrySet()) {
		i += entry.getCount();
		if (i > randPos) {
			selected = entry.getElement();
			break;
		}
	}
	return selected;
}
 
Example 11
Source File: DefaultDistributedMultisetService.java    From atomix with Apache License 2.0 5 votes vote down vote up
@Override
public IteratorBatch<String> nextElements(long iteratorId, int position) {
  IteratorBatch<Multiset.Entry<String>> batch = nextEntries(iteratorId, position);
  return batch == null ? null : new IteratorBatch<>(batch.id(), batch.position(), batch.entries()
      .stream()
      .map(element -> element.getElement())
      .collect(Collectors.toList()), batch.complete());
}
 
Example 12
Source File: DistributedMultisetProxy.java    From atomix with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Boolean> retainAll(Collection<? extends Multiset.Entry<String>> c) {
  throw new UnsupportedOperationException();
}
 
Example 13
Source File: UnmodifiableAsyncDistributedMultiset.java    From atomix with Apache License 2.0 4 votes vote down vote up
@Override
public AsyncDistributedSet<Multiset.Entry<E>> entrySet() {
  return asyncMultiset.entrySet();
}
 
Example 14
Source File: AtomicMultimapProxy.java    From atomix with Apache License 2.0 4 votes vote down vote up
@Override
public AsyncDistributedSet<Multiset.Entry<byte[]>> entrySet() {
  return new EntrySet();
}
 
Example 15
Source File: AtomicMultimapProxy.java    From atomix with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Boolean> retainAll(Collection<? extends Multiset.Entry<byte[]>> c) {
  return Futures.exceptionalFuture(new UnsupportedOperationException());
}
 
Example 16
Source File: AtomicMultimapProxy.java    From atomix with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Boolean> remove(Multiset.Entry<byte[]> element) {
  return Futures.exceptionalFuture(new UnsupportedOperationException());
}
 
Example 17
Source File: AtomicMultimapProxy.java    From atomix with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Boolean> add(Multiset.Entry<byte[]> element) {
  return Futures.exceptionalFuture(new UnsupportedOperationException());
}
 
Example 18
Source File: AtomicMultimapProxy.java    From atomix with Apache License 2.0 4 votes vote down vote up
@Override
public DistributedSet<Multiset.Entry<byte[]>> sync(Duration operationTimeout) {
  return new BlockingDistributedSet<>(this, operationTimeout.toMillis());
}
 
Example 19
Source File: EMStep.java    From sequence-mining with GNU General Public License v3.0 4 votes vote down vote up
/** EM-step for structural EM */
static Tuple2<Double, Map<Integer, Double>> structuralEMStep(final TransactionDatabase transactions,
		final InferenceAlgorithm inferenceAlgorithm, final Sequence candidate) {
	final double noTransactions = transactions.size();

	// Calculate max. no. of candidate occurrences
	final int maxReps = transactions.getTransactionList().parallelStream().mapToInt(t -> t.repetitions(candidate))
			.max().getAsInt();
	final Map<Integer, Double> initProb = new HashMap<>();
	initProb.put(0, 0.);
	for (int occur = 1; occur <= maxReps; occur++)
		initProb.put(occur, 1.);

	// E-step (adding candidate to transactions that support it)
	final Map<Multiset.Entry<Sequence>, Long> coveringWithCounts = transactions.getTransactionList()
			.parallelStream().map(t -> {
				if (t.contains(candidate)) {
					t.addSequenceCache(candidate, initProb);
					final Multiset<Sequence> covering = inferenceAlgorithm.infer(t);
					t.setTempCachedCovering(covering);
					return covering.entrySet();
				}
				return t.getCachedCovering().entrySet();
			}).flatMap(Set::stream).collect(groupingBy(identity(), counting()));

	// M-step
	final Table<Sequence, Integer, Double> newSequences = coveringWithCounts.entrySet().parallelStream().collect(
			HashBasedTable::create,
			(t, e) -> t.put(e.getKey().getElement(), e.getKey().getCount(), e.getValue() / noTransactions),
			Table::putAll);
	newSequences.rowKeySet().parallelStream().forEach(seq -> {
		// Pad with zero counts for non-occurrences
		final int maxOccur = Collections.max(newSequences.row(seq).keySet());
		for (int occur = 1; occur <= maxOccur; occur++) {
			if (!newSequences.contains(seq, occur))
				newSequences.put(seq, occur, 0.);
		} // Add probabilities for zero occurrences
		double rowSum = 0;
		for (final Double count : newSequences.row(seq).values())
			rowSum += count;
		newSequences.put(seq, 0, 1 - rowSum);
	});

	// Get average cost (removing candidate from supported transactions)
	final double averageCost = transactions.getTransactionList().parallelStream().mapToDouble(t -> {
		double cost;
		if (t.contains(candidate))
			cost = t.getTempCachedCost(newSequences);
		else
			cost = t.getCachedCost(newSequences);
		t.removeSequenceCache(candidate);
		return cost;
	}).sum() / noTransactions;

	// Get candidate prob
	final Map<Integer, Double> prob = newSequences.row(candidate);

	return new Tuple2<Double, Map<Integer, Double>>(averageCost, prob);
}
 
Example 20
Source File: AtomicMultimapProxy.java    From atomix with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Void> removeListener(CollectionEventListener<Multiset.Entry<byte[]>> listener) {
  return Futures.exceptionalFuture(new UnsupportedOperationException());
}