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-legacy-v1`, the set signature of datasketch before 2.0.0, and its permutation table.

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

/// The Mersenne prime `2^61 - 1`, datasketch's modulus.
const PRIME: u64 = (1 << 61) - 1;

/// Make the `minhash-legacy-v1` signature of a set of features, Broder's MinHash as the Python
/// library datasketch computed it by default before its version 2.0.0.
///
/// Choose it to agree with signatures datasketch made before 2.0.0, or with `scheme="legacy"`.
/// For new data choose [`minhash_v1`](crate::minhash_v1), datasketch's current default. 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`, as in `minhash-v1`.
/// 3. For each of 128 permutations `(a, b)`, in order, compute
///    `p = ((a × h + b) mod 2^64) mod (2^61 - 1)`, that is `a × h + b` in wrapping unsigned 64-bit
///    arithmetic, then the remainder by the Mersenne prime, and keep the low 32 bits of `p`. The
///    wrap before the modulus is datasketch's: its `uint64` arithmetic overflows, and the
///    definition follows it. The 128 pairs are the ones datasketch draws from NumPy's legacy generator,
///    `RandomState(1)`, `a` from `[1, 2^61 - 1)` then `b` from `[0, 2^61 - 1)` for each
///    permutation; the crate holds them as a table, generated from datasketch 2.0.0, never
///    computed at run time.
/// 4. 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 `MinHash(num_perm=128, seed=1, scheme="legacy")`, which is the default
/// `MinHash(num_perm=128, seed=1)` of datasketch from 1.1.3, when it began drawing permutations
/// with NumPy, until 2.0.0; 1.9.0's is checked. It isn't datasketch 2.0.0's default,
/// `scheme="affine32"`, which is `minhash-v1`, nor that of releases before 1.1.3.
///
/// Step 3 folds a 61-bit range onto 32 bits, which, in datasketch's words, "turns the combined step
/// into a random function rather than a permutation": it makes features collide on top of the
/// collisions of the 32-bit feature hash, so on very large sets the estimate runs high. datasketch
/// measures two disjoint sets of a billion features at about 0.23, nearly twice the 0.12 of its
/// current default, and keeps the legacy scheme only for sketches made by earlier versions. In a
/// measurement made before this crate's release, the excess first showed at 10 million features per
/// set, where about 0.1% to 0.2% of the values matched spuriously, and not at all at the sizes of
/// texts.
///
/// ```
/// use legit_hashes::minhash_legacy_v1;
///
/// let first = minhash_legacy_v1(["stored", "hashes", "outlive", "the", "code"]);
/// let second = minhash_legacy_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_legacy_v1<F: AsRef<[u8]>>(features: impl IntoIterator<Item = F>) -> Signature {
    let mut signature = MinHashLegacyV1::new();
    for feature in features {
        signature.add(feature);
    }
    signature.finish()
}

/// Make the `minhash-legacy-v1` signature of the character shingles of `text`, from
/// [`shingles_v1`](crate::shingles_v1) with `size`. [`minhash_v1_shingles`](crate::minhash_v1_shingles)
/// says how to choose the size and when to normalise the text first.
///
/// ```
/// use legit_hashes::minhash_legacy_v1_shingles;
///
/// let original = minhash_legacy_v1_shingles("Your parcel is waiting: confirm your address today.", 5)?;
/// let edited = minhash_legacy_v1_shingles("Your parcel is waiting: confirm your adress today!", 5)?;
/// let other = minhash_legacy_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_legacy_v1_shingles(text: &str, size: usize) -> Result<Signature> {
    Ok(minhash_legacy_v1(shingles_v1(text, size)?))
}

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

impl MinHashLegacyV1 {
    /// Start a signature with no features.
    ///
    /// ```
    /// use legit_hashes::MinHashLegacyV1;
    ///
    /// assert!(MinHashLegacyV1::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::MinHashLegacyV1;
    ///
    /// let mut signature = MinHashLegacyV1::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 = u64::from(sha1_hash32(feature.as_ref()));
        for (value, &(a, b)) in self.values.iter_mut().zip(&PERMUTATIONS) {
            let permuted = a.wrapping_mul(h).wrapping_add(b) % PRIME;
            // The low 32 bits, as datasketch masks them...
            *value = (*value).min((permuted & 0xffff_ffff) as u32);
        }
    }

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

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

