legit-hashes 0.2.0

Versioned similarity hashes of images and text, and MinHash set signatures, with index keys for finding near matches
Documentation
//! `minhash-v1`, the set signature of datasketch's current default, its feature hash and its
//! permutation table.

use sha1::{Digest, Sha1};

use crate::{Result, Signature, SignatureAlgorithm, shingles_v1};

/// Make the `minhash-v1` signature of a set of features, Broder's MinHash as the Python library
/// datasketch computes it by default since its version 2.0.0.
///
/// Choose it for new data. To agree with signatures datasketch made before 2.0.0, or with its
/// `scheme="legacy"`, choose [`minhash_legacy_v1`](crate::minhash_legacy_v1) instead. The two
/// definitions' signatures never compare, merge or parse as each other.
///
/// The definition, frozen:
///
/// 1. The features are byte strings, and form a set: adding a feature again changes nothing, and
///    order doesn't matter.
/// 2. Hash each feature's bytes with SHA-1 and take the first four bytes of the digest as a
///    little-endian `u32`, `h`. This is datasketch's `sha1_hash32`. SHA-1 serves only as a
///    well-mixed feature hash here, not as a security measure: anyone can make features collide.
/// 3. Mix `h` once with MurmurHash3's 32-bit finalizer, in wrapping unsigned 32-bit arithmetic:
///    `h ^= h >> 16`, `h ×= 0x85ebca6b`, `h ^= h >> 13`, `h ×= 0xc2b2ae35`, `h ^= h >> 16`. This is
///    datasketch's `_fmix(h, 32)`, a bijection on 32-bit values.
/// 4. For each of 128 permutations `(a, b)`, in order, compute `p = (a × h + b) mod 2^32`, in
///    wrapping unsigned 32-bit arithmetic. Every `a` is odd, so each permutation is a bijection on
///    32-bit values. The 128 pairs are the ones datasketch draws from NumPy's legacy generator,
///    `RandomState(1)`: 128 values `k` from `[0, 2^31)` as `uint32`, each giving `a = 2k + 1`, then
///    128 values `b` from `[0, 2^32)`. The crate holds them as a table, generated from datasketch
///    2.0.0, never computed at run time.
/// 5. Value `i` of the signature is the smallest `p` of permutation `i` over every feature. With
///    no features, every value is `u32::MAX`: see [`Signature::is_empty`].
///
/// For the same features, given as bytes, this is value for value the `digest()` of datasketch
/// 2.0.0's default `MinHash(num_perm=128, seed=1)`, whose scheme is `affine32`. Releases of
/// datasketch before 2.0.0 don't compute it.
///
/// Because each permutation is a bijection, it adds no collisions of its own, which is why
/// datasketch made this construction its default: the legacy one's folding of 61 bits into 32
/// does. What remains on very large sets is the floor every 32-bit feature hash sets, when
/// different features get the same `h`: datasketch puts it at about +0.001 at 10 million features
/// per set, +0.01 at 100 million and +0.12 at a billion. An affine map is not proven min-wise
/// independent: as datasketch says, the estimator's accuracy rests on measurement, which the
/// crate's tests repeat on seeded sets.
///
/// ```
/// use legit_hashes::minhash_v1;
///
/// let first = minhash_v1(["stored", "hashes", "outlive", "the", "code"]);
/// let second = minhash_v1(["stored", "hashes", "outlive", "the", "program"]);
/// // Four features shared of six in all: a Jaccard similarity of 0.67...
/// assert!((first.similarity(&second)? - 4.0 / 6.0).abs() < 0.2);
/// # Ok::<(), legit_hashes::Error>(())
/// ```
#[must_use]
pub fn minhash_v1<F: AsRef<[u8]>>(features: impl IntoIterator<Item = F>) -> Signature {
    let mut signature = MinHashV1::new();
    for feature in features {
        signature.add(feature);
    }
    signature.finish()
}

/// Make the `minhash-v1` signature of the character shingles of `text`, from
/// [`shingles_v1`](crate::shingles_v1) with `size`.
///
/// Shingles of 5 characters are a sound starting point for messages and documents: a changed word
/// or letter, or changed spacing, touches only the few shingles around it. The crate changes no
/// character, so normalise the text first, in the application, if case, runs of whitespace or
/// Unicode form shouldn't count: lower-case it, collapse whitespace and apply NFC or NFKC. A frozen
/// definition can't depend on a Unicode version's tables, so the crate doesn't.
///
/// ```
/// use legit_hashes::minhash_v1_shingles;
///
/// let original = minhash_v1_shingles("Your parcel is waiting: confirm your address today.", 5)?;
/// let edited = minhash_v1_shingles("Your parcel is waiting: confirm your adress today!", 5)?;
/// let other = minhash_v1_shingles("The committee meets on the second Tuesday of each month.", 5)?;
/// assert!(original.similarity(&edited)? > original.similarity(&other)?);
/// # Ok::<(), legit_hashes::Error>(())
/// ```
///
/// # Errors
///
/// Returns [`Error::ShingleSize`](crate::Error::ShingleSize) when `size` is 0.
pub fn minhash_v1_shingles(text: &str, size: usize) -> Result<Signature> {
    Ok(minhash_v1(shingles_v1(text, size)?))
}

