[
https://issues.apache.org/jira/browse/TEXT-155?focusedWorklogId=210453&page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel#worklog-210453
]
ASF GitHub Bot logged work on TEXT-155:
---------------------------------------
Author: ASF GitHub Bot
Created on: 09/Mar/19 04:09
Start Date: 09/Mar/19 04:09
Worklog Time Spent: 10m
Work Description: kinow commented on pull request #109: TEXT-155: Add a
generic IntersectionSimilarity measure
URL: https://github.com/apache/commons-text/pull/109#discussion_r263985577
##########
File path:
src/main/java/org/apache/commons/text/similarity/IntersectionSimilarity.java
##########
@@ -0,0 +1,197 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.text.similarity;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+/**
+ * Measures the intersection of two sets created from a pair of character
sequences.
+ *
+ * <p>It is assumed that the type {@code T} correctly conforms to the
requirements for storage
+ * within a {@link Set} or {@link HashMap}. Ideally the type is immutable and
implements
+ * {@link Object#equals(Object)} and {@link Object#hashCode()}.</p>
+ *
+ * @param <T> the type of the elements extracted from the character sequence
+ * @since 1.7
+ * @see Set
+ * @see HashMap
+ */
+public class IntersectionSimilarity<T> implements
SimilarityScore<IntersectionResult> {
+ /** The converter used to create the elements from the characters. */
+ private final Function<CharSequence, Collection<T>> converter;
+
+ // The following is adapted from commons-collections for a Bag.
+ // A Bag is a collection that can store the count of the number
+ // of copies of each element.
+
+ /**
+ * Mutable counter class for storing the count of elements.
+ */
+ private static class BagCount {
+ /** The count. This is initialised to 1 upon construction. */
+ int count = 1;
+ }
+
+ /**
+ * A minimal implementation of a Bag that can store elements and a count.
+ *
+ * <p>For the intended purpose the Bag does not have to be a {@link
Collection}. It does not
+ * even have to know its own size.
+ */
+ private class TinyBag {
+ /** The backing map. */
+ private final Map<T, BagCount> map;
+
+ /**
+ * Create a new tiny bag.
+ *
+ * @param initialCapacity the initial capacity
+ */
+ TinyBag(int initialCapacity) {
+ map = new HashMap<>(initialCapacity);
+ }
+
+ /**
+ * Adds a new element to the bag, incrementing its count in the
underlying map.
+ *
+ * @param object the object to add
+ */
+ void add(T object) {
+ final BagCount mut = map.get(object);
+ if (mut == null) {
+ map.put(object, new BagCount());
+ } else {
+ mut.count++;
+ }
+ }
+
+ /**
+ * Returns the number of occurrence of the given element in this bag by
+ * looking up its count in the underlying map.
+ *
+ * @param object the object to search for
+ * @return the number of occurrences of the object, zero if not found
+ */
+ int getCount(final Object object) {
+ final BagCount count = map.get(object);
+ if (count != null) {
+ return count.count;
+ }
+ return 0;
+ }
+
+ /**
+ * Returns a possibly parallel Stream of all the entries in the bag.
+ *
+ * @return the stream
+ */
+ Stream<Map.Entry<T, BagCount>> parallelStream() {
+ return map.entrySet().parallelStream();
+ }
Review comment:
Returning a `parallelStream` might be bad here I think. Instead we should
either default to normal stream, or give the user a way to choose whether to
use a normal or a parallel stream (example [discussion about
it](https://stackoverflow.com/questions/48471554/java-parallel-stream-use-or-not-to-use)
with some good references).
I had an issue with a parallel stream in a library some months ago, and took
a while to identify where the problem was (it involved returning gridded data
from an ArcGIS server in a JAXB web service in a legacy app being ported to
Java 8... not the best of the experiences troubleshooting that).
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]
Issue Time Tracking
-------------------
Worklog Id: (was: 210453)
Time Spent: 2h 50m (was: 2h 40m)
> Add a generic SetSimilarity measure
> -----------------------------------
>
> Key: TEXT-155
> URL: https://issues.apache.org/jira/browse/TEXT-155
> Project: Commons Text
> Issue Type: New Feature
> Affects Versions: 1.6
> Reporter: Alex D Herbert
> Priority: Minor
> Time Spent: 2h 50m
> Remaining Estimate: 0h
>
> The {{SimilarityScore<T>}} interface can be used to compute a generic result.
> I propose to add a class that can compute the intersection between two sets
> formed from the characters. The sets must be formed from the {{CharSequence}}
> input to the {{apply}} method using a {{Function<CharSequence, Set<T>>}} to
> convert the {{CharSequence}}. This function can be passed to the
> {{SimilarityScore<T>}} during construction.
> The result can then be computed to have the size of each set and the
> intersection.
> I have created an implementation that can compute the equivalent of the
> {{JaccardSimilary}} class by creating {{Set<Character>}} and also the
> F1-score using bigrams (pairs of characters) by creating {{Set<String>}}.
> This relates to
> [Text-126|https://issues.apache.org/jira/projects/TEXT/issues/TEXT-126] which
> suggested an algorithm for the Sorensen-Dice similarity, also known as the
> F1-score.
> Here is an example:
> {code:java}
> // Match the functionality of the JaccardSimilarity class
> Function<CharSequence, Set<Character>> converter = (cs) -> {
> final Set<Character> set = new HashSet<>();
> for (int i = 0; i < cs.length(); i++) {
> set.add(cs.charAt(i));
> }
> return set;
> };
> IntersectionSimilarity<Character> similarity = new
> IntersectionSimilarity<>(converter);
> IntersectionResult result = similarity.apply("something", "something else");
> {code}
> The result has the size of set A, set B and the intersection between them.
> This class was inspired by my look through the various similarity
> implementations. All of them except the {{CosineSimilarity}} perform single
> character matching between the input {{CharSequence}}s. The
> {{CosineSimilarity}} tokenises using whitespace to create words.
> This more generic type of implementation will allow a user to determine how
> to divide the {{CharSequence}} but to create the sets that are compared, e.g.
> single characters, words, bigrams, etc.
--
This message was sent by Atlassian JIRA
(v7.6.3#76005)