tisonkun commented on code in PR #62: URL: https://github.com/apache/datasketches-rust/pull/62#discussion_r2807095654
########## datasketches/src/density/sketch.rs: ########## @@ -0,0 +1,601 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use std::io::Write; + +use crate::codec::SketchBytes; +use crate::codec::SketchSlice; +use crate::common::RandomSource; +use crate::common::XorShift64; +use crate::density::serialization::DENSITY_FAMILY_ID; +use crate::density::serialization::FLAGS_IS_EMPTY; +use crate::density::serialization::PREAMBLE_INTS_LONG; +use crate::density::serialization::PREAMBLE_INTS_SHORT; +use crate::density::serialization::SERIAL_VERSION; +use crate::error::Error; +use crate::error::ErrorKind; + +type SerializeValue<T> = fn(&mut SketchBytes, T); +type DeserializeValue<T> = fn(&mut SketchSlice<'_>) -> std::io::Result<T>; +type Point<T> = Vec<T>; +type Level<T> = Vec<Point<T>>; +type Levels<T> = Vec<Level<T>>; + +/// Floating point types supported by the density sketch. +pub trait DensityValue: Copy + PartialOrd + 'static { + /// Converts from f64. + fn from_f64(value: f64) -> Self; + /// Converts to f64 for accumulation. + fn to_f64(self) -> f64; +} + +macro_rules! impl_density_value { + ($name:ty, $from:expr, $to:expr) => { + impl DensityValue for $name { + #[inline(always)] + fn from_f64(value: f64) -> Self { + ($from)(value) + } + + #[inline(always)] + fn to_f64(self) -> f64 { + ($to)(self) + } + } + }; +} + +impl_density_value!(f64, |value: f64| value, |value: f64| value); +impl_density_value!(f32, |value: f64| value as f32, |value: f32| value as f64); + +/// Kernel used to compute density contributions between points. +pub trait DensityKernel { + /// Returns the kernel evaluation for the two points. + fn evaluate<T: DensityValue>(&self, left: &[T], right: &[T]) -> T; +} + +/// Gaussian kernel based on squared Euclidean distance. +#[derive(Debug, Default, Clone, Copy)] +pub struct GaussianKernel; + +impl DensityKernel for GaussianKernel { + fn evaluate<T: DensityValue>(&self, left: &[T], right: &[T]) -> T { + let mut sum = 0.0f64; + for (a, b) in left.iter().zip(right.iter()) { + let diff = a.to_f64() - b.to_f64(); + sum += diff * diff; + } + T::from_f64((-sum).exp()) + } +} + +/// Density sketch for streaming density estimation. +pub struct DensitySketch< + T: DensityValue, + K: DensityKernel = GaussianKernel, + R: RandomSource = XorShift64, +> { + kernel: K, + rng: R, + k: u16, + dim: u32, + num_retained: u32, + n: u64, + levels: Levels<T>, +} + +impl<T: DensityValue> DensitySketch<T, GaussianKernel, XorShift64> { + /// Creates a new sketch using the Gaussian kernel. + /// + /// # Panics + /// + /// Panics if `k` is less than 2. + pub fn new(k: u16, dim: u32) -> Self { + Self::with_kernel(k, dim, GaussianKernel) + } +} + +impl DensitySketch<f32, GaussianKernel, XorShift64> { + /// Deserializes a sketch using the Gaussian kernel. + pub fn deserialize(bytes: &[u8]) -> Result<Self, Error> { + Self::deserialize_with_kernel(bytes, GaussianKernel) + } +} + +impl DensitySketch<f64, GaussianKernel, XorShift64> { + /// Deserializes a sketch using the Gaussian kernel. + pub fn deserialize(bytes: &[u8]) -> Result<Self, Error> { + Self::deserialize_with_kernel(bytes, GaussianKernel) + } +} + +impl<K: DensityKernel> DensitySketch<f32, K, XorShift64> { + /// Deserializes a sketch using the provided kernel. + pub fn deserialize_with_kernel(bytes: &[u8], kernel: K) -> Result<Self, Error> { + Self::deserialize_with_kernel_and_rng(bytes, kernel, XorShift64::default()) + } +} + +impl<K: DensityKernel> DensitySketch<f64, K, XorShift64> { + /// Deserializes a sketch using the provided kernel. + pub fn deserialize_with_kernel(bytes: &[u8], kernel: K) -> Result<Self, Error> { + Self::deserialize_with_kernel_and_rng(bytes, kernel, XorShift64::default()) + } +} + +impl<K: DensityKernel, R: RandomSource> DensitySketch<f32, K, R> { + /// Deserializes a sketch using the provided kernel and random source. + pub fn deserialize_with_kernel_and_rng(bytes: &[u8], kernel: K, rng: R) -> Result<Self, Error> { + deserialize_inner(bytes, kernel, rng, read_f32_value) + } + + /// Serializes the sketch to a byte vector. + pub fn serialize(&self) -> Vec<u8> { + serialize_inner(self, 4, write_f32_value) + } + + /// Serializes the sketch to a writer. + pub fn serialize_to_writer(&self, writer: &mut dyn Write) -> std::io::Result<()> { + writer.write_all(&self.serialize()) + } +} + +impl<K: DensityKernel, R: RandomSource> DensitySketch<f64, K, R> { + /// Deserializes a sketch using the provided kernel and random source. + pub fn deserialize_with_kernel_and_rng(bytes: &[u8], kernel: K, rng: R) -> Result<Self, Error> { + deserialize_inner(bytes, kernel, rng, read_f64_value) + } + + /// Serializes the sketch to a byte vector. + pub fn serialize(&self) -> Vec<u8> { + serialize_inner(self, 8, write_f64_value) + } + + /// Serializes the sketch to a writer. + pub fn serialize_to_writer(&self, writer: &mut dyn Write) -> std::io::Result<()> { + writer.write_all(&self.serialize()) + } Review Comment: I tend to remove this method unless we implement something that directly streams to the writer. Building a vector and write to the Writer can be easily implemented from the user side. ########## datasketches/src/density/sketch.rs: ########## @@ -0,0 +1,601 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use std::io::Write; + +use crate::codec::SketchBytes; +use crate::codec::SketchSlice; +use crate::common::RandomSource; +use crate::common::XorShift64; +use crate::density::serialization::DENSITY_FAMILY_ID; +use crate::density::serialization::FLAGS_IS_EMPTY; +use crate::density::serialization::PREAMBLE_INTS_LONG; +use crate::density::serialization::PREAMBLE_INTS_SHORT; +use crate::density::serialization::SERIAL_VERSION; +use crate::error::Error; +use crate::error::ErrorKind; + +type SerializeValue<T> = fn(&mut SketchBytes, T); +type DeserializeValue<T> = fn(&mut SketchSlice<'_>) -> std::io::Result<T>; +type Point<T> = Vec<T>; +type Level<T> = Vec<Point<T>>; +type Levels<T> = Vec<Level<T>>; + +/// Floating point types supported by the density sketch. +pub trait DensityValue: Copy + PartialOrd + 'static { + /// Converts from f64. + fn from_f64(value: f64) -> Self; + /// Converts to f64 for accumulation. + fn to_f64(self) -> f64; +} + +macro_rules! impl_density_value { + ($name:ty, $from:expr, $to:expr) => { + impl DensityValue for $name { + #[inline(always)] + fn from_f64(value: f64) -> Self { + ($from)(value) + } + + #[inline(always)] + fn to_f64(self) -> f64 { + ($to)(self) + } + } + }; +} + +impl_density_value!(f64, |value: f64| value, |value: f64| value); +impl_density_value!(f32, |value: f64| value as f32, |value: f32| value as f64); + +/// Kernel used to compute density contributions between points. +pub trait DensityKernel { + /// Returns the kernel evaluation for the two points. + fn evaluate<T: DensityValue>(&self, left: &[T], right: &[T]) -> T; +} + +/// Gaussian kernel based on squared Euclidean distance. +#[derive(Debug, Default, Clone, Copy)] +pub struct GaussianKernel; + +impl DensityKernel for GaussianKernel { + fn evaluate<T: DensityValue>(&self, left: &[T], right: &[T]) -> T { + let mut sum = 0.0f64; + for (a, b) in left.iter().zip(right.iter()) { + let diff = a.to_f64() - b.to_f64(); + sum += diff * diff; + } + T::from_f64((-sum).exp()) + } +} + +/// Density sketch for streaming density estimation. +pub struct DensitySketch< + T: DensityValue, + K: DensityKernel = GaussianKernel, + R: RandomSource = XorShift64, +> { + kernel: K, + rng: R, + k: u16, + dim: u32, + num_retained: u32, + n: u64, + levels: Levels<T>, +} + +impl<T: DensityValue> DensitySketch<T, GaussianKernel, XorShift64> { + /// Creates a new sketch using the Gaussian kernel. + /// + /// # Panics + /// + /// Panics if `k` is less than 2. + pub fn new(k: u16, dim: u32) -> Self { + Self::with_kernel(k, dim, GaussianKernel) + } +} + +impl DensitySketch<f32, GaussianKernel, XorShift64> { + /// Deserializes a sketch using the Gaussian kernel. + pub fn deserialize(bytes: &[u8]) -> Result<Self, Error> { + Self::deserialize_with_kernel(bytes, GaussianKernel) + } +} + +impl DensitySketch<f64, GaussianKernel, XorShift64> { + /// Deserializes a sketch using the Gaussian kernel. + pub fn deserialize(bytes: &[u8]) -> Result<Self, Error> { + Self::deserialize_with_kernel(bytes, GaussianKernel) + } +} + +impl<K: DensityKernel> DensitySketch<f32, K, XorShift64> { + /// Deserializes a sketch using the provided kernel. + pub fn deserialize_with_kernel(bytes: &[u8], kernel: K) -> Result<Self, Error> { + Self::deserialize_with_kernel_and_rng(bytes, kernel, XorShift64::default()) + } +} + +impl<K: DensityKernel> DensitySketch<f64, K, XorShift64> { + /// Deserializes a sketch using the provided kernel. + pub fn deserialize_with_kernel(bytes: &[u8], kernel: K) -> Result<Self, Error> { + Self::deserialize_with_kernel_and_rng(bytes, kernel, XorShift64::default()) + } +} + +impl<K: DensityKernel, R: RandomSource> DensitySketch<f32, K, R> { + /// Deserializes a sketch using the provided kernel and random source. + pub fn deserialize_with_kernel_and_rng(bytes: &[u8], kernel: K, rng: R) -> Result<Self, Error> { + deserialize_inner(bytes, kernel, rng, read_f32_value) + } + + /// Serializes the sketch to a byte vector. + pub fn serialize(&self) -> Vec<u8> { + serialize_inner(self, 4, write_f32_value) + } + + /// Serializes the sketch to a writer. + pub fn serialize_to_writer(&self, writer: &mut dyn Write) -> std::io::Result<()> { + writer.write_all(&self.serialize()) + } +} + +impl<K: DensityKernel, R: RandomSource> DensitySketch<f64, K, R> { + /// Deserializes a sketch using the provided kernel and random source. + pub fn deserialize_with_kernel_and_rng(bytes: &[u8], kernel: K, rng: R) -> Result<Self, Error> { + deserialize_inner(bytes, kernel, rng, read_f64_value) + } + + /// Serializes the sketch to a byte vector. + pub fn serialize(&self) -> Vec<u8> { + serialize_inner(self, 8, write_f64_value) + } + + /// Serializes the sketch to a writer. + pub fn serialize_to_writer(&self, writer: &mut dyn Write) -> std::io::Result<()> { + writer.write_all(&self.serialize()) + } Review Comment: I tend to remove this method unless we implement something that directly streams to the writer. Building a vector and write to the Writer can be easily implemented at the user side. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