/// A `minhash-v1` signature being built a feature at a time, for features that arrive in parts.
///
/// [`minhash_v1`] holds the definition.
///
/// ```
/// use legit_hashes::{MinHashV1, minhash_v1};
///
/// let mut signature = MinHashV1::new();
/// for feature in ["a", "b", "a"] {
///     signature.add(feature);
/// }
/// assert_eq!(signature.finish(), minhash_v1(["b", "a"]));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MinHashV1 {
    values: [u32; 128],
}

impl MinHashV1 {
    /// Start a signature with no features.
    ///
    /// ```
    /// use legit_hashes::MinHashV1;
    ///
    /// assert!(MinHashV1::new().finish().is_empty());
    /// ```
    #[must_use]
    pub const fn new() -> Self {
        Self {
            values: [u32::MAX; 128],
        }
    }

    /// Add one feature, the bytes of `feature`. Adding a feature that's already there changes
    /// nothing.
    ///
    /// ```
    /// use legit_hashes::MinHashV1;
    ///
    /// let mut signature = MinHashV1::new();
    /// signature.add(b"\xff\xfe");
    /// signature.add("text");
    /// assert!(!signature.finish().is_empty());
    /// ```
    pub fn add(&mut self, feature: impl AsRef<[u8]>) {
        let h = fmix32(sha1_hash32(feature.as_ref()));
        for (value, &(a, b)) in self.values.iter_mut().zip(&PERMUTATIONS) {
            *value = (*value).min(a.wrapping_mul(h).wrapping_add(b));
        }
    }

    /// The signature of the features added so far.
    ///
    /// ```
    /// use legit_hashes::{MinHashV1, minhash_v1};
    ///
    /// let mut signature = MinHashV1::new();
    /// signature.add("a");
    /// assert_eq!(signature.finish(), minhash_v1(["a"]));
    /// ```
    #[must_use]
    pub const fn finish(&self) -> Signature {
        Signature::from_array(SignatureAlgorithm::MinHashV1, self.values)
    }
}

impl Default for MinHashV1 {
    /// Start a signature with no features, as [`new`](Self::new) does.
    fn default() -> Self {
        Self::new()
    }
}

/// datasketch's `sha1_hash32`: the first four bytes of the SHA-1 digest of `feature`, read
/// little-endian. Both MinHash definitions hash features with it.
pub(crate) fn sha1_hash32(feature: &[u8]) -> u32 {
    let digest: [u8; 20] = Sha1::digest(feature).into();
    let [d0, d1, d2, d3, ..] = digest;
    u32::from_le_bytes([d0, d1, d2, d3])
}

/// MurmurHash3's 32-bit finalizer, datasketch's `_fmix(h, 32)`.
const fn fmix32(mut h: u32) -> u32 {
    h ^= h >> 16;
    h = h.wrapping_mul(0x85eb_ca6b);
    h ^= h >> 13;
    h = h.wrapping_mul(0xc2b2_ae35);
    h ^ (h >> 16)
}

