com.google.common.collect.HashMultiset Java Examples

The following examples show how to use com.google.common.collect.HashMultiset. 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: BankPlugin.java    From plugins with GNU General Public License v3.0 6 votes vote down vote up
private Multiset<Integer> getBankItemSet()
{
	ItemContainer itemContainer = client.getItemContainer(InventoryID.BANK);
	if (itemContainer == null)
	{
		return HashMultiset.create();
	}

	Multiset<Integer> set = HashMultiset.create();
	for (Item item : itemContainer.getItems())
	{
		if (item.getId() != ItemID.BANK_FILLER)
		{
			set.add(item.getId(), item.getQuantity());
		}
	}
	return set;
}
 
Example #3
Source File: CountWordOccurrencesInFile.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
/**
 * Example was modified from the guava site to remove 
 * periods
 * 
 * @throws IOException
 */
@Test 
public void count_distinct_words_in_file_guava () throws IOException {

	File file = new File(sourceFileURI);
	
	Multiset<String> wordOccurrences = HashMultiset.create(
	  Splitter.on(CharMatcher.WHITESPACE)
	  	.trimResults(CharMatcher.is('.'))
	    .omitEmptyStrings()
	    .split(Files.asCharSource(file, Charsets.UTF_8).read()));

	
	logger.info(wordOccurrences);

	assertEquals(80, wordOccurrences.elementSet().size());
}
 
Example #4
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if {@code atLeastM} of the expressions in the given column are the same kind.
 */
private static boolean expressionsAreParallel(
        List<List<ExpressionTree>> rows, int column, int atLeastM) {
    Multiset<Tree.Kind> nodeTypes = HashMultiset.create();
    for (List<? extends ExpressionTree> row : rows) {
        if (column >= row.size()) {
            continue;
        }
        nodeTypes.add(row.get(column).getKind());
    }
    for (Multiset.Entry<Tree.Kind> nodeType : nodeTypes.entrySet()) {
        if (nodeType.getCount() >= atLeastM) {
            return true;
        }
    }
    return false;
}
 
Example #5
Source File: ImmutableSortedKeyListMultimapTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void emptyMultimapReads() {
  Multimap<String, Integer> multimap = ImmutableSortedKeyListMultimap.of();
  assertThat(multimap).doesNotContainKey("foo");
  assertThat(multimap.containsValue(1)).isFalse();
  assertThat(multimap).doesNotContainEntry("foo", 1);
  assertThat(multimap.entries()).isEmpty();
  assertThat(multimap.equals(ArrayListMultimap.create())).isTrue();
  assertThat(multimap).valuesForKey("foo").isEqualTo(Collections.emptyList());
  assertThat(multimap.hashCode()).isEqualTo(0);
  assertThat(multimap).isEmpty();
  assertThat(multimap.keys()).isEqualTo(HashMultiset.create());
  assertThat(multimap).isEmpty();
  assertThat(multimap).isEmpty();
  assertThat(multimap).isEmpty();
  assertThat(multimap.toString()).isEqualTo("{}");
}
 
Example #6
Source File: MultisetGwtTest.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
public void testSerialization() {
    BeanWithMultisetTypes bean = new BeanWithMultisetTypes();

    List<String> list = Arrays.asList( "foo", "abc", null, "abc" );
    List<String> listWithNonNull = Arrays.asList( "foo", "abc", "bar", "abc" );

    bean.multiset = LinkedHashMultiset.create( list );
    bean.hashMultiset = HashMultiset.create( Arrays.asList( "abc", "abc" ) );
    bean.linkedHashMultiset = LinkedHashMultiset.create( list );
    bean.sortedMultiset = TreeMultiset.create( listWithNonNull );
    bean.treeMultiset = TreeMultiset.create( listWithNonNull );
    bean.immutableMultiset = ImmutableMultiset.copyOf( listWithNonNull );
    bean.enumMultiset = EnumMultiset.create( Arrays.asList( AlphaEnum.B, AlphaEnum.A, AlphaEnum.D, AlphaEnum.A ) );

    String expected = "{" +
            "\"multiset\":[\"foo\",\"abc\",\"abc\",null]," +
            "\"hashMultiset\":[\"abc\",\"abc\"]," +
            "\"linkedHashMultiset\":[\"foo\",\"abc\",\"abc\",null]," +
            "\"sortedMultiset\":[\"abc\",\"abc\",\"bar\",\"foo\"]," +
            "\"treeMultiset\":[\"abc\",\"abc\",\"bar\",\"foo\"]," +
            "\"immutableMultiset\":[\"foo\",\"abc\",\"abc\",\"bar\"]," +
            "\"enumMultiset\":[\"A\",\"A\",\"B\",\"D\"]" +
            "}";

    assertEquals( expected, BeanWithMultisetTypesMapper.INSTANCE.write( bean ) );
}
 
