datafusion_functions_nested/
array_normalize.rs1use crate::utils::{make_scalar_function, needs_norm_scale, norm_scale};
8use arrow::array::{
9 Array, ArrayRef, Float64Array, GenericListArray, NullBufferBuilder, OffsetSizeTrait,
10};
11use arrow::buffer::OffsetBuffer;
12use arrow::datatypes::{
13 DataType,
14 DataType::{FixedSizeList, LargeList, List, Null},
15 Field,
16};
17use datafusion_common::cast::{as_float64_array, as_generic_list_array};
18use datafusion_common::utils::{
19 ListCoercion, coerced_type_with_base_type_only, offset_span_len,
20};
21use datafusion_common::{Result, internal_err, plan_err, utils::take_function_args};
22use datafusion_expr::{
23 ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
24 Volatility,
25};
26use datafusion_macros::user_doc;
27use std::sync::Arc;
28
29make_udf_expr_and_func!(
30 ArrayNormalize,
31 array_normalize,
32 array,
33 "returns the L2-normalized vector for a numeric array.",
34 array_normalize_udf
35);
36
37#[user_doc(
38 doc_section(label = "Array Functions"),
39 description = "Returns the L2-normalized vector for the input numeric array, computed as `array[i] / sqrt(sum(array[i]^2))` per element. Returns NULL if the input is NULL, contains NULL elements, or has zero magnitude (all elements are zero). Returns an empty array for an empty input array.",
40 syntax_example = "array_normalize(array)",
41 sql_example = r#"```sql
42> select array_normalize([3.0, 4.0]);
43+----------------------------------+
44| array_normalize(List([3.0,4.0])) |
45+----------------------------------+
46| [0.6, 0.8] |
47+----------------------------------+
48```"#,
49 argument(
50 name = "array",
51 description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
52 )
53)]
54#[derive(Debug, PartialEq, Eq, Hash)]
55pub struct ArrayNormalize {
56 signature: Signature,
57 aliases: Vec<String>,
58}
59
60impl Default for ArrayNormalize {
61 fn default() -> Self {
62 Self::new()
63 }
64}
65
66impl ArrayNormalize {
67 pub fn new() -> Self {
68 Self {
69 signature: Signature::user_defined(Volatility::Immutable),
70 aliases: vec!["list_normalize".to_string()],
71 }
72 }
73}
74
75impl ScalarUDFImpl for ArrayNormalize {
76 fn name(&self) -> &str {
77 "array_normalize"
78 }
79
80 fn signature(&self) -> &Signature {
81 &self.signature
82 }
83
84 fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
85 Ok(arg_types[0].clone())
87 }
88
89 fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
90 let [arg_type] = take_function_args(self.name(), arg_types)?;
91 let coercion = Some(&ListCoercion::FixedSizedListToList);
92
93 if !matches!(arg_type, Null | List(_) | LargeList(_) | FixedSizeList(..)) {
94 return plan_err!("{} does not support type {arg_type}", self.name());
95 }
96
97 let coerced = if matches!(arg_type, Null) {
98 List(Arc::new(Field::new_list_field(DataType::Float64, true)))
99 } else {
100 coerced_type_with_base_type_only(arg_type, &DataType::Float64, coercion)
101 };
102
103 Ok(vec![coerced])
104 }
105
106 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
107 make_scalar_function(array_normalize_inner)(&args.args)
108 }
109
110 fn aliases(&self) -> &[String] {
111 &self.aliases
112 }
113
114 fn documentation(&self) -> Option<&Documentation> {
115 self.doc()
116 }
117}
118
119fn array_normalize_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
120 let [array] = take_function_args("array_normalize", args)?;
121 match array.data_type() {
122 List(_) => general_array_normalize::<i32>(args),
123 LargeList(_) => general_array_normalize::<i64>(args),
124 arg_type => internal_err!(
125 "array_normalize received unexpected type after coercion: {arg_type}"
126 ),
127 }
128}
129
130fn general_array_normalize<O: OffsetSizeTrait>(arrays: &[ArrayRef]) -> Result<ArrayRef> {
131 let list_array = as_generic_list_array::<O>(&arrays[0])?;
132 let values = as_float64_array(list_array.values())?;
133 let offsets = list_array.offsets();
134
135 let mut new_values: Vec<f64> = Vec::with_capacity(offset_span_len(offsets));
136 let mut new_offsets = Vec::<O>::with_capacity(list_array.len() + 1);
137 new_offsets.push(O::zero());
138 let mut nulls = NullBufferBuilder::new(list_array.len());
139
140 for row in 0..list_array.len() {
141 if list_array.is_null(row) {
142 nulls.append_null();
143 new_offsets.push(new_offsets[row]);
144 continue;
145 }
146
147 let start = offsets[row].as_usize();
148 let end = offsets[row + 1].as_usize();
149 let len = end - start;
150
151 let slice = values.slice(start, len);
152 if slice.null_count() != 0 {
153 nulls.append_null();
154 new_offsets.push(new_offsets[row]);
155 continue;
156 }
157
158 let vals = slice.values();
159
160 if len == 0 {
162 nulls.append_non_null();
163 new_offsets.push(new_offsets[row]);
164 continue;
165 }
166
167 let mut sq_sum = 0.0;
169 for i in 0..len {
170 sq_sum += vals[i] * vals[i];
171 }
172
173 let scale = if needs_norm_scale(sq_sum, len) {
177 norm_scale(vals.iter().copied())
178 } else {
179 None
180 };
181 if let Some(scale) = scale {
182 sq_sum = 0.0;
183 for i in 0..len {
184 let scaled = vals[i] * scale;
185 sq_sum += scaled * scaled;
186 }
187 }
188
189 if sq_sum == 0.0 {
191 nulls.append_null();
192 new_offsets.push(new_offsets[row]);
193 continue;
194 }
195
196 let mag = sq_sum.sqrt();
197 match scale {
198 Some(scale) => new_values.extend(vals.iter().map(|v| v * scale / mag)),
199 None => new_values.extend(vals.iter().map(|v| v / mag)),
200 }
201 nulls.append_non_null();
202 new_offsets.push(new_offsets[row] + O::usize_as(len));
203 }
204
205 let values_array = Arc::new(Float64Array::from(new_values));
206 let field = Arc::new(Field::new_list_field(DataType::Float64, true));
207
208 Ok(Arc::new(GenericListArray::<O>::try_new(
209 field,
210 OffsetBuffer::new(new_offsets.into()),
211 values_array,
212 nulls.finish(),
213 )?))
214}
215
216#[cfg(test)]
217mod tests {
218 use super::*;
219
220 #[test]
221 fn test_sliced_capacity() -> Result<()> {
222 crate::utils::tests::check_sliced_list_behavior(|input| {
223 array_normalize_inner(std::slice::from_ref(input))
224 })
225 }
226}