Java Code Examples for com.google.common.collect.Multiset#addAll()

The following examples show how to use com.google.common.collect.Multiset#addAll() . 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: SlotMachineSimulation.java    From levelup-java-exercises with Apache License 2.0 8 votes vote down vote up
/**
 * Method should return the number of times an occurrence of a reel
 * 
 * @param reels
 * @return
 */
static int determinePayOutPercentage(List<String> reels) {

	Multiset<String> reelCount = HashMultiset.create();
	reelCount.addAll(reels);

	// order the number of elements by the higest
	ImmutableMultiset<String> highestCountFirst = Multisets.copyHighestCountFirst(reelCount);

	int count = 0;
	for (Entry<String> entry : highestCountFirst.entrySet()) {
		count = entry.getCount();
		break;
	}
	return count;
}
 
Example 2
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 3
Source File: NgramEnumerator.java    From pyramid with Apache License 2.0 6 votes vote down vote up
private static void add(List<String> source, Multiset<Ngram> multiset, String field, int slop, List<Integer> template){
    Multiset<Ngram> multiSetForDoc = ConcurrentHashMultiset.create();
    for (int i=0;i<source.size();i++){
        if(i+template.get(template.size()-1)<source.size()){
            List<String> list = new ArrayList<>();
            for (int j: template){
                list.add(source.get(i+j));
            }
            Ngram ngram = new Ngram();
            ngram.setNgram(Ngram.toNgramString(list));
            ngram.setSlop(slop);
            ngram.setField(field);
            ngram.setInOrder(true);
            multiSetForDoc.setCount(ngram,1);
        }
    }
     multiset.addAll(multiSetForDoc);
}
 
Example 4
Source File: BindingUtils.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a unidirectional content binding from the given source
 * {@link Multiset} to the given target {@link ObservableMultiset}.
 *
 * @param <E>
 *            The element type of the given {@link Multiset} and
 *            {@link ObservableMultiset}.
 * @param source
 *            The {@link Multiset} whose content to update when the given
 *            {@link ObservableMultiset} changes.
 * @param target
 *            The {@link ObservableMultiset} whose content is to be
 *            observed.
 */
public static <E> void bindContent(Multiset<E> source,
		ObservableMultiset<? extends E> target) {
	if (source == null) {
		throw new NullPointerException("Cannot bind null value.");
	}
	if (target == null) {
		throw new NullPointerException("Cannot bind to null value.");
	}
	if (source == target) {
		throw new IllegalArgumentException("Cannot bind source to itself.");
	}

	if (source instanceof ObservableMultiset) {
		// ensure we use an atomic operation in case the source multiset is
		// observable.
		((ObservableMultiset<E>) source).replaceAll(target);
	} else {
		source.clear();
		source.addAll(target);
	}

	final UnidirectionalMultisetContentBinding<E> contentBinding = new UnidirectionalMultisetContentBinding<>(
			source);
	// clear any previous bindings
	target.removeListener(contentBinding);
	// add new binding as listener
	target.addListener(contentBinding);
}
 
Example 5
Source File: PAMCore.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This method scans the input database to calculate the support of single
 * items.
 *
 * @param inputFile
 *            the input file
 * @return a multiset for storing the support of each singleton
 */
public static Multiset<Sequence> scanDatabaseToDetermineFrequencyOfSingleItems(final File inputFile)
		throws IOException {

	final Multiset<Sequence> singletons = HashMultiset.create();

	// for each line (transaction) until the end of file
	final LineIterator it = FileUtils.lineIterator(inputFile, "UTF-8");
	while (it.hasNext()) {

		final String line = it.nextLine();
		// if the line is a comment, is empty or is a
		// kind of metadata
		if (line.isEmpty() == true || line.charAt(0) == '#' || line.charAt(0) == '%' || line.charAt(0) == '@') {
			continue;
		}

		// split the line into items
		final String[] lineSplit = line.split(" ");
		// for each item
		final HashSet<Sequence> seenItems = new HashSet<>();
		for (final String itemString : lineSplit) {
			final int item = Integer.parseInt(itemString);
			if (item >= 0) { // ignore end of itemset/sequence tags
				final Sequence seq = new Sequence(item);
				PAMCore.recursiveSetOccurrence(seq, seenItems); // set
																// occurrence
				seenItems.add(seq); // add item to seen
			}
		}
		singletons.addAll(seenItems); // increase the support of the items
	}

	// close the input file
	LineIterator.closeQuietly(it);

	return singletons;
}
 
Example 6
Source File: KMeans.java    From jpmml-sklearn with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public ClusteringModel encodeModel(Schema schema){
	int[] shape = getClusterCentersShape();

	int numberOfClusters = shape[0];
	int numberOfFeatures = shape[1];

	List<? extends Number> clusterCenters = getClusterCenters();
	List<Integer> labels = getLabels();

	Multiset<Integer> labelCounts = HashMultiset.create();

	if(labels != null){
		labelCounts.addAll(labels);
	}

	List<Cluster> clusters = new ArrayList<>();

	for(int i = 0; i < numberOfClusters; i++){
		Cluster cluster = new Cluster(PMMLUtil.createRealArray(CMatrixUtil.getRow(clusterCenters, numberOfClusters, numberOfFeatures, i)))
			.setId(String.valueOf(i))
			.setSize((labelCounts.size () > 0 ? labelCounts.count(i) : null));

		clusters.add(cluster);
	}

	ComparisonMeasure comparisonMeasure = new ComparisonMeasure(ComparisonMeasure.Kind.DISTANCE, new SquaredEuclidean())
		.setCompareFunction(CompareFunction.ABS_DIFF);

	ClusteringModel clusteringModel = new ClusteringModel(MiningFunction.CLUSTERING, ClusteringModel.ModelClass.CENTER_BASED, numberOfClusters, ModelUtil.createMiningSchema(schema.getLabel()), comparisonMeasure, ClusteringModelUtil.createClusteringFields(schema.getFeatures()), clusters)
		.setOutput(ClusteringModelUtil.createOutput(FieldName.create("Cluster"), DataType.DOUBLE, clusters));

	return clusteringModel;
}
 
