polars-lazy 0.26.1

Lazy query engine for the Polars DataFrame library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
use std::borrow::Cow;
use std::sync::Arc;

use polars_arrow::export::arrow::array::*;
use polars_arrow::export::arrow::compute::concatenate::concatenate;
use polars_arrow::export::arrow::offset::Offsets;
use polars_arrow::prelude::QuantileInterpolOptions;
use polars_arrow::utils::CustomIterTools;
use polars_core::frame::groupby::{GroupByMethod, GroupsProxy};
use polars_core::prelude::*;
use polars_core::utils::NoNull;
#[cfg(feature = "dtype-struct")]
use polars_core::POOL;

use crate::physical_plan::state::ExecutionState;
use crate::physical_plan::PartitionedAggregation;
use crate::prelude::*;

pub(crate) struct AggregationExpr {
    pub(crate) input: Arc<dyn PhysicalExpr>,
    pub(crate) agg_type: GroupByMethod,
}

impl AggregationExpr {
    pub fn new(expr: Arc<dyn PhysicalExpr>, agg_type: GroupByMethod) -> Self {
        Self {
            input: expr,
            agg_type,
        }
    }
}

impl PhysicalExpr for AggregationExpr {
    fn as_expression(&self) -> Option<&Expr> {
        None
    }