Example #7
Source File: TestBucketBalancer.java    From presto with Apache License 2.0 6 votes vote down vote up
private static void assertBalancing(BucketBalancer balancer, int expectedMoves)
{
    int actualMoves = balancer.balance();
    assertEquals(actualMoves, expectedMoves);

    // check that number of buckets per node is within bounds
    ClusterState clusterState = balancer.fetchClusterState();
    for (Distribution distribution : clusterState.getDistributionAssignments().keySet()) {
        Multiset<String> allocationCounts = HashMultiset.create();
        clusterState.getDistributionAssignments().get(distribution).stream()
                .map(BucketAssignment::getNodeIdentifier)
                .forEach(allocationCounts::add);

        double bucketsPerNode = (1.0 * allocationCounts.size()) / clusterState.getActiveNodes().size();
        for (String node : allocationCounts) {
            assertGreaterThanOrEqual(allocationCounts.count(node), (int) Math.floor(bucketsPerNode), node + " has fewer buckets than expected");
            assertLessThanOrEqual(allocationCounts.count(node), (int) Math.ceil(bucketsPerNode), node + " has more buckets than expected");
        }
    }

    // check stability
    assertEquals(balancer.balance(), 0);
}
 
Example #8
Source File: PipelineQueryIT.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleStatementPattern() throws Exception {
    // Insert data
    insert(OWL.THING, RDF.TYPE, OWL.CLASS);
    insert(FOAF.PERSON, RDF.TYPE, OWL.CLASS, 1);
    insert(FOAF.PERSON, RDFS.SUBCLASSOF, OWL.THING);
    insert(VF.createIRI("urn:Alice"), RDF.TYPE, FOAF.PERSON);
    dao.flush();
    // Define query and expected results
    final String query = "SELECT * WHERE {\n"
            + "  ?individual a ?type .\n"
            + "}";
    final List<String> varNames = Arrays.asList("individual", "type");
    final Multiset<BindingSet> expectedSolutions = HashMultiset.create();
    expectedSolutions.add(new ListBindingSet(varNames, OWL.THING, OWL.CLASS));
    expectedSolutions.add(new ListBindingSet(varNames, FOAF.PERSON, OWL.CLASS));
    expectedSolutions.add(new ListBindingSet(varNames, VF.createIRI("urn:Alice"), FOAF.PERSON));
    // Execute pipeline and verify results
    testPipelineQuery(query, expectedSolutions);
}
 
Example #9
Source File: TupleStoreManagerRegistry.java    From bboxdb with Apache License 2.0 6 votes vote down vote up
/**
 * Get the lowest utilized data storage location
 * @return
 */
public String getLocationLowestUtilizedDataLocation() {

	final Multiset<String> usage = HashMultiset.create();

	// Put every location into the table (even unused ones)
	storages.keySet().forEach(s -> usage.add(s));

	// Add SSTables per storage usage
	tupleStoreLocations.values().forEach(v -> usage.add(v));

	// Return the lowest usage
	return usage.entrySet().stream()
		.reduce((a,b) -> a.getCount() < b.getCount() ? a : b)
		.get()
		.getElement();
}
 
Example #10
Source File: GuavaHashMultisetTest.java    From java_in_examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    // Parse text to separate words
    String INPUT_TEXT = "Hello World! Hello All! Hi World!";
    // Create Multiset
    Multiset<String> multiset = HashMultiset.create(Arrays.asList(INPUT_TEXT.split(" ")));

    // Print count words
    System.out.println(multiset); // print [Hi, Hello x 2, World! x 2, All!] - in random orders
    // Print all unique words
    System.out.println(multiset.elementSet());    // print [Hi, Hello, World!, All!] - in random orders

    // Print count occurrences of words
    System.out.println("Hello = " + multiset.count("Hello"));    // print 2
    System.out.println("World = " + multiset.count("World!"));    // print 2
    System.out.println("All = " + multiset.count("All!"));    // print 1
    System.out.println("Hi = " + multiset.count("Hi"));    // print 1
    System.out.println("Empty = " + multiset.count("Empty"));    // print 0

    // Print count all words
    System.out.println(multiset.size());    //print 6

    // Print count unique words
    System.out.println(multiset.elementSet().size());    //print 4
}
 