/// The 128 permutations `(a, b)` of `minhash-v1`, in order: the parameters datasketch draws for
/// its default `MinHash(num_perm=128, seed=1)`, whose scheme is `affine32`.
///
/// Printed by `tools/hash-ref/capture_minhash.py --table affine32` in the repository, from
/// datasketch 2.0.0, which the same script checks against this table. Frozen with `minhash-v1`.
const PERMUTATIONS: [(u32, u32); 128] = [
    (0xd583e84b, 0x0cc9bff8),
    (0xfe8f01d7, 0xc3f6d4fd),
    (0x70ce5f19, 0x893081cd),
    (0xdd782891, 0x0b9bc706),
    (0x000efdff, 0xa9ee7234),
    (0x41998713, 0x23d4d1d5),
    (0x9acb5597, 0x83cfc5c6),
    (0xff823d0b, 0xcadaf602),
    (0x4b23969f, 0xf1d0f64c),
    (0x78e0a781, 0x07a10fdb),
    (0x2f470121, 0x96287895),
    (0xcb0ca103, 0xe21482cb),
    (0x5f5d7f99, 0xe7455907),
    (0xc69c3c8f, 0x8a71184d),
    (0xb0ed55db, 0x23318ac8),
    (0x56e8f3f9, 0x72aed44b),
    (0xcb251b0d, 0x23a79d4c),
    (0xdefefa33, 0xe463042b),
    (0x13dfc965, 0xceb13214),
    (0xb14faa29, 0x60a95e1e),
    (0xd6a0a9fd, 0x65ce2624),
    (0xa06562cb, 0x89d63367),
    (0x5ed51725, 0x2a54a707),
    (0x0c9193a9, 0xa6fd0f2d),
    (0x68adf717, 0xed7133c4),
    (0xe30c41f9, 0x5c7b9a39),
    (0xc1989bd5, 0x59072ef0),
    (0x758b2539, 0x922d9dfc),
    (0x0e05bf3b, 0xc03538d2),
    (0x119eb31d, 0xa3494060),
    (0x57478465, 0xb9db010d),
    (0xd3f2d489, 0x20562c0a),
    (0xd5a8f9af, 0xe2205917),
    (0xea16bfaf, 0xb0b13f7c),
    (0x1e0c97d3, 0x9fa8fb51),
    (0xdc8485e3, 0xa5d2e787),
    (0x47e0cbef, 0xc03dc379),
    (0xe0d55bbd, 0x5a9bc098),
    (0x656d8ec1, 0x595166ca),
    (0x8e8908ad, 0xc3633ddc),
    (0x99fb311b, 0x4519fe94),
    (0x6e93afd3, 0x5b45a9a0),
    (0xefbffb13, 0xe558cc8c),
    (0x9b03080f, 0xc0b6bcc1),
    (0xa079227f, 0x6d97625e),
    (0x2f83967b, 0xe19f9e3c),
    (0x62781c2d, 0xf6ffc1e9),
    (0x094b4a73, 0x02fcc098),
    (0xc0b61403, 0xa9d74d52),
    (0xbae3ef01, 0x7f841373),
    (0xca09e279, 0x9f277361),
    (0xa885f1a3, 0x12e40882),
    (0x2b8aea11, 0x1d5ffdec),
    (0xa8c1c5b1, 0xc975a6dc),
    (0x13fefd1b, 0xf311ba67),
    (0x8bcd34e7, 0x1066b762),
    (0x56f4035f, 0x732d710a),
    (0x1e551fd5, 0x5af59eb6),
    (0xc19be4f3, 0x94115760),
    (0x574f7391, 0xf11c39e9),
    (0x325a843d, 0x687ba752),
    (0x2fa6488f, 0x613ac9d6),
    (0xd79b6b07, 0x3cadccc6),
    (0x57e30b8d, 0xc34ebac2),
    (0xea707f2b, 0xe743e147),
    (0xd2d5dc63, 0xc5873fe7),
    (0x10fb0a73, 0x92dca8b0),
    (0x65256407, 0x4d25f636),
    (0x623db789, 0x00bc1c0f),
    (0x944a5631, 0xc5d23b85),
    (0xa18b43e3, 0x9dfd3591),
    (0x48c3f857, 0x272668aa),
    (0x5f7d0c99, 0x539f0014),
    (0x910e9835, 0x94215a76),
    (0xab540e69, 0x86ed47b0),
    (0xd3384aa1, 0x024e5916),
    (0x095d14db, 0xe2cd19e5),
    (0x117ee6e7, 0xb583cf8d),
    (0x8012ea53, 0x5b7607f1),
    (0x3f80dba5, 0x787bea72),
    (0xfa4c001f, 0xe895c261),
    (0x523ed881, 0xc3bc56b5),
    (0x7f0f9189, 0x9f948754),
    (0x98d46033, 0x77a70c0a),
    (0x8f965adf, 0x040cdc60),
    (0xe46bbdc5, 0x44dd40b7),
    (0x941c6baf, 0xedef993d),
    (0x71ba4f0f, 0xd4e9ce38),
    (0x34da0a35, 0xb0de9ed9),
    (0x258ffd33, 0x8d23a195),
    (0xe5524cd1, 0xff508ce7),
    (0xf040082d, 0x11f0dc60),
    (0xd1336e13, 0x2c1e81f9),
    (0x313d7d87, 0x78f41fd3),
    (0x965497cf, 0x231b5419),
    (0xce8688fd, 0xbe25d5f1),
    (0x93574a2f, 0xeebe938e),
    (0x3d2ddafb, 0x3124088d),
    (0x42931ac9, 0xb262acd4),
    (0x0cb28137, 0x76dd1e74),
    (0x09ea774b, 0x10e5632b),
    (0x2ad0a273, 0x3af90e86),
    (0x5b9054a7, 0xc16606cd),
    (0xd56ed94d, 0x821c82b8),
    (0x6c5a8511, 0xc0fe07bb),
    (0xd2264a41, 0x3564bb8f),
    (0x87f5bb45, 0xec4b5618),
    (0x990d5e15, 0x0c9f33fb),
    (0xfbaf7a2f, 0xb6267c89),
    (0x2b350d1f, 0x84d421c2),
    (0x1b5255df, 0x1fd038c7),
    (0x21bf38af, 0x2c1a6f35),
    (0x25f2be33, 0x0516dd45),
    (0x3a561f8f, 0x6574c9a4),
    (0x4b2001e7, 0x06b5c365),
    (0xe9bf0ab9, 0x1b7c4af8),
    (0x2db97495, 0x073f1815),
    (0x859f097d, 0x8282ed28),
    (0x6646ba5d, 0x3f07b04d),
    (0x7647a741, 0x1a2588db),
    (0x34652db1, 0xdc2acab1),
    (0x1120292f, 0x49e96971),
    (0xd3ff256f, 0x89f0d52f),
    (0xe65e4a83, 0x3b5485cd),
    (0x63886ae3, 0x8d85bda8),
    (0xfc724e9b, 0xf7b915ce),
    (0xd40f4e07, 0xd78f562d),
    (0x14c99701, 0x473fe757),
];