    fn evaluate(&self, _df: &DataFrame, _state: &ExecutionState) -> PolarsResult<Series> {
        unimplemented!()
    }
    #[allow(clippy::ptr_arg)]
    fn evaluate_on_groups<'a>(
        &self,
        df: &DataFrame,
        groups: &'a GroupsProxy,
        state: &ExecutionState,
    ) -> PolarsResult<AggregationContext<'a>> {
        let mut ac = self.input.evaluate_on_groups(df, groups, state)?;
        // don't change names by aggregations as is done in polars-core
        let keep_name = ac.series().name().to_string();

        let check_flat = || {
            if matches!(ac.agg_state(), AggState::AggregatedFlat(_)) {
                Err(PolarsError::ComputeError(
                    format!(
                        "Cannot aggregate as {}. The column is already aggregated.",
                        self.agg_type
                    )
                    .into(),
                ))
            } else {
                Ok(())
            }
        };

        // Safety:
        // groups must always be in bounds.
        let out = unsafe {
            match self.agg_type {
                GroupByMethod::Min => {
                    check_flat()?;
                    let agg_s = ac.flat_naive().into_owned().agg_min(ac.groups());
                    rename_series(agg_s, &keep_name)
                }
                GroupByMethod::Max => {
                    check_flat()?;
                    let agg_s = ac.flat_naive().into_owned().agg_max(ac.groups());
                    rename_series(agg_s, &keep_name)
                }
                GroupByMethod::Median => {
                    check_flat()?;
                    let agg_s = ac.flat_naive().into_owned().agg_median(ac.groups());
                    rename_series(agg_s, &keep_name)
                }
                GroupByMethod::Mean => {
                    check_flat()?;
                    let agg_s = ac.flat_naive().into_owned().agg_mean(ac.groups());
                    rename_series(agg_s, &keep_name)
                }
                GroupByMethod::Sum => {
                    check_flat()?;
                    let agg_s = ac.flat_naive().into_owned().agg_sum(ac.groups());
                    rename_series(agg_s, &keep_name)
                }
                GroupByMethod::Count => {
                    // a few fast paths that prevent materializing new groups
                    match ac.update_groups {
                        UpdateGroups::WithSeriesLen => {
                            let list = ac
                                .series()
                                .list()
                                .expect("impl error, should be a list at this point");

                            let mut s = match list.chunks().len() {
                                1 => {
                                    let arr = list.downcast_iter().next().unwrap();
                                    let offsets = arr.offsets().as_slice();

                                    let mut previous = 0i64;
                                    let counts: NoNull<IdxCa> = offsets[1..]
                                        .iter()
                                        .map(|&o| {
                                            let len = (o - previous) as IdxSize;
                                            previous = o;
                                            len
                                        })
                                        .collect_trusted();
                                    counts.into_inner()
                                }
                                _ => {
                                    let counts: NoNull<IdxCa> = list
                                        .amortized_iter()
                                        .map(|s| {
                                            if let Some(s) = s {
                                                s.as_ref().len() as IdxSize
                                            } else {
                                                1
                                            }
                                        })
                                        .collect_trusted();
                                    counts.into_inner()
                                }
                            };
                            s.rename(&keep_name);
                            s.into_series()
                        }
                        UpdateGroups::WithGroupsLen => {
                            // no need to update the groups
                            // we can just get the attribute, because we only need the length,
                            // not the correct order
                            let mut ca = ac.groups.group_count();
                            ca.rename(&keep_name);
                            ca.into_series()
                        }
                        // materialize groups
                        _ => {
                            let mut ca = ac.groups().group_count();
                            ca.rename(&keep_name);
                            ca.into_series()
                        }
                    }
                }
                GroupByMethod::First => {
                    check_flat()?;
                    let mut agg_s = ac.flat_naive().into_owned().agg_first(ac.groups());
                    agg_s.rename(&keep_name);
                    agg_s
                }
                GroupByMethod::Last => {
                    check_flat()?;
                    let mut agg_s = ac.flat_naive().into_owned().agg_last(ac.groups());
                    agg_s.rename(&keep_name);
                    agg_s
                }
                GroupByMethod::NUnique => {
                    check_flat()?;
                    let agg_s = ac.flat_naive().into_owned().agg_n_unique(ac.groups());
                    rename_series(agg_s, &keep_name)
                }
                GroupByMethod::List => {
                    let agg = ac.aggregated();
                    rename_series(agg, &keep_name)
                }
                GroupByMethod::Groups => {
                    let mut column: ListChunked = ac.groups().as_list_chunked();
                    column.rename(&keep_name);
                    column.into_series()
                }
                GroupByMethod::Std(ddof) => {
                    check_flat()?;
                    let agg_s = ac.flat_naive().into_owned().agg_std(ac.groups(), ddof);
                    rename_series(agg_s, &keep_name)
                }
                GroupByMethod::Var(ddof) => {
                    check_flat()?;
                    let agg_s = ac.flat_naive().into_owned().agg_var(ac.groups(), ddof);
                    rename_series(agg_s, &keep_name)
                }
                GroupByMethod::Quantile(_, _) => {
                    // implemented explicitly in AggQuantile struct
                    unimplemented!()
                }
                GroupByMethod::NanMin => {
                    #[cfg(feature = "propagate_nans")]
                    {
                        check_flat()?;
                        let agg_s = ac.flat_naive().into_owned();
                        let groups = ac.groups();
                        let agg_s = if agg_s.dtype().is_float() {
                            nan_propagating_aggregate::group_agg_nan_min_s(&agg_s, groups)
                        } else {
                            agg_s.agg_min(groups)
                        };
                        rename_series(agg_s, &keep_name)
                    }
                    #[cfg(not(feature = "propagate_nans"))]
                    {
                        panic!("activate 'propagate_nans' feature")
                    }
                }
                GroupByMethod::NanMax => {
                    #[cfg(feature = "propagate_nans")]
                    {
                        check_flat()?;
                        let agg_s = ac.flat_naive().into_owned();
                        let groups = ac.groups();
                        let agg_s = if agg_s.dtype().is_float() {
                            nan_propagating_aggregate::group_agg_nan_max_s(&agg_s, groups)
                        } else {
                            agg_s.agg_max(groups)
                        };
                        rename_series(agg_s, &keep_name)
                    }
                    #[cfg(not(feature = "propagate_nans"))]
                    {
                        panic!("activate 'propagate_nans' feature")
                    }
                }
            }
        };

        Ok(AggregationContext::new(out, Cow::Borrowed(groups), true))
    }

    fn to_field(&self, input_schema: &Schema) -> PolarsResult<Field> {
        self.input.to_field(input_schema)
    }

    fn as_partitioned_aggregator(&self) -> Option<&dyn PartitionedAggregation> {
        Some(self)
    }

    fn is_valid_aggregation(&self) -> bool {
        true
    }
}

fn rename_series(mut s: Series, name: &str) -> Series {
    s.rename(name);
    s
}

