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 sdr.hamming() #163

Merged
merged 3 commits into from
Nov 19, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
29 changes: 29 additions & 0 deletions src/sdr/_measurement/_distance.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,32 @@ def euclidean(
y = np.asarray(y)
d = np.sqrt(np.sum(np.abs(x - y) ** 2, axis=axis))
return d


@export
def hamming(
x: npt.NDArray[np.int_],
y: npt.NDArray[np.int_],
axis: int | tuple[int, ...] | None = None,
) -> npt.NDArray[np.int_]:
r"""
Measures the Hamming distance between two signals $x[n]$ and $y[n]$.

$$d = \sum_{n=0}^{N-1} x[n] \oplus y[n]$$

Arguments:
x: The time-domain signal $x[n]$.
y: The time-domain signal $y[n]$.
axis: Axis or axes along which to compute the distance. The default is `None`, which computes the distance
across the entire array.

Returns:
The Hamming distance between $x[n]$ and $y[n]$.

Group:
measurement-distance
"""
x = np.asarray(x)
y = np.asarray(y)
d = np.sum(np.bitwise_xor(x, y), axis=axis)
return d
24 changes: 24 additions & 0 deletions tests/measurements/test_hamming.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import numpy as np

import sdr

X = np.array([[6, 5, 0, 0, 5], [0, 1, 5, 0, 3], [4, 3, 3, 0, 5]])
Y = np.array([[7, 5, 2, 4, 0], [0, 0, 4, 1, 5], [5, 0, 7, 5, 6]])


def test_axis_none():
d = sdr.hamming(X, Y)
assert d.shape == ()
assert d == 37


def test_axis_0():
d = sdr.hamming(X, Y, axis=0)
assert d.shape == (5,)
assert np.allclose(d, [2, 4, 7, 10, 14])


def test_axis_1():
d = sdr.hamming(X, Y, axis=1)
assert d.shape == (3,)
assert np.allclose(d, [12, 9, 16])