Example #11
Source File: TrainsModel.java    From Rails with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Make an abbreviated list of trains, like "2(6) 3(5)" etc, to show in the
 * IPO.
 */
public String makeListOfTrainCards() {
    if (trainCards.isEmpty()) return "";

    // create a bag with train types
    Multiset<TrainCardType> trainCardTypes = HashMultiset.create();
    for (TrainCard card:trainCards) {
        trainCardTypes.add(card.getType());
    }
    
    StringBuilder b = new StringBuilder();
    
    for (TrainCardType cardType:ImmutableSortedSet.copyOf(trainCardTypes.elementSet())) {
        if (b.length() > 0) b.append(" ");
        b.append(cardType.toText()).append("(");
        if (cardType.hasInfiniteQuantity()) {
            b.append("+");
        } else {
            b.append(trainCardTypes.count(cardType));
        }
        b.append(")");
    }

    return b.toString();
}
 
Example #12
Source File: AccessNetworkLayout.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean classify(Device device) {
    if (!super.classify(device)) {
        String role;

        // Does the device have any hosts attached? If not, it's a spine
        if (hostService.getConnectedHosts(device.id()).isEmpty()) {
            // Does the device have any aggregate links to other devices?
            Multiset<DeviceId> destinations = HashMultiset.create();
            linkService.getDeviceEgressLinks(device.id()).stream()
                    .map(l -> l.dst().deviceId()).forEach(destinations::add);

            // If yes, it's the main spine; otherwise it's an aggregate spine
            role = destinations.entrySet().stream().anyMatch(e -> e.getCount() > 1) ?
                    SPINE : AGGREGATION;
        } else {
            // Does the device have any multi-home hosts attached?
            // If yes, it's a service leaf; otherwise it's an access leaf
            role = hostService.getConnectedHosts(device.id()).stream()
                    .map(Host::locations).anyMatch(s -> s.size() > 1) ?
                    LEAF : ACCESS;
        }
        deviceCategories.put(role, device.id());
    }
    return true;
}
 
Example #13
Source File: SwitchedVlanPropertiesAnswerer.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Gets properties of switched vlans.
 *
 * @param ctxt context in which to apply {@code interfacesSpecifier}
 * @param configurations configuration to use in extractions
 * @param nodes the set of nodes to consider
 * @param interfaceSpecifier Specifies which interfaces to consider
 * @param columns a map from column name to {@link ColumnMetadata}
 * @return A multiset of {@link Row}s where each row corresponds to a node/vlan pair and columns
 *     correspond to property values.
 */
public static Multiset<Row> getProperties(
    SpecifierContext ctxt,
    Map<String, Configuration> configurations,
    Set<String> nodes,
    InterfaceSpecifier interfaceSpecifier,
    boolean excludeShutInterfaces,
    IntegerSpace vlans,
    Map<String, ColumnMetadata> columns) {
  Multiset<Row> rows = HashMultiset.create();
  for (String node : nodes) {
    Map<Integer, ImmutableSet.Builder<NodeInterfacePair>> switchedVlanInterfaces =
        new HashMap<>();
    ImmutableMap.Builder<Integer, Integer> vlanVnisBuilder = ImmutableMap.builder();
    computeNodeVlanProperties(
        ctxt,
        configurations.get(node),
        interfaceSpecifier,
        excludeShutInterfaces,
        vlans,
        switchedVlanInterfaces,
        vlanVnisBuilder);
    populateNodeRows(node, switchedVlanInterfaces, vlanVnisBuilder, columns, rows);
  }
  return rows;
}
 
Example #14
Source File: EnumerableDefaults.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Produces the set difference of two sequences by
 * using the specified {@code EqualityComparer<TSource>} to compare
 * values, using {@code all} to indicate whether to eliminate duplicates.
 */
public static <TSource> Enumerable<TSource> except(
    Enumerable<TSource> source0, Enumerable<TSource> source1,
    EqualityComparer<TSource> comparer, boolean all) {
  if (comparer == Functions.identityComparer()) {
    return except(source0, source1, all);
  }
  Collection<Wrapped<TSource>> collection = all ? HashMultiset.create() : new HashSet<>();
  Function1<TSource, Wrapped<TSource>> wrapper = wrapperFor(comparer);
  source0.select(wrapper).into(collection);
  try (Enumerator<Wrapped<TSource>> os =
           source1.select(wrapper).enumerator()) {
    while (os.moveNext()) {
      Wrapped<TSource> o = os.current();
      collection.remove(o);
    }
  }
  Function1<Wrapped<TSource>, TSource> unwrapper = unwrapper();
  return Linq4j.asEnumerable(collection).select(unwrapper);
}
 