impl PartitionedAggregation for AggregationExpr {
    fn evaluate_partitioned(
        &self,
        df: &DataFrame,
        groups: &GroupsProxy,
        state: &ExecutionState,
    ) -> PolarsResult<Series> {
        let expr = self.input.as_partitioned_aggregator().unwrap();
        let series = expr.evaluate_partitioned(df, groups, state)?;

        // Safety:
        // groups are in bounds
        unsafe {
            match self.agg_type {
                #[cfg(feature = "dtype-struct")]
                GroupByMethod::Mean => {
                    let new_name = series.name().to_string();

                    // ensure we don't overflow
                    // the all 8 and 16 bits integers are already upcasted to int16 on `agg_sum`
                    let mut agg_s = if matches!(series.dtype(), DataType::Int32 | DataType::UInt32)
                    {
                        series.cast(&DataType::Int64).unwrap().agg_sum(groups)
                    } else {
                        series.agg_sum(groups)
                    };
                    agg_s.rename(&new_name);

                    if !agg_s.dtype().is_numeric() {
                        Ok(agg_s)
                    } else {
                        let agg_s = match agg_s.dtype() {
                            DataType::Float32 => agg_s,
                            _ => agg_s.cast(&DataType::Float64).unwrap(),
                        };
                        let mut count_s = series.agg_valid_count(groups);
                        count_s.rename("count");
                        Ok(StructChunked::new(&new_name, &[agg_s, count_s])
                            .unwrap()
                            .into_series())
                    }
                }
                GroupByMethod::List => {
                    let new_name = series.name();
                    let mut agg = series.agg_list(groups);
                    agg.rename(new_name);
                    Ok(agg)
                }
                GroupByMethod::First => {
                    let mut agg = series.agg_first(groups);
                    agg.rename(series.name());
                    Ok(agg)
                }
                GroupByMethod::Last => {
                    let mut agg = series.agg_last(groups);
                    agg.rename(series.name());
                    Ok(agg)
                }
                GroupByMethod::Max => {
                    let mut agg = series.agg_max(groups);
                    agg.rename(series.name());
                    Ok(agg)
                }
                GroupByMethod::Min => {
                    let mut agg = series.agg_min(groups);
                    agg.rename(series.name());
                    Ok(agg)
                }
                GroupByMethod::Sum => {
                    let mut agg = series.agg_sum(groups);
                    agg.rename(series.name());
                    Ok(agg)
                }
                GroupByMethod::Count => {
                    let mut ca = groups.group_count();
                    ca.rename(series.name());
                    Ok(ca.into_series())
                }
                _ => {
                    unimplemented!()
                }
            }
        }
    }

    fn finalize(
        &self,
        partitioned: Series,
        groups: &GroupsProxy,
        _state: &ExecutionState,
    ) -> PolarsResult<Series> {
        match self.agg_type {
            GroupByMethod::Count | GroupByMethod::Sum => {
                let mut agg = unsafe { partitioned.agg_sum(groups) };
                agg.rename(partitioned.name());
                Ok(agg)
            }
            #[cfg(feature = "dtype-struct")]
            GroupByMethod::Mean => {
                let new_name = partitioned.name();
                match partitioned.dtype() {
                    DataType::Struct(_) => {
                        let ca = partitioned.struct_().unwrap();
                        let sum = &ca.fields()[0];
                        let count = &ca.fields()[1];
                        let (agg_count, agg_s) =
                            unsafe { POOL.join(|| count.agg_sum(groups), || sum.agg_sum(groups)) };
                        let agg_s = &agg_s / &agg_count;
                        Ok(rename_series(agg_s, new_name))
                    }
                    _ => Ok(Series::full_null(
                        new_name,
                        groups.len(),
                        partitioned.dtype(),
                    )),
                }
            }
            GroupByMethod::List => {
                // the groups are scattered over multiple groups/sub dataframes.
                // we now must collect them into a single group
                let ca = partitioned.list().unwrap();
                let new_name = partitioned.name().to_string();

                let mut values = Vec::with_capacity(groups.len());
                let mut can_fast_explode = true;

                let mut offsets = Vec::<i64>::with_capacity(groups.len() + 1);
                let mut length_so_far = 0i64;
                offsets.push(length_so_far);

                let mut process_group = |ca: ListChunked| -> PolarsResult<()> {
                    let s = ca.explode()?;
                    length_so_far += s.len() as i64;
                    offsets.push(length_so_far);
                    values.push(s.chunks()[0].clone());

                    if s.len() == 0 {
                        can_fast_explode = false;
                    }
                    Ok(())
                };

                match groups {
                    GroupsProxy::Idx(groups) => {
                        for (_, idx) in groups {
                            let ca = unsafe {
                                // Safety
                                // The indexes of the groupby operation are never out of bounds
                                ca.take_unchecked(idx.into())
                            };
                            process_group(ca)?;
                        }
                    }
                    GroupsProxy::Slice { groups, .. } => {
                        for [first, len] in groups {
                            let len = *len as usize;
                            let ca = ca.slice(*first as i64, len);
                            process_group(ca)?;
                        }
                    }
                }

                let vals = values.iter().map(|arr| &**arr).collect::<Vec<_>>();
                let values = concatenate(&vals).unwrap();

                let data_type = ListArray::<i64>::default_datatype(values.data_type().clone());
                // Safety:
                // offsets are monotonically increasing
                let arr = unsafe {
                    Box::new(ListArray::<i64>::new(
                        data_type,
                        Offsets::new_unchecked(offsets).into(),
                        values,
                        None,
                    )) as ArrayRef
                };
                let mut ca = ListChunked::from_chunks(&new_name, vec![arr]);
                if can_fast_explode {
                    ca.set_fast_explode()
                }
                Ok(ca.into_series())
            }
            GroupByMethod::First => {
                let mut agg = unsafe { partitioned.agg_first(groups) };
                agg.rename(partitioned.name());
                Ok(agg)
            }
            GroupByMethod::Last => {
                let mut agg = unsafe { partitioned.agg_last(groups) };
                agg.rename(partitioned.name());
                Ok(agg)
            }
            GroupByMethod::Max => {
                let mut agg = unsafe { partitioned.agg_max(groups) };
                agg.rename(partitioned.name());
                Ok(agg)
            }
            GroupByMethod::Min => {
                let mut agg = unsafe { partitioned.agg_min(groups) };
                agg.rename(partitioned.name());
                Ok(agg)
            }
            _ => unimplemented!(),
        }
    }
}

