const K1: f64 = 1.2;
const B: f64 = 0.75;
const POINT: f64 = 4_294_967_296.0;
const STEMS: f64 = 0.75;
pub(crate) const PREFIXED: f64 = 0.5;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct Part(pub(crate) u32);
const FILTERS: u32 = 1 << 30;
impl Part {
pub(crate) fn filter(number: u32) -> Part {
Part(FILTERS + number)
}
pub(crate) fn is_filter(self) -> bool {
self.0 >= FILTERS
}
pub(crate) fn is_written(self) -> bool {
!self.is_filter() && self.0.is_multiple_of(2)
}
pub(crate) fn written(field: u32) -> Part {
Part(field * 2)
}
pub(crate) fn stems(field: u32) -> Part {
Part(field * 2 + 1)
}
pub(crate) fn field(self) -> u32 {
self.0 / 2
}
pub(crate) fn is_stems(self) -> bool {
self.0 % 2 == 1
}
pub(crate) fn weight(self, field: f64) -> f64 {
if self.is_stems() { field * STEMS } else { field }
}
}
pub(crate) fn idf(documents: u64, holding: u64) -> f64 {
let (n, df) = (documents as f64, holding as f64);
(1.0 + (n - df + 0.5) / (df + 0.5)).ln()
}
fn saturated(tf: u32, len: u32, average: f64) -> f64 {
let tf = f64::from(tf);
tf * (K1 + 1.0) / (tf + K1 * (1.0 - B + B * f64::from(len) / average))
}
pub(crate) fn points(scale: f64, tf: u32, len: u32, average: f64) -> u64 {
(scale * saturated(tf, len, average) * POINT).round() as u64
}
pub(crate) fn score(points: u64) -> f64 {
points as f64 / POINT
}
pub(crate) fn average(tokens: u64, documents: u64) -> f64 {
(tokens as f64 / documents.max(1) as f64).max(1.0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_bound_from_a_blocks_largest_frequency_and_shortest_length_is_never_below_its_postings() {
for scale in [0.001, 0.37, 1.0, 7.5, 312.0] {
for average in [1.0, 3.7, 120.0, 9_000.0] {
for most_tf in 1..40 {
for least_len in [0, 1, 2, 5, 17, 300, 65_535] {
let bound = points(scale, most_tf, least_len, average);
for tf in [1, most_tf / 2 + 1, most_tf] {
for len in [least_len, least_len + 1, least_len.saturating_mul(3)] {
assert!(points(scale, tf, len, average) <= bound);
}
}
}
}
}
}
}
#[test]
fn a_rarer_key_tells_more() {
assert!(idf(1000, 1) > idf(1000, 10));
assert!(idf(1000, 1000) > 0.0);
}
}