Example #15
Source File: LootTrackerPlugin.java    From runelite with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void processInventoryLoot(String event, LootRecordType lootRecordType, ItemContainer inventoryContainer, Collection<ItemStack> groundItems)
{
	if (inventorySnapshot != null)
	{
		Multiset<Integer> currentInventory = HashMultiset.create();
		Arrays.stream(inventoryContainer.getItems())
			.forEach(item -> currentInventory.add(item.getId(), item.getQuantity()));

		groundItems.stream()
			.forEach(item -> currentInventory.add(item.getId(), item.getQuantity()));

		final Multiset<Integer> diff = Multisets.difference(currentInventory, inventorySnapshot);

		List<ItemStack> items = diff.entrySet().stream()
			.map(e -> new ItemStack(e.getElement(), e.getCount(), client.getLocalPlayer().getLocalLocation()))
			.collect(Collectors.toList());

		addLoot(event, -1, lootRecordType, items);

		inventorySnapshot = null;
	}
}
 
Example #16
Source File: AbstractVisualPart.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void attachAnchored(IVisualPart<? extends Node> anchored) {
	// determine the viewer before adding the anchored
	IViewer oldViewer = getViewer();

	// register if we obtain a link to the viewer
	HashMultiset<IVisualPart<? extends Node>> newAnchoreds = HashMultiset
			.create(anchoreds);
	newAnchoreds.add(anchored);
	IViewer newViewer = determineViewer(getParent(), newAnchoreds);

	// unregister from old viewer in case we were registered (oldViewer !=
	// null) and the viewer changes (newViewer != oldViewer)
	if (oldViewer != null && newViewer != oldViewer) {
		oldViewer.unsetAdapter(this);
	}

	// detach anchoreds (and fire change notifications)
	anchoreds.add(anchored);

	// if we obtain a link to the viewer then register at new viewer
	if (newViewer != null && newViewer != oldViewer) {
		newViewer.setAdapter(this,
				String.valueOf(System.identityHashCode(this)));
	}
}
 
Example #17
Source File: EdgesAnswerer.java    From batfish with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static Multiset<Row> getLayer1Edges(
    Set<String> includeNodes,
    Set<String> includeRemoteNodes,
    @Nullable Layer1Topology layer1Topology) {
  if (layer1Topology == null) {
    return HashMultiset.create();
  }
  return layer1Topology.getGraph().edges().stream()
      .filter(
          layer1Edge ->
              includeNodes.contains(layer1Edge.getNode1().getHostname())
                  && includeRemoteNodes.contains(layer1Edge.getNode2().getHostname()))
      .map(EdgesAnswerer::layer1EdgeToRow)
      .collect(Collectors.toCollection(HashMultiset::create));
}
 
Example #18
Source File: TopologicalSorter.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Sorts the list of triplesMapBuilders
 * Taken from https://en.wikipedia.org/wiki/Topological_sorting#Depth-first_search
 *
 * <p>
 *   L ← Empty list that will contain the sorted nodes
 *   while there are unvisited nodes do
 *      select an unvisited node current
 *      visit(current, L)
 * </p>
 *
 * @param input the original list of triplesMapBuilders
 * @param lookup a lookup table to link URI's to their tripleMap objects
 * @param onCycle code to handle a cycle if it occurs
 * @param errorConsumer code to handle errors reported by this method (i.e. log it, throw it, do what you want)
 * @return the sorted list of builders
 */
public static LinkedList<TriplesMapBuilder> topologicalSort(List<TriplesMapBuilder> input,
                                                            Map<String, TriplesMapBuilder> lookup,
                                                            TopologicalSorter.CycleConsumer onCycle,
                                                            Consumer<String> errorConsumer) {
  Set<TriplesMapBuilder> unvisited = input.stream().collect(Collectors.toSet()); //copy so we don't modify the input

  // L ← Empty list that will contain the sorted nodes
  LinkedList<TriplesMapBuilder> result = Lists.newLinkedList();

  // while there are unvisited nodes do
  while (!unvisited.isEmpty()) {
    // select an unvisited node n
    TriplesMapBuilder current = unvisited.iterator().next();
    // visit(n)
    sortStep(current, result, HashMultiset.create(), lookup, unvisited, onCycle, errorConsumer);
  }

  return result;
}
 