pub struct AggQuantileExpr {
    pub(crate) input: Arc<dyn PhysicalExpr>,
    pub(crate) quantile: Arc<dyn PhysicalExpr>,
    pub(crate) interpol: QuantileInterpolOptions,
}

impl AggQuantileExpr {
    pub fn new(
        input: Arc<dyn PhysicalExpr>,
        quantile: Arc<dyn PhysicalExpr>,
        interpol: QuantileInterpolOptions,
    ) -> Self {
        Self {
            input,
            quantile,
            interpol,
        }
    }

    fn get_quantile(&self, df: &DataFrame, state: &ExecutionState) -> PolarsResult<f64> {
        let quantile = self.quantile.evaluate(df, state)?;
        if quantile.len() > 1 {
            return Err(PolarsError::ComputeError(
                "Polars only supports computing a single quantile. \
            Make sure the 'quantile' expression input produces a single quantile."
                    .into(),
            ));
        }
        quantile.get(0).unwrap().try_extract::<f64>()
    }
}

impl PhysicalExpr for AggQuantileExpr {
    fn as_expression(&self) -> Option<&Expr> {
        None
    }

    fn evaluate(&self, df: &DataFrame, state: &ExecutionState) -> PolarsResult<Series> {
        let input = self.input.evaluate(df, state)?;
        let quantile = self.get_quantile(df, state)?;
        input.quantile_as_series(quantile, self.interpol)
    }
    #[allow(clippy::ptr_arg)]
    fn evaluate_on_groups<'a>(
        &self,
        df: &DataFrame,
        groups: &'a GroupsProxy,
        state: &ExecutionState,
    ) -> PolarsResult<AggregationContext<'a>> {
        let mut ac = self.input.evaluate_on_groups(df, groups, state)?;
        // don't change names by aggregations as is done in polars-core
        let keep_name = ac.series().name().to_string();

        let quantile = self.get_quantile(df, state)?;

        // safety:
        // groups are in bounds
        let mut agg = unsafe {
            ac.flat_naive()
                .into_owned()
                .agg_quantile(ac.groups(), quantile, self.interpol)
        };
        agg.rename(&keep_name);
        Ok(AggregationContext::new(agg, Cow::Borrowed(groups), true))
    }

    fn to_field(&self, input_schema: &Schema) -> PolarsResult<Field> {
        self.input.to_field(input_schema)
    }

    fn is_valid_aggregation(&self) -> bool {
        true
    }
}