Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new DamerauLevenshtein... classes #84

Merged
merged 6 commits into from
Sep 18, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 24 additions & 6 deletions tests/test_edit/test_damerau_levenshtein.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@
# project
import textdistance


ALG = textdistance.DamerauLevenshtein


@pytest.mark.parametrize('left, right, expected', [
COMMON = [
('test', 'text', 1),
('test', 'tset', 1),
('test', 'qwy', 4),
Expand All @@ -24,15 +22,35 @@
('ab', 'ba', 1),
('ab', 'cde', 3),
('ab', 'ac', 1),
('ab', 'ba', 1),
('ab', 'bc', 2),
]


@pytest.mark.parametrize('left, right, expected', COMMON + [
('ab', 'bca', 3),
('abcd', 'bdac', 4),
])
def test_distance(left, right, expected):
def test_distance_restricted(left, right, expected):
actual = ALG(external=False)(left, right)
assert actual == expected

actual = ALG(external=True)(left, right)
assert actual == expected

actual = ALG()._pure_python(left, right)
actual = ALG()._pure_python_restricted(left, right)
assert actual == expected


@pytest.mark.parametrize('left, right, expected', COMMON + [
('ab', 'bca', 2),
('abcd', 'bdac', 3),
])
def test_distance_unrestricted(left, right, expected):
actual = ALG(external=False, restricted=False)(left, right)
assert actual == expected

actual = ALG(external=True, restricted=False)(left, right)
assert actual == expected

actual = ALG()._pure_python_unrestricted(left, right)
assert actual == expected
57 changes: 54 additions & 3 deletions textdistance/algorithms/edit_based.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,10 @@ class DamerauLevenshtein(_Base):
* substitution: ABC -> ABE, ADC, FBC..
* transposition: ABC -> ACB, BAC

If `restricted=False`, it will calculate unrestricted distance,
where the same character can be touched more than once.
So the distance between BA and ACB is 2: BA -> AB -> ACB.

https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance
"""

Expand All @@ -156,10 +160,12 @@ def __init__(
qval: int = 1,
test_func: TestFunc | None = None,
external: bool = True,
restricted: bool = True,
) -> None:
self.qval = qval
self.test_func = test_func or self._ident
self.external = external
self.restricted = restricted

def _numpy(self, s1: Sequence[T], s2: Sequence[T]) -> int:
# TODO: doesn't pass tests, need improve
Expand Down Expand Up @@ -194,11 +200,54 @@ def _numpy(self, s1: Sequence[T], s2: Sequence[T]) -> int:

return d[len(s1) - 1][len(s2) - 1]

def _pure_python(self, s1: Sequence[T], s2: Sequence[T]) -> int:
def _pure_python_unrestricted(self, s1: Sequence[T], s2: Sequence[T]) -> int:
"""https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance
"""
d: dict[tuple[int, int], int] = {}
da: defaultdict[T, int] = defaultdict(int)

len1 = len(s1)
len2 = len(s2)

maxdist = len1 + len2
d[-1, -1] = maxdist

# matrix
for i in range(len(s1) + 1):
d[i, -1] = maxdist
d[i, 0] = i
for j in range(len(s2) + 1):
d[-1, j] = maxdist
d[0, j] = j

for i, cs1 in enumerate(s1):
i += 1
db = 0
for j, cs2 in enumerate(s2):
j += 1
i1 = da[cs2]
j1 = db
if self.test_func(cs1, cs2):
cost = 0
db = j
else:
cost = 1

d[i, j] = min(
d[i - 1, j - 1] + cost, # substitution
d[i, j - 1] + 1, # insertion
d[i - 1, j] + 1, # deletion
d[i1 - 1, j1 - 1] + (i - i1) - 1 + (j - j1), # transposition
)
da[cs1] = i

return d[len1, len2]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this really correct? we write into d[i, j] which should be at most d[len1-1, len2-1] from my understanding.

Copy link
Member

@orsinium orsinium Sep 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't remember much about the algorithms, I can only rely on tests.

Copy link
Member

@orsinium orsinium Sep 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked the code. What a mess it is, oh my. We first set these values by doing iteration over range(len(s1) + 1) when initializing the matrix, And then when we do enumeration for i, cs1 in enumerate(s1):, we on the next line shift the index: i += 1 🧠 I'll try to clean it up a tiny bit.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is deliberate! The boundary values are needed, but are never modified later, as the algorithm looks at the preceding values in the array when calculating the new values. I tried to come up with a way of avoiding the i+=1 business, but I kept messing things up, so I decided to be somewhat non-Pythonic and stick to the algorithm as presented on Wikipedia!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to come up with a way of avoiding the i+=1 business, but I kept messing things up

Tip of the day: enumerate accepts an argument start, where you can specify the initial value. I've changed the code to use it. It became a bit slower, for some reason, but IMHO a bit more readable.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes I completely missed the += 1 before

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to come up with a way of avoiding the i+=1 business, but I kept messing things up

Tip of the day: enumerate accepts an argument start, where you can specify the initial value. I've changed the code to use it. It became a bit slower, for some reason, but IMHO a bit more readable.

Oh, how neat! Thanks for that tip. I agree, more readable is better.


def _pure_python_restricted(self, s1: Sequence[T], s2: Sequence[T]) -> int:
"""
https://www.guyrutenberg.com/2008/12/15/damerau-levenshtein-distance-in-python/
"""
d = {}
d: dict[tuple[int, int], int] = {}

# matrix
for i in range(-1, len(s1) + 1):
Expand Down Expand Up @@ -241,7 +290,9 @@ def __call__(self, s1: Sequence[T], s2: Sequence[T]) -> int:
# if numpy:
# return self._numpy(s1, s2)
# else:
return self._pure_python(s1, s2)
if self.restricted:
return self._pure_python_restricted(s1, s2)
return self._pure_python_unrestricted(s1, s2)


class JaroWinkler(_BaseSimilarity):
Expand Down
11 changes: 7 additions & 4 deletions textdistance/libraries.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,13 @@ class SameLengthTextLibrary(SameLengthLibrary, TextLibrary):
reg = prototype.register

alg = 'DamerauLevenshtein'
reg(alg, LibraryBase('abydos.distance', 'DamerauLevenshtein', presets={}, attr='dist_abs'))
reg(alg, LibraryBase('pyxdameraulevenshtein', 'damerau_levenshtein_distance'))
reg(alg, TextLibrary('jellyfish', 'damerau_levenshtein_distance'))
reg(alg, LibraryBase('rapidfuzz.distance.DamerauLevenshtein', 'distance'))
reg(alg, LibraryBase(
'abydos.distance', 'DamerauLevenshtein', presets={}, attr='dist_abs',
conditions=dict(restricted=False),
))
reg(alg, LibraryBase('pyxdameraulevenshtein', 'damerau_levenshtein_distance', conditions=dict(restricted=True)))
reg(alg, TextLibrary('jellyfish', 'damerau_levenshtein_distance', conditions=dict(restricted=False)))
reg(alg, LibraryBase('rapidfuzz.distance.DamerauLevenshtein', 'distance', conditions=dict(restricted=False)))
orsinium marked this conversation as resolved.
Show resolved Hide resolved

alg = 'Hamming'
reg(alg, LibraryBase('abydos.distance', 'Hamming', presets={}, attr='dist_abs'))
Expand Down