Example #19
Source File: ApplicationMasterService.java    From twill with Apache License 2.0 6 votes vote down vote up
/**
 * Handling containers that are completed.
 */
private void handleCompleted(List<YarnContainerStatus> completedContainersStatuses) {
  Multiset<String> restartRunnables = HashMultiset.create();
  for (YarnContainerStatus status : completedContainersStatuses) {
    LOG.info("Container {} completed with {}:{}.",
             status.getContainerId(), status.getState(), status.getDiagnostics());
    runningContainers.handleCompleted(status, restartRunnables);
  }

  for (Multiset.Entry<String> entry : restartRunnables.entrySet()) {
    LOG.info("Re-request container for {} with {} instances.", entry.getElement(), entry.getCount());
    runnableContainerRequests.add(createRunnableContainerRequest(entry.getElement(),  entry.getCount()));
  }

  // For all runnables that needs to re-request for containers, update the expected count timestamp
  // so that the EventHandler would triggered with the right expiration timestamp.
  expectedContainers.updateRequestTime(restartRunnables.elementSet());
}
 
Example #20
Source File: Rebanker.java    From easyccg with MIT License 6 votes vote down vote up
private void writeCatList(Multiset<Category> cats, File outputFile) throws IOException {
  Multiset<Category> catsNoPPorPRfeatures = HashMultiset.create();
  for (Category cat : cats) {
    catsNoPPorPRfeatures.add(cat.dropPPandPRfeatures());
  }
  FileWriter fw = new FileWriter(outputFile.getAbsoluteFile());
  BufferedWriter bw = new BufferedWriter(fw);
  
  
  int categories = 0;
  for (Category type : Multisets.copyHighestCountFirst(cats).elementSet()) {
    if (catsNoPPorPRfeatures.count(type.dropPPandPRfeatures()) >= 10) {
      bw.write(type.toString());
      bw.newLine();
      categories++;
    }
  }
  System.out.println("Number of cats occurring 10 times: " + categories);
  
  
  bw.flush();
  bw.close();
  

}
 
Example #21
Source File: CollectReadCounts.java    From gatk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void onTraversalStart() {
    validateArguments();

    metadata = MetadataUtils.fromHeader(getHeaderForReads(), Metadata.Type.SAMPLE_LOCATABLE);
    final SAMSequenceDictionary sequenceDictionary = getBestAvailableSequenceDictionary();
    //this check is currently redundant, since the master dictionary is taken from the reads;
    //however, if any other dictionary is added in the future, such a check should be performed
    if (!CopyNumberArgumentValidationUtils.isSameDictionary(metadata.getSequenceDictionary(), sequenceDictionary)) {
        logger.warn("Sequence dictionary in BAM does not match the master sequence dictionary.");
    }

    intervals = intervalArgumentCollection.getIntervals(sequenceDictionary);
    intervalMultiset = HashMultiset.create(intervals.size());

    logger.info("Collecting read counts...");
}
 
Example #22
Source File: TestTreeBoundedSynthesis.java    From angelix with MIT License 6 votes vote down vote up
@Test
public void testSimpleITE() {
    Multiset<Node> components = HashMultiset.create();
    components.add(BoolConst.TRUE);
    components.add(IntConst.of(0));
    components.add(IntConst.of(1));
    components.add(Library.ITE);

    ArrayList<TestCase> testSuite = new ArrayList<>();
    Map<ProgramVariable, Node> assignment1 = new HashMap<>();
    TestCase testCase1 = TestCase.ofAssignment(assignment1, IntConst.of(0));
    testCase1.setId("t1");
    testSuite.add(testCase1);

    Synthesis synthesizerWithForbidden = new Synthesis(new BoundedShape(3, IntType.TYPE), new TreeBoundedEncoder());
    Optional<Pair<Expression, Map<Parameter, Constant>>> result = synthesizerWithForbidden.synthesize(testSuite, components);
    assertTrue(result.isPresent());
}
 
Example #23
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 6 votes vote down vote up
/** Returns true if {@code atLeastM} of the expressions in the given column are the same kind. */
private static boolean expressionsAreParallel(
    List<List<ExpressionTree>> rows, int column, int atLeastM) {
  Multiset<Tree.Kind> nodeTypes = HashMultiset.create();
  for (List<? extends ExpressionTree> row : rows) {
    if (column >= row.size()) {
      continue;
    }
    // Treat UnaryTree expressions as their underlying type for the comparison (so, for example
    // -ve and +ve numeric literals are considered the same).
    if (row.get(column) instanceof UnaryTree) {
      nodeTypes.add(((UnaryTree) row.get(column)).getExpression().getKind());
    } else {
      nodeTypes.add(row.get(column).getKind());
    }
  }
  for (Multiset.Entry<Tree.Kind> nodeType : nodeTypes.entrySet()) {
    if (nodeType.getCount() >= atLeastM) {
      return true;
    }
  }
  return false;
}
 