/// The 128 permutations `(a, b)` of `minhash-legacy-v1`, in order: the parameters datasketch draws
/// for `MinHash(num_perm=128, seed=1, scheme="legacy")`.
///
/// Printed by `tools/hash-ref/capture_minhash.py --table legacy` in the repository, from datasketch
/// 2.0.0, which the same script checks against this table. Frozen with `minhash-legacy-v1`.
const PERMUTATIONS: [(u64, u64); 128] = [
    (0x0ac1f425ff4780ec, 0x18672f8ceebc1448),
    (0x00077eff20ccc38a, 0x0d65aacbffc11e85),
    (0x0591cb4f3c7053c1, 0x17a3809065865081),
    (0x0faebfcc634e1e48, 0x1876aaedab7479fc),
    (0x05928d86ef7f7d1a, 0x09efe4b2d8a7d514),
    (0x0b5054fe5032b166, 0x0f6a8b928648c9d4),
    (0x1456fb8b718620fd, 0x00cc4dea3ac5929c),
    (0x0702df9d88cf598f, 0x0ba3c232e9f96a44),
    (0x0ad47cd7750b5fd8, 0x0f064be96e4242f1),
    (0x03f065f7f06aaddf, 0x12b6c760c7448456),
    (0x0cfd988db749d7ea, 0x17dffd89cd818407),
    (0x103c913f17c1cb3e, 0x113c0e1684a5a539),
    (0x005b0a01dd71f781, 0x0504f13cd442f8d1),
    (0x15c57508d460e2d9, 0x09ff7e8d45e69a73),
    (0x0b7a01af0f2a8feb, 0x00cdf279aba7b9c8),
    (0x192d421e97d32448, 0x0bcdb583abf185c6),
    (0x15383f95696aee32, 0x087d85393292b203),
    (0x111edbc44a252b19, 0x10c5a1f12461fc2b),
    (0x0fbe864cc8874c1b, 0x15aa0734699c2550),
    (0x04ae8a6d08bf7374, 0x000975299fc06dd2),
    (0x1d26000fa91f6c41, 0x1f87c8c44c6a3019),
    (0x07cb2d6f7235dee3, 0x0a0e35d738dd2787),
    (0x1a6d051a12c7fe9a, 0x12a9266878200416),
    (0x0899b709189ebec4, 0x0b2a4be7e743447e),
    (0x09aba5171e96ed7e, 0x01498d648659409b),
    (0x04f53ba51568513a, 0x0dc82a53eab76ca6),
    (0x162d4288e9132521, 0x03fadda24c86af0a),
    (0x1dd7bd17959a8690, 0x0da92aef90df9c57),
    (0x12f95f199d2b0fc8, 0x059000f3f4df855c),
    (0x16dcba4a42cf84bf, 0x13235d2e3b23d3a0),
    (0x1a3296d888901498, 0x09ff92b7f32f2541),
    (0x11c435717e39274e, 0x0a07a7038a64cb80),
    (0x0cc9bff8c3f6d4fe, 0x093081cd0b9bc706),
    (0x09ee723423d4d1d6, 0x03cfc5c6cadaf602),
    (0x11d0f64c07a10fdc, 0x16287895e21482cb),
    (0x074559078a71184e, 0x03318ac872aed44b),
    (0x03a79d4ce463042c, 0x0eb1321460a95e1e),
    (0x05ce262489d63368, 0x0a54a707a6fd0f2d),
    (0x0d7133c45c7b9a3a, 0x19072ef0922d9dfc),
    (0x003538d2a3494061, 0x19db010d20562c0a),
    (0x02205917b0b13f7d, 0x1fa8fb51a5d2e787),
    (0x003dc3795a9bc099, 0x195166cac3633ddc),
    (0x0519fe945b45a9a1, 0x0558cc8cc0b6bcc1),
    (0x0d97625ee19f9e3d, 0x16ffc1e902fcc098),
    (0x09d74d527f841374, 0x1f27736112e40882),
    (0x1d5ffdecc975a6dd, 0x1311ba671066b762),
    (0x132d710a5af59eb7, 0x14115760f11c39e9),
    (0x087ba752613ac9d7, 0x1cadccc6c34ebac2),
    (0x0743e147c5873fe8, 0x12dca8b04d25f636),
    (0x00bc1c0fc5d23b86, 0x1dfd3591272668aa),
    (0x139f001494215a77, 0x06ed47b0024e5916),
    (0x02cd19e5b583cf8e, 0x1b7607f1787bea72),
    (0x0895c261c3bc56b6, 0x1f94875477a70c0a),
    (0x040cdc6044dd40b8, 0x0def993dd4e9ce38),
    (0x10de9ed98d23a196, 0x1f508ce711f0dc60),
    (0x0c1e81f978f41fd4, 0x031b5419be25d5f1),
    (0x0ebe938e3124088e, 0x1262acd476dd1e74),
    (0x10e5632b3af90e87, 0x016606cd821c82b8),
    (0x00fe07bb3564bb90, 0x0c4b56180c9f33fb),
    (0x16267c8984d421c3, 0x1fd038c72c1a6f35),
    (0x0516dd456574c9a5, 0x06b5c3651b7c4af8),
    (0x073f18158282ed29, 0x1f07b04d1a2588db),
    (0x1c2acab149e96972, 0x09f0d52f3b5485cd),
    (0x0d85bda8f7b915cf, 0x178f562d473fe757),
    (0x1fc9d2903bceaf9d, 0x077894ea17703e2d),
    (0x15f451c391efe375, 0x18376d426afd3bce),
    (0x0f9fad2e5e2af981, 0x04c6119dd020703f),
    (0x0cf6434b4a2db624, 0x1ba433b5b7a6f9dd),
    (0x0e9e72219cea2a83, 0x034ad5d46d49f653),
    (0x1d111430c07abf37, 0x1f435d206d8520fd),
    (0x0e65c29c6daa7838, 0x02eebad25ca5c51f),
    (0x0f56c41c274130df, 0x1f105d4aefebb488),
    (0x0b67c06dea99d664, 0x1b84bc20c82e6e08),
    (0x19c816549dc7bbce, 0x168672320937424f),
    (0x0f499ca9a781c341, 0x0336de6c213894d3),
    (0x126ce8184b5b2472, 0x179f6bea5c5e5b14),
    (0x116f082c464f2510, 0x140b069e12efa1db),
    (0x00986b8e26f275f4, 0x1e6b5f13295fd4fb),
    (0x1207aa9af04f68ec, 0x14d3f0565f02a187),
    (0x18533ae30ccdfc36, 0x18c9c5afbdaf436e),
    (0x1d66a9bc4c764ef4, 0x1e67b1223450d064),
    (0x1eb56ae4fb546721, 0x14381793e49d09c3),
    (0x08237b18c264aed4, 0x04c168e5a6afd65e),
    (0x11ecf8a60a28b2b0, 0x1c811ce7d05a3385),
    (0x1b38684fc337fe40, 0x11a03f71748d6457),
    (0x113ea9a08825c72b, 0x1d15f2ca1bfd72c2),
    (0x146a2ed8256266e3, 0x0150ee9e823ffa91),
    (0x0d0af1443734db41, 0x1ece3cbcea9c0df4),
    (0x0b52d8ce764fa092, 0x03d1c4a721dc44a3),
    (0x10fb51d1c3a5569d, 0x1ebdd6963675b726),
    (0x01352aa9130299cb, 0x15cdf6cd186d6546),
    (0x00b4969929864ce7, 0x110888f05b413430),
    (0x02a402b2186617bf, 0x0e04652c24ace269),
    (0x1184e8b6ee56dd01, 0x03b3b556939b05f7),
    (0x0650cb10d6f2fd14, 0x0cc037099f901270),
    (0x03676adc53139434, 0x10e2d36fba5ef88a),
    (0x1c2d487b85d21145, 0x05ad7597bc9fad0e),
    (0x08669ebf2a580e16, 0x0e95b8aeafe30d7c),
    (0x039254836d4379b9, 0x1bff2758ba82bcd0),
    (0x1de52faec19f3237, 0x12f2bbcf65c9da47),
    (0x133ebdfcecd9ea0f, 0x0e80d2cd3419408f),
    (0x0a652d99020c7736, 0x043daed4ed2551f9),
    (0x03d78bba4b651bd6, 0x1c69e2722abd56ee),
    (0x1ab4179d062b862d, 0x0caf2c2573b66096),
    (0x0d1a39dbceef49b7, 0x0b321d4c5e4df20c),
    (0x051691789bf4fd3c, 0x16985f9a08ebc7cc),
    (0x0c885bc75ac592d8, 0x005721a71419e27d),
    (0x02948c2bb17495cd, 0x0173137203412326),
    (0x0582a65b75a4c271, 0x12ae2cfdf618e345),
    (0x13bdd6e2558d29a2, 0x03d848ab78da759a),
    (0x0d1b32b81afaebc6, 0x15021e4980c99534),
    (0x01890259e2bc921c, 0x0f3ac82b88ccf401),
    (0x1840a952480edc80, 0x10aae25e5ac60fe0),
    (0x14fee19ae5729f55, 0x00fb221e3dd23b67),
    (0x18408440061d4497, 0x07c7ca62f739df34),
    (0x15bab6836e126047, 0x0bdd628c58a65d27),
    (0x0c7148e693bab454, 0x0924deef206404b0),
    (0x1d81413df33609c7, 0x195f4b0d5048cca4),
    (0x03f9fd17f3ecbd97, 0x17ee65c237e89e7a),
    (0x0f0569dc3faad0fa, 0x0eaf2deadd221d5f),
    (0x10b3e2353c3a8b8a, 0x04945aa9d0aa65b9),
    (0x13ee73588b3cd96e, 0x0f1b4af630f66edd),
    (0x09b5baf496be36cd, 0x1cae13520c52b16a),
    (0x0dccff8b0410406a, 0x0b91d0240cb9dc70),
    (0x0dd774906640149f, 0x0b297c7393affa6a),
    (0x001a58d4de159fba, 0x1a0ce323c941eda9),
    (0x0067915141343303, 0x1949e0d5150ea85d),
    (0x1aceaca42862b26e, 0x142f3d2e35a15350),
];