tisonkun commented on code in PR #62: URL: https://github.com/apache/datasketches-rust/pull/62#discussion_r2701209759
########## datasketches/src/density/sketch.rs: ########## @@ -0,0 +1,551 @@ +// 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::cell::Cell; +use std::io::Read; +use std::io::Write; +use std::time::SystemTime; +use std::time::UNIX_EPOCH; + +use crate::codec::SketchBytes; +use crate::codec::SketchSlice; +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; + +/// 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; +} + +impl DensityValue for f64 { + fn from_f64(value: f64) -> Self { + value + } + + fn to_f64(self) -> f64 { + self + } +} + +impl DensityValue for f32 { + fn from_f64(value: f64) -> Self { + value as f32 + } + + fn to_f64(self) -> f64 { + self as f64 + } +} + +/// Kernel used to compute density contributions between points. +pub trait DensityKernel<T: DensityValue> { + /// Returns the kernel evaluation for the two points. + fn evaluate(&self, left: &[T], right: &[T]) -> T; +} + +/// Gaussian kernel based on squared Euclidean distance. +#[derive(Debug, Default, Clone, Copy)] +pub struct GaussianKernel; + +impl<T: DensityValue> DensityKernel<T> for GaussianKernel { + fn evaluate(&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> { + kernel: Box<dyn DensityKernel<T>>, + k: u16, + dim: u32, + num_retained: u32, + n: u64, + levels: Vec<Vec<Vec<T>>>, +} + +impl<T: DensityValue> DensitySketch<T> { + /// 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, Box::new(GaussianKernel)) + } + + /// Creates a new sketch with a custom kernel. + /// + /// # Panics + /// + /// Panics if `k` is less than 2. + pub fn with_kernel(k: u16, dim: u32, kernel: Box<dyn DensityKernel<T>>) -> Self { + check_k(k); + Self { + kernel, + k, + dim, + num_retained: 0, + n: 0, + levels: vec![Vec::new()], + } + } + + /// Deserializes a sketch using the Gaussian kernel. + pub fn deserialize(bytes: &[u8]) -> Result<Self, Error> { + Self::deserialize_with_kernel(bytes, Box::new(GaussianKernel)) + } + + /// Deserializes a sketch using the provided kernel. + pub fn deserialize_with_kernel( + bytes: &[u8], + kernel: Box<dyn DensityKernel<T>>, + ) -> Result<Self, Error> { + fn make_error(tag: &'static str) -> impl FnOnce(std::io::Error) -> Error { + move |_| Error::insufficient_data(tag) + } + + let mut cursor = SketchSlice::new(bytes); + let preamble_ints = cursor.read_u8().map_err(make_error("preamble_ints"))?; + let serial_version = cursor.read_u8().map_err(make_error("serial_version"))?; + let family_id = cursor.read_u8().map_err(make_error("family_id"))?; + let flags = cursor.read_u8().map_err(make_error("flags"))?; + let k = cursor.read_u16_le().map_err(make_error("k"))?; + cursor.read_u16_le().map_err(make_error("unused"))?; + let dim = cursor.read_u32_le().map_err(make_error("dim"))?; + + if family_id != DENSITY_FAMILY_ID { + return Err(Error::invalid_family( + DENSITY_FAMILY_ID, + family_id, + "DensitySketch", + )); + } + if serial_version != SERIAL_VERSION { + return Err(Error::unsupported_serial_version( + SERIAL_VERSION, + serial_version, + )); + } + validate_k(k)?; + check_header_validity(preamble_ints, flags)?; + + let is_empty = (flags & FLAGS_IS_EMPTY) != 0; + if is_empty { + return Ok(Self::with_kernel(k, dim, kernel)); + } + + let num_retained = cursor.read_u32_le().map_err(make_error("num_retained"))?; + let n = cursor.read_u64_le().map_err(make_error("n"))?; + + let mut levels = Vec::new(); + let mut remaining = num_retained as i64; + while remaining > 0 { + let level_size = cursor.read_u32_le().map_err(make_error("level_size"))?; + let mut level = Vec::with_capacity(level_size as usize); + for _ in 0..level_size { + let mut point = Vec::with_capacity(dim as usize); + for _ in 0..dim { + point.push(read_value(&mut cursor).map_err(make_error("point"))?); + } + level.push(point); + } + remaining -= level_size as i64; + levels.push(level); + } + if remaining != 0 { + return Err(Error::deserial( + "invalid number of retained points while decoding density sketch", + )); + } + + Ok(Self { + kernel, + k, + dim, + num_retained, + n, + levels, + }) + } + + /// Deserializes a sketch from a reader using the Gaussian kernel. + pub fn deserialize_from_reader(reader: &mut dyn Read) -> Result<Self, Error> { + Self::deserialize_from_reader_with_kernel(reader, Box::new(GaussianKernel)) + } + + /// Deserializes a sketch from a reader using the provided kernel. + pub fn deserialize_from_reader_with_kernel( + reader: &mut dyn Read, + kernel: Box<dyn DensityKernel<T>>, + ) -> Result<Self, Error> { + let mut buf = Vec::new(); + reader + .read_to_end(&mut buf) + .map_err(|err| Error::deserial(format!("error reading stream: {err}")))?; + Self::deserialize_with_kernel(&buf, kernel) + } Review Comment: Why do you consider this is good to have? Generally, supporting `std::io::Read` is for streaming reading. If, as here, we just `read_to_end` and deserialize with the full bytes, I'd prefer to leave this work to the user and keep our logics less. -- 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]