Example #24
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 #25
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 #26
Source File: ObservableMultisetTests.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void remove() {
	// initialize multiset with some values
	observable.add(1, 1);
	observable.add(2, 2);
	observable.add(3, 3);

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

	// register listeners
	registerListeners();

	// remove (first occurrence of) value
	invalidationListener.expect(1);
	multisetChangeListener.addAtomicExpectation();
	multisetChangeListener.addElementaryExpection(2, 1, 0);
	assertEquals(backupMultiset.remove(2), observable.remove(2));
	check(observable, backupMultiset);
	checkListeners();

	// remove (second occurrence of) value
	invalidationListener.expect(1);
	multisetChangeListener.addAtomicExpectation();
	multisetChangeListener.addElementaryExpection(2, 1, 0);
	assertEquals(backupMultiset.remove(2), observable.remove(2));
	check(observable, backupMultiset);
	checkListeners();

	// remove not contained value (no change expected)
	assertEquals(backupMultiset.remove(2), observable.remove(2));
	check(observable, backupMultiset);
	checkListeners();
}
 
Example #27
Source File: ObservableMultisetTests.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void addAll() {
	// prepare backup multiset
	Multiset<Integer> backupMultiset = HashMultiset.create();
	check(observable, backupMultiset);

	// register listeners
	registerListeners();

	// add a collection with three values
	invalidationListener.expect(1);
	multisetChangeListener.addAtomicExpectation();
	multisetChangeListener.addElementaryExpection(1, 0, 1);
	multisetChangeListener.addElementaryExpection(2, 0, 2);
	multisetChangeListener.addElementaryExpection(3, 0, 3);
	Multiset<Integer> toAdd = HashMultiset.create();
	toAdd.add(1);
	toAdd.add(2, 2);
	toAdd.add(3, 3);
	assertEquals(backupMultiset.addAll(toAdd), observable.addAll(toAdd));
	check(observable, backupMultiset);
	checkListeners();

	// add another collection with three values
	invalidationListener.expect(1);
	multisetChangeListener.addAtomicExpectation();
	multisetChangeListener.addElementaryExpection(2, 0, 2);
	multisetChangeListener.addElementaryExpection(4, 0, 3);
	toAdd = HashMultiset.create();
	toAdd.add(2, 2);
	toAdd.add(4, 3);
	assertEquals(backupMultiset.addAll(toAdd), observable.addAll(toAdd));
	check(observable, backupMultiset);
	checkListeners();
}
 
Example #28
Source File: MostFrequentCharInString.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void most_frequent_char_guava() throws IOException {

	Multiset<String> frequentCharacters = HashMultiset.create(Splitter
			.fixedLength(1).split(sentence.toLowerCase()));

	for (Entry<String> item : frequentCharacters.entrySet()) {
		System.out.println(item.getElement() + ":" + item.getCount());
	}

	assertEquals(7, frequentCharacters.count("e"), 0);
}
 
Example #29
Source File: SchemaSamplerTest.java    From log-synth with Apache License 2.0 5 votes vote down vote up
@Test
public void testInt() throws IOException {
    //noinspection UnstableApiUsage
    SchemaSampler s = new SchemaSampler(Resources.asCharSource(Resources.getResource("schema001.json"), Charsets.UTF_8).read());
    Multiset<String> counts = HashMultiset.create();
    for (int i = 0; i < 10000; i++) {
        counts.add(s.sample().get("size").asText());
    }
    for (int i = 10; i < 99; i++) {
        Assert.assertTrue(counts.elementSet().contains(i + ""));
    }
    assertEquals(99 - 10, counts.elementSet().size());
}
 
Example #30
Source File: DiscreteElementwiseConditionalDistribution.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Add a single element to the CPD given the context.
 * 
 * @param element
 * @param given
 */
public void addElement(final A element, final B given) {
	final Multiset<A> elements;

	if (!table.containsKey(given)) {
		elements = HashMultiset.create();
		table.put(given, elements);
	} else {
		elements = table.get(given);
	}

	elements.add(element);
}