dharanad commented on code in PR #1199: URL: https://github.com/apache/datafusion-comet/pull/1199#discussion_r1901024382
########## native/spark-expr/src/rand.rs: ########## @@ -0,0 +1,261 @@ +// 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 crate::spark_hash::spark_compatible_murmur3_hash; +use arrow_array::builder::Float64Builder; +use arrow_array::{Float64Array, RecordBatch}; +use arrow_schema::{DataType, Schema}; +use datafusion::logical_expr::ColumnarValue; +use datafusion::physical_expr::PhysicalExpr; +use datafusion::physical_expr_common::physical_expr::down_cast_any_ref; +use datafusion_common::ScalarValue; +use datafusion_common::{DataFusionError, Result}; +use std::any::Any; +use std::fmt::Display; +use std::hash::{Hash, Hasher}; +use std::sync::{Arc, Mutex}; + +const DOUBLE_UNIT: f64 = 1.1102230246251565e-16; +const SPARK_MURMUR_ARRAY_SEED: u32 = 0x3c074a61; + +#[derive(Debug, Clone)] +struct XorShiftRandom { + seed: i64, +} + +impl XorShiftRandom { + fn from_init_seed(init_seed: i64) -> Self { + XorShiftRandom { + seed: Self::init_seed(init_seed), + } + } + + fn from_stored_seed(stored_seed: i64) -> Self { + XorShiftRandom { seed: stored_seed } + } + + fn next(&mut self, bits: u8) -> i32 { + let mut next_seed = self.seed ^ (self.seed << 21); + next_seed ^= ((next_seed as u64) >> 35) as i64; + next_seed ^= next_seed << 4; + self.seed = next_seed; + (next_seed & ((1i64 << bits) - 1)) as i32 + } + + pub fn next_f64(&mut self) -> f64 { + let a = self.next(26) as i64; + let b = self.next(27) as i64; + ((a << 27) + b) as f64 * DOUBLE_UNIT + } + + fn init_seed(init: i64) -> i64 { + let bytes_repr = init.to_be_bytes(); + let low_bits = spark_compatible_murmur3_hash(bytes_repr, SPARK_MURMUR_ARRAY_SEED); + let high_bits = spark_compatible_murmur3_hash(bytes_repr, low_bits); + ((high_bits as i64) << 32) | (low_bits as i64 & 0xFFFFFFFFi64) + } +} + +#[derive(Debug)] +pub struct RandExpr { + seed: Arc<dyn PhysicalExpr>, + init_seed_shift: i32, + state_holder: Arc<Mutex<Option<i64>>>, +} + +impl RandExpr { + pub fn new(seed: Arc<dyn PhysicalExpr>, init_seed_shift: i32) -> Self { + Self { + seed, + init_seed_shift, + state_holder: Arc::new(Mutex::new(None::<i64>)), + } + } + + fn extract_init_state(seed: ScalarValue) -> Result<i64> { + if let ScalarValue::Int64(seed_opt) = seed.cast_to(&DataType::Int64)? { + Ok(seed_opt.unwrap_or(0)) + } else { + Err(DataFusionError::Internal( + "unexpected execution branch".to_string(), + )) + } + } + fn evaluate_batch(&self, seed: ScalarValue, num_rows: usize) -> Result<ColumnarValue> { + let mut seed_state = self.state_holder.lock().unwrap(); + let mut rnd = if seed_state.is_none() { + let init_seed = RandExpr::extract_init_state(seed)?; + let init_seed = init_seed.wrapping_add(self.init_seed_shift as i64); + *seed_state = Some(init_seed); + XorShiftRandom::from_init_seed(init_seed) + } else { + let stored_seed = seed_state.unwrap(); + XorShiftRandom::from_stored_seed(stored_seed) + }; + + let mut arr_builder = Float64Builder::with_capacity(num_rows); + std::iter::repeat_with(|| rnd.next_f64()) + .take(num_rows) + .for_each(|v| arr_builder.append_value(v)); + let array_ref = Arc::new(Float64Array::from(arr_builder.finish())); + *seed_state = Some(rnd.seed); + Ok(ColumnarValue::Array(array_ref)) + } +} + +impl Display for RandExpr { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "RAND({})", self.seed) + } +} + +impl PartialEq<dyn Any> for RandExpr { + fn eq(&self, other: &dyn Any) -> bool { + down_cast_any_ref(other) + .downcast_ref::<Self>() + .map(|x| self.seed.eq(&x.seed)) + .unwrap_or(false) + } +} + +impl PhysicalExpr for RandExpr { + fn as_any(&self) -> &dyn Any { + self + } + + fn data_type(&self, _input_schema: &Schema) -> Result<DataType> { + Ok(DataType::Float64) + } + + fn nullable(&self, _input_schema: &Schema) -> Result<bool> { + Ok(false) + } + + fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> { + match self.seed.evaluate(batch)? { + ColumnarValue::Scalar(seed) => self.evaluate_batch(seed, batch.num_rows()), + ColumnarValue::Array(_arr) => Err(DataFusionError::NotImplemented(format!( + "Only literal seeds are not supported for {}", Review Comment: Error message seems to have a typo -- 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: github-unsubscr...@datafusion.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org For additional commands, e-mail: github-h...@datafusion.apache.org