Skip to main content

polars_core/chunked_array/
arg_min_max.rs

1use polars_arrow::array::Array;
2use polars_utils::arg_min_max::ArgMinMax;
3use polars_utils::min_max::{MaxIgnoreNan, MinIgnoreNan, MinMaxPolicy};
4
5use crate::chunked_array::ChunkedArray;
6use crate::chunked_array::ops::float_sorted_arg_max::{
7    float_arg_max_sorted_ascending, float_arg_max_sorted_descending,
8};
9use crate::chunked_array::ops::row_encode::row_encode_ordered_propagate_nulls;
10use crate::datatypes::{
11    BinaryChunked, BinaryOffsetChunked, BooleanChunked, PolarsDataType, PolarsNumericType,
12    StringChunked,
13};
14#[cfg(feature = "dtype-categorical")]
15use crate::datatypes::{CategoricalChunked, PolarsCategoricalType};
16use crate::prelude::{AnyValue, Scalar, Series};
17use crate::series::IsSorted;
18
19pub fn arg_min_opt_iter<T, I>(iter: I) -> Option<usize>
20where
21    I: IntoIterator<Item = Option<T>>,
22    T: Ord,
23{
24    iter.into_iter()
25        .enumerate()
26        .flat_map(|(idx, val)| Some((idx, val?)))
27        .min_by(|x, y| Ord::cmp(&x.1, &y.1))
28        .map(|x| x.0)
29}
30
31pub fn arg_max_opt_iter<T, I>(iter: I) -> Option<usize>
32where
33    I: IntoIterator<Item = Option<T>>,
34    T: Ord,
35{
36    iter.into_iter()
37        .enumerate()
38        .flat_map(|(idx, val)| Some((idx, val?)))
39        .max_by(|x, y| Ord::cmp(&x.1, &y.1))
40        .map(|x| x.0)
41}
42
43pub fn arg_min_numeric<T>(ca: &ChunkedArray<T>) -> Option<usize>
44where
45    T: PolarsNumericType,
46    for<'b> &'b [T::Native]: ArgMinMax,
47{
48    if ca.null_count() == ca.len() {
49        None
50    } else if let Ok(vals) = ca.cont_slice() {
51        arg_min_numeric_slice(vals, ca.is_sorted_flag())
52    } else {
53        arg_min_numeric_chunked(ca)
54    }
55}
56
57pub fn arg_max_numeric<T>(ca: &ChunkedArray<T>) -> Option<usize>
58where
59    T: PolarsNumericType,
60    for<'b> &'b [T::Native]: ArgMinMax,
61{
62    if ca.null_count() == ca.len() {
63        None
64    } else if T::get_static_dtype().is_float() && !matches!(ca.is_sorted_flag(), IsSorted::Not) {
65        arg_max_float_sorted(ca)
66    } else if let Ok(vals) = ca.cont_slice() {
67        arg_max_numeric_slice(vals, ca.is_sorted_flag())
68    } else {
69        arg_max_numeric_chunked(ca)
70    }
71}
72
73/// # Safety
74/// `ca` has a float dtype, has at least one non-null value and is sorted.
75fn arg_max_float_sorted<T>(ca: &ChunkedArray<T>) -> Option<usize>
76where
77    T: PolarsNumericType,
78{
79    let out = match ca.is_sorted_flag() {
80        IsSorted::Ascending => float_arg_max_sorted_ascending(ca),
81        IsSorted::Descending => float_arg_max_sorted_descending(ca),
82        _ => unreachable!(),
83    };
84    Some(out)
85}
86
87#[cfg(feature = "dtype-categorical")]
88pub fn arg_min_cat<T: PolarsCategoricalType>(ca: &CategoricalChunked<T>) -> Option<usize> {
89    if ca.null_count() == ca.len() {
90        return None;
91    }
92    arg_min_opt_iter(ca.iter_str())
93}
94
95#[cfg(feature = "dtype-categorical")]
96pub fn arg_max_cat<T: PolarsCategoricalType>(ca: &CategoricalChunked<T>) -> Option<usize> {
97    if ca.null_count() == ca.len() {
98        return None;
99    }
100    arg_max_opt_iter(ca.iter_str())
101}
102
103pub fn arg_min_bool(ca: &BooleanChunked) -> Option<usize> {
104    ca.first_false_idx().or_else(|| ca.first_true_idx())
105}
106
107pub fn arg_max_bool(ca: &BooleanChunked) -> Option<usize> {
108    ca.first_true_idx().or_else(|| ca.first_false_idx())
109}
110
111pub fn arg_min_str(ca: &StringChunked) -> Option<usize> {
112    arg_min_physical_generic(ca)
113}
114
115pub fn arg_max_str(ca: &StringChunked) -> Option<usize> {
116    arg_max_physical_generic(ca)
117}
118
119pub fn arg_min_binary(ca: &BinaryChunked) -> Option<usize> {
120    arg_min_physical_generic(ca)
121}
122
123pub fn arg_max_binary(ca: &BinaryChunked) -> Option<usize> {
124    arg_max_physical_generic(ca)
125}
126
127pub fn arg_min_binary_offset(ca: &BinaryOffsetChunked) -> Option<usize> {
128    arg_min_physical_generic(ca)
129}
130
131pub fn arg_max_binary_offset(ca: &BinaryOffsetChunked) -> Option<usize> {
132    arg_max_physical_generic(ca)
133}
134
135/// The arg min or arg max of `s` in its sort order, skipping nulls.
136pub fn arg_min_max_row_encoded(s: &Series, is_max: bool) -> Option<usize> {
137    let encoded = row_encode_ordered_propagate_nulls(s);
138    if is_max {
139        arg_max_binary_offset(&encoded)
140    } else {
141        arg_min_binary_offset(&encoded)
142    }
143}
144
145/// The min or max of `s` in its sort order, skipping nulls.
146pub(crate) fn min_max_reduce_row_encoded(s: &Series, is_max: bool) -> Scalar {
147    let value = match arg_min_max_row_encoded(s, is_max) {
148        Some(idx) => s.get(idx).unwrap().into_static(),
149        None => AnyValue::Null,
150    };
151    Scalar::new(s.dtype().clone(), value)
152}
153
154fn arg_min_physical_generic<T>(ca: &ChunkedArray<T>) -> Option<usize>
155where
156    T: PolarsDataType,
157    for<'a> T::Physical<'a>: Ord,
158{
159    if ca.null_count() == ca.len() {
160        return None;
161    }
162    match ca.is_sorted_flag() {
163        IsSorted::Ascending => ca.first_non_null(),
164        IsSorted::Descending => ca.last_non_null(),
165        IsSorted::Not => arg_min_opt_iter(ca.iter()),
166    }
167}
168
169fn arg_max_physical_generic<T>(ca: &ChunkedArray<T>) -> Option<usize>
170where
171    T: PolarsDataType,
172    for<'a> T::Physical<'a>: Ord,
173{
174    if ca.null_count() == ca.len() {
175        return None;
176    }
177    match ca.is_sorted_flag() {
178        IsSorted::Ascending => ca.last_non_null(),
179        IsSorted::Descending => ca.first_non_null(),
180        IsSorted::Not => arg_max_opt_iter(ca.iter()),
181    }
182}
183
184fn arg_min_numeric_chunked<'a, T>(ca: &'a ChunkedArray<T>) -> Option<usize>
185where
186    T: PolarsNumericType,
187    for<'b> &'b [T::Native]: ArgMinMax,
188{
189    match ca.is_sorted_flag() {
190        IsSorted::Ascending => ca.first_non_null(),
191        IsSorted::Descending => ca.last_non_null(),
192        IsSorted::Not => {
193            let mut chunk_start_offset = 0;
194            let mut min_idx: Option<usize> = None;
195            let mut min_val: Option<T::Native> = None;
196            for arr in ca.downcast_iter() {
197                if arr.len() == arr.null_count() {
198                    chunk_start_offset += arr.len();
199                    continue;
200                }
201
202                let chunk_min: Option<(usize, T::Native)> = if arr.null_count() > 0 {
203                    let (validity, offset, _) = arr.validity().unwrap().as_slice();
204                    arr.values()
205                        .as_slice()
206                        .argmin_masked(validity, offset)
207                        .map(|idx| (idx, arr.value(idx)))
208                } else {
209                    // When no nulls & array not empty => we can use fast argmin.
210                    let min_idx: usize = arr.values().as_slice().argmin();
211                    Some((min_idx, arr.value(min_idx)))
212                };
213
214                if let Some((chunk_min_idx, chunk_min_val)) = chunk_min {
215                    if min_val.is_none()
216                        || MinIgnoreNan::is_better(&chunk_min_val, &min_val.unwrap())
217                    {
218                        min_val = Some(chunk_min_val);
219                        min_idx = Some(chunk_start_offset + chunk_min_idx);
220                    }
221                }
222                chunk_start_offset += arr.len();
223            }
224            min_idx
225        },
226    }
227}
228
229fn arg_max_numeric_chunked<'a, T>(ca: &'a ChunkedArray<T>) -> Option<usize>
230where
231    T: PolarsNumericType,
232    for<'b> &'b [T::Native]: ArgMinMax,
233{
234    match ca.is_sorted_flag() {
235        IsSorted::Ascending => ca.last_non_null(),
236        IsSorted::Descending => ca.first_non_null(),
237        IsSorted::Not => {
238            let mut chunk_start_offset = 0;
239            let mut max_idx: Option<usize> = None;
240            let mut max_val: Option<T::Native> = None;
241            for arr in ca.downcast_iter() {
242                if arr.len() == arr.null_count() {
243                    chunk_start_offset += arr.len();
244                    continue;
245                }
246
247                let chunk_max: Option<(usize, T::Native)> = if arr.null_count() > 0 {
248                    let (validity, offset, _) = arr.validity().unwrap().as_slice();
249                    arr.values()
250                        .as_slice()
251                        .argmax_masked(validity, offset)
252                        .map(|idx| (idx, arr.value(idx)))
253                } else {
254                    // When no nulls & array not empty => we can use fast argmax.
255                    let max_idx: usize = arr.values().as_slice().argmax();
256                    Some((max_idx, arr.value(max_idx)))
257                };
258
259                if let Some((chunk_max_idx, chunk_max_val)) = chunk_max {
260                    if max_val.is_none()
261                        || MaxIgnoreNan::is_better(&chunk_max_val, &max_val.unwrap())
262                    {
263                        max_val = Some(chunk_max_val);
264                        max_idx = Some(chunk_start_offset + chunk_max_idx);
265                    }
266                }
267                chunk_start_offset += arr.len();
268            }
269            max_idx
270        },
271    }
272}
273
274fn arg_min_numeric_slice<T>(vals: &[T], is_sorted: IsSorted) -> Option<usize>
275where
276    for<'a> &'a [T]: ArgMinMax,
277{
278    match is_sorted {
279        // all vals are not null guarded by cont_slice
280        IsSorted::Ascending => Some(0),
281        // all vals are not null guarded by cont_slice
282        IsSorted::Descending => Some(vals.len() - 1),
283        IsSorted::Not => Some(vals.argmin()), // assumes not empty
284    }
285}
286
287fn arg_max_numeric_slice<T>(vals: &[T], is_sorted: IsSorted) -> Option<usize>
288where
289    for<'a> &'a [T]: ArgMinMax,
290{
291    match is_sorted {
292        // all vals are not null guarded by cont_slice
293        IsSorted::Ascending => Some(vals.len() - 1),
294        // all vals are not null guarded by cont_slice
295        IsSorted::Descending => Some(0),
296        IsSorted::Not => Some(vals.argmax()), // assumes not empty
297    }
298}