Example 7
Source File: Main.java    From angelix with MIT License 5 votes vote down vote up
private static Multiset<Node> selectComponents(Expression expression, Set<ProgramVariable> contextVariables) {
    Multiset<Node> components = HashMultiset.create();

    components.addAll(expression.getAllComponents());
    components.addAll(contextVariables);

    components.add(Library.AND);
    components.add(Library.OR);
    components.add(Library.NOT);

    components.add(Library.LE);
    components.add(Library.LT);
    components.add(Library.GT);
    components.add(Library.GE);
    components.add(Library.EQ);
    components.add(Library.NEQ);

    components.add(Library.ADD);
    components.add(Library.SUB);
    components.add(Library.MINUS);

    components.add(Library.ID(IntType.TYPE));
    components.add(Library.ID(BoolType.TYPE));

    components.add(Parameter.mkInt("parameter"));

    return components;
}
 
Example 8
Source File: BaseTest.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
protected static <T> void assertEqualsAsMultisets(
		Collection<T> expectedCollection, Collection<T> actualCollection) {

	Multiset<T> expecteds = HashMultiset.create();
	Multiset<T> actuals = HashMultiset.create();

	expecteds.addAll(expectedCollection);
	actuals.addAll(actualCollection);

	assertCollectionEquals(expecteds, actuals);
}
 
Example 9
Source File: SyntheticResultJsonService.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private ImmutableList<SyntheticMonitor> getAllSyntheticMonitors(String agentRollupId,
        long from, long to) throws Exception {
    Map<String, String> syntheticMonitorIds =
            syntheticResultRepository.getSyntheticMonitorIds(agentRollupId, from, to);
    Multiset<String> multiset = HashMultiset.create();
    multiset.addAll(syntheticMonitorIds.values());
    List<SyntheticMonitor> syntheticMonitors = Lists.newArrayList();
    for (Map.Entry<String, String> entry : syntheticMonitorIds.entrySet()) {
        String id = entry.getKey();
        String display = entry.getValue();
        if (multiset.count(entry.getValue()) > 1) {
            display += " (" + id + ")";
        }
        syntheticMonitors.add(ImmutableSyntheticMonitor.of(id, display));
    }
    if (to > clock.currentTimeMillis()) {
        // so that new synthetic monitors will show up right away
        List<SyntheticMonitorConfig> configs =
                configRepository.getSyntheticMonitorConfigs(agentRollupId);
        for (SyntheticMonitorConfig config : configs) {
            if (!syntheticMonitorIds.containsKey(config.getId())) {
                syntheticMonitors.add(ImmutableSyntheticMonitor.of(config.getId(),
                        MoreConfigDefaults.getDisplayOrDefault(config)));
            }
        }
    }
    return new SyntheticMonitorOrdering().immutableSortedCopy(syntheticMonitors);
}
 
Example 10
Source File: MultisetExpression.java    From gef with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public boolean addAll(Collection<? extends E> c) {
	final Multiset<E> multiset = get();
	return (multiset == null) ? EMPTY_MULTISET.addAll(c)
			: multiset.addAll(c);
}
 
Example 11
Source File: ObservableMultisetTests.java    From gef with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void replaceAll() {
	// initialize multiset with some values
	observable.add(1, 1);
	observable.add(2, 2);
	observable.add(3, 3);
	observable.add(4, 4);

	// prepare backup multiset
	Multiset<Integer> backupMultiset = HashMultiset.create();
	backupMultiset.add(1, 1);
	backupMultiset.add(2, 2);
	backupMultiset.add(3, 3);
	backupMultiset.add(4, 4);
	check(observable, backupMultiset);

	// register listeners
	registerListeners();

	// replaceAll
	invalidationListener.expect(1);
	multisetChangeListener.addAtomicExpectation();
	multisetChangeListener.addElementaryExpection(2, 1, 0); // decrease
															// count
	multisetChangeListener.addElementaryExpection(4, 4, 0); // remove
	multisetChangeListener.addElementaryExpection(3, 0, 3); // increase
															// count
	multisetChangeListener.addElementaryExpection(5, 0, 5); // add

	Multiset<Integer> toReplace = HashMultiset.create();
	toReplace.add(1);
	toReplace.add(2, 1);
	toReplace.add(3, 6);
	toReplace.add(5, 5);

	observable.replaceAll(toReplace);
	backupMultiset.clear();
	backupMultiset.addAll(toReplace);
	check(observable, backupMultiset);
	checkListeners();

	// replace with same contents (should not have any effect)
	invalidationListener.expect(0);
	observable.replaceAll(toReplace);
	check(observable, backupMultiset);
	checkListeners();
}