Skip to main content

polars_time/windows/
group_by.rs

1use std::collections::VecDeque;
2
3use polars_arrow::legacy::time_zone::Tz;
4use polars_arrow::trusted_len::TrustedLen;
5use polars_core::prelude::*;
6use polars_core::runtime::RAYON;
7use polars_core::utils::_split_offsets;
8use polars_core::utils::flatten::flatten_par;
9use polars_defs::time::duration::Duration;
10use polars_defs::time::group_by::{ClosedWindow, DynamicWindowPlacement, StartBy};
11use rayon::prelude::*;
12
13use crate::prelude::*;
14
15#[allow(clippy::too_many_arguments)]
16fn update_groups_and_bounds(
17    bounds_iter: BoundsIter<'_>,
18    mut start: usize,
19    time: &[i64],
20    closed_window: ClosedWindow,
21    include_lower_bound: bool,
22    include_upper_bound: bool,
23    placement: Option<&DynamicWindowPlacement>,
24    lower_bound: &mut Vec<i64>,
25    upper_bound: &mut Vec<i64>,
26    groups: &mut Vec<[IdxSize; 2]>,
27) {
28    let mut iter = bounds_iter.into_iter();
29    let mut stride = 0;
30
31    'bounds: while let Some(bi) = iter.nth(stride) {
32        if let Some(placement) = placement {
33            if placement.start_range.is_past(bi.start) {
34                break;
35            }
36            if placement.start_range.is_before(bi.start) {
37                // Skip windows that start before the range. `get_stride` never overshoots,
38                // so windows close to the range are still visited one by one.
39                stride = iter.get_stride(placement.start_range.start());
40                continue 'bounds;
41            }
42        }
43
44        let mut has_member = false;
45        // find starting point of window
46        for &t in &time[start..time.len().saturating_sub(1)] {
47            // the window is behind the time values.
48            if bi.is_future(t, closed_window) {
49                stride = iter.get_stride(t);
50                continue 'bounds;
51            }
52            if bi.is_member_entry(t, closed_window) {
53                has_member = true;
54                break;
55            }
56            // element drops out of the window
57            start += 1;
58        }
59
60        // update stride so we can fast-forward in case of sparse data
61        stride = if has_member {
62            0
63        } else {
64            debug_assert!(start < time.len());
65            iter.get_stride(time[start])
66        };
67
68        // find members of this window
69        let mut end = start;
70
71        // last value isn't always added
72        if end == time.len() - 1 {
73            let t = time[end];
74            if bi.is_member(t, closed_window) {
75                if include_lower_bound {
76                    lower_bound.push(bi.start);
77                }
78                if include_upper_bound {
79                    upper_bound.push(bi.stop);
80                }
81                groups.push([end as IdxSize, 1])
82            }
83            continue;
84        }
85        for &t in &time[end..] {
86            if !bi.is_member_exit(t, closed_window) {
87                break;
88            }
89            end += 1;
90        }
91        let len = end - start;
92
93        if include_lower_bound {
94            lower_bound.push(bi.start);
95        }
96        if include_upper_bound {
97            upper_bound.push(bi.stop);
98        }
99        groups.push([start as IdxSize, len as IdxSize])
100    }
101}
102
103/// Window boundaries are created based on the given `Window`, which is defined by:
104/// - every
105/// - period
106/// - offset
107///
108/// And every window boundary we search for the values that fit that window by the given
109/// `ClosedWindow`. The groups are returned as `GroupTuples` together with the lower bound and upper
110/// bound timestamps. These timestamps indicate the start (lower) and end (upper) of the window of
111/// that group.
112///
113/// If `include_boundaries` is `false` those `lower` and `upper` vectors will be empty.
114#[allow(clippy::too_many_arguments)]
115pub fn group_by_windows(
116    window: Window,
117    time: &[i64],
118    closed_window: ClosedWindow,
119    tu: TimeUnit,
120    tz: &Option<TimeZone>,
121    include_lower_bound: bool,
122    include_upper_bound: bool,
123    start_by: StartBy,
124    placement: Option<DynamicWindowPlacement>,
125) -> PolarsResult<(GroupsSlice, Vec<i64>, Vec<i64>)> {
126    let start = time[0];
127    // the boundary we define here is not yet correct. It doesn't take 'period' into account
128    // and it doesn't have the proper starting point. This boundary is used as a proxy to find
129    // the proper 'boundary' in  'window.get_overlapping_bounds_iter'.
130    let boundary = if time.len() > 1 {
131        // +1 because left or closed boundary could match the next window if it is on the boundary
132        let stop = time[time.len() - 1] + 1;
133        Bounds::new_checked(start, stop)
134    } else {
135        let stop = start + 1;
136        Bounds::new_checked(start, stop)
137    };
138
139    let size = window.estimate_overlapping_bounds(tu, boundary);
140    let size_lower = if include_lower_bound { size } else { 0 };
141    let size_upper = if include_upper_bound { size } else { 0 };
142    let mut lower_bound = Vec::with_capacity(size_lower);
143    let mut upper_bound = Vec::with_capacity(size_upper);
144
145    let mut groups = Vec::with_capacity(size);
146    let start_offset = 0;
147
148    match tz {
149        #[cfg(feature = "timezones")]
150        Some(tz) => {
151            update_groups_and_bounds(
152                window.get_overlapping_bounds_iter(
153                    boundary,
154                    closed_window,
155                    tu,
156                    tz.parse::<Tz>().ok().as_ref(),
157                    start_by,
158                    placement.map(|p| p.origin),
159                )?,
160                start_offset,
161                time,
162                closed_window,
163                include_lower_bound,
164                include_upper_bound,
165                placement.as_ref(),
166                &mut lower_bound,
167                &mut upper_bound,
168                &mut groups,
169            );
170        },
171        _ => {
172            update_groups_and_bounds(
173                window.get_overlapping_bounds_iter(
174                    boundary,
175                    closed_window,
176                    tu,
177                    None,
178                    start_by,
179                    placement.map(|p| p.origin),
180                )?,
181                start_offset,
182                time,
183                closed_window,
184                include_lower_bound,
185                include_upper_bound,
186                placement.as_ref(),
187                &mut lower_bound,
188                &mut upper_bound,
189                &mut groups,
190            );
191        },
192    };
193
194    Ok((groups, lower_bound, upper_bound))
195}
196
197// t is right at the end of the window
198// ------t---
199// [------]
200#[inline]
201#[allow(clippy::too_many_arguments)]
202pub(crate) fn group_by_values_iter_lookbehind(
203    period: Duration,
204    offset: Duration,
205    time: &[i64],
206    closed_window: ClosedWindow,
207    tu: TimeUnit,
208    tz: Option<Tz>,
209    start_offset: usize,
210    upper_bound: Option<usize>,
211) -> PolarsResult<impl TrustedLen<Item = PolarsResult<(IdxSize, IdxSize)>> + '_> {
212    debug_assert_eq!(offset, -period);
213
214    let upper_bound = upper_bound.unwrap_or(time.len());
215    // Use binary search to find the initial start as that is behind.
216    let mut start = if let Some(&t) = time.get(start_offset) {
217        let lower = offset.add(tu, t, tz.as_ref())?;
218        // We have `period == -offset`, so `t + offset + period` is equal to `t`,
219        // and `upper` is trivially equal to `t` itself. Using the trivial calculation,
220        // instead of `upper = lower + period`, avoids issues around
221        // `t - 1mo + 1mo` not round-tripping.
222        let upper = t;
223        let b = Bounds::new(lower, upper);
224        let slice = &time[..start_offset];
225        slice.partition_point(|v| !b.is_member(*v, closed_window))
226    } else {
227        0
228    };
229    let mut end = start;
230    let mut last = time[start_offset];
231    Ok(time[start_offset..upper_bound]
232        .iter()
233        .enumerate()
234        .map(move |(mut i, t)| {
235            // Fast path for duplicates.
236            if *t == last && i > 0 {
237                let len = end - start;
238                let offset = start as IdxSize;
239                return Ok((offset, len as IdxSize));
240            }
241            last = *t;
242            i += start_offset;
243
244            let lower = offset.add(tu, *t, tz.as_ref())?;
245            let upper = *t;
246
247            let b = Bounds::new(lower, upper);
248
249            for &t in unsafe { time.get_unchecked(start..i) } {
250                if b.is_member_entry(t, closed_window) {
251                    break;
252                }
253                start += 1;
254            }
255
256            // faster path, check if `i` is member.
257            if b.is_member_exit(*t, closed_window) {
258                end = i;
259            } else {
260                end = std::cmp::max(end, start);
261            }
262            // we still must loop to consume duplicates
263            for &t in unsafe { time.get_unchecked(end..) } {
264                if !b.is_member_exit(t, closed_window) {
265                    break;
266                }
267                end += 1;
268            }
269
270            let len = end - start;
271            let offset = start as IdxSize;
272
273            Ok((offset, len as IdxSize))
274        }))
275}
276
277// this one is correct for all lookbehind/lookaheads, but is slower
278// window is completely behind t and t itself is not a member
279// ---------------t---
280//  [---]
281#[allow(clippy::too_many_arguments)]
282pub(crate) fn group_by_values_iter_window_behind_t(
283    period: Duration,
284    offset: Duration,
285    time: &[i64],
286    closed_window: ClosedWindow,
287    tu: TimeUnit,
288    tz: Option<Tz>,
289    start_offset: usize,
290    upper_bound: Option<usize>,
291) -> PolarsResult<impl TrustedLen<Item = PolarsResult<(IdxSize, IdxSize)>> + '_> {
292    let upper_bound = upper_bound.unwrap_or(time.len());
293    let mut start = first_member_row(period, offset, time, closed_window, tu, tz, start_offset)?;
294    let mut end = start;
295    let mut last = time[start_offset];
296    let mut started = false;
297    Ok(time[start_offset..upper_bound].iter().map(move |lower| {
298        // Fast path for duplicates.
299        if *lower == last && started {
300            let len = end - start;
301            let offset = start as IdxSize;
302            return Ok((offset, len as IdxSize));
303        }
304        last = *lower;
305        started = true;
306        let lower = offset.add(tu, *lower, tz.as_ref())?;
307        let upper = period.add(tu, lower, tz.as_ref())?;
308
309        let b = Bounds::new(lower, upper);
310        if b.is_future(time[0], closed_window) {
311            Ok((0, 0))
312        } else {
313            for &t in &time[start..] {
314                if b.is_member_entry(t, closed_window) {
315                    break;
316                }
317                start += 1;
318            }
319
320            end = std::cmp::max(start, end);
321            for &t in &time[end..] {
322                if !b.is_member_exit(t, closed_window) {
323                    break;
324                }
325                end += 1;
326            }
327
328            let len = end - start;
329            let offset = start as IdxSize;
330
331            Ok((offset, len as IdxSize))
332        }
333    }))
334}
335
336// window is within -1 periods of t
337// ----t---
338//  [---]
339#[allow(clippy::too_many_arguments)]
340pub(crate) fn group_by_values_iter_partial_lookbehind(
341    period: Duration,
342    offset: Duration,
343    time: &[i64],
344    closed_window: ClosedWindow,
345    tu: TimeUnit,
346    tz: Option<Tz>,
347    start_offset: usize,
348    upper_bound: Option<usize>,
349) -> PolarsResult<impl TrustedLen<Item = PolarsResult<(IdxSize, IdxSize)>> + '_> {
350    let upper_bound = upper_bound.unwrap_or(time.len());
351    let mut start = first_member_row(period, offset, time, closed_window, tu, tz, start_offset)?;
352    let mut end = start;
353    let mut last = time[start_offset];
354    let rows = &time[start_offset..upper_bound];
355    Ok(rows.iter().enumerate().map(move |(i, lower)| {
356        // Fast path for duplicates.
357        if *lower == last && i > 0 {
358            let len = end - start;
359            let offset = start as IdxSize;
360            return Ok((offset, len as IdxSize));
361        }
362        last = *lower;
363        let i = i + start_offset;
364
365        let lower = offset.add(tu, *lower, tz.as_ref())?;
366        let upper = period.add(tu, lower, tz.as_ref())?;
367
368        let b = Bounds::new(lower, upper);
369
370        for &t in &time[start..] {
371            if b.is_member_entry(t, closed_window) || start == i {
372                break;
373            }
374            start += 1;
375        }
376
377        end = std::cmp::max(start, end);
378        for &t in &time[end..] {
379            if !b.is_member_exit(t, closed_window) {
380                break;
381            }
382            end += 1;
383        }
384
385        let len = end - start;
386        let offset = start as IdxSize;
387
388        Ok((offset, len as IdxSize))
389    }))
390}
391
392/// The first row of `time[..start_offset]` that can be a member of the window of row
393/// `start_offset`, so a window search need not walk the rows before it.
394fn first_member_row(
395    period: Duration,
396    offset: Duration,
397    time: &[i64],
398    closed_window: ClosedWindow,
399    tu: TimeUnit,
400    tz: Option<Tz>,
401    start_offset: usize,
402) -> PolarsResult<usize> {
403    let lower = offset.add(tu, time[start_offset], tz.as_ref())?;
404    let upper = period.add(tu, lower, tz.as_ref())?;
405    let b = Bounds::new(lower, upper);
406    Ok(time[..start_offset].partition_point(|&t| !b.is_member_entry(t, closed_window)))
407}
408
409#[allow(clippy::too_many_arguments)]
410// window is completely ahead of t and t itself is not a member
411// --t-----------
412//        [---]
413pub(crate) fn group_by_values_iter_lookahead(
414    period: Duration,
415    offset: Duration,
416    time: &[i64],
417    closed_window: ClosedWindow,
418    tu: TimeUnit,
419    tz: Option<Tz>,
420    start_offset: usize,
421    upper_bound: Option<usize>,
422) -> impl TrustedLen<Item = PolarsResult<(IdxSize, IdxSize)>> + '_ {
423    let upper_bound = upper_bound.unwrap_or(time.len());
424
425    let mut start = start_offset;
426    let mut end = start;
427
428    let mut last = time[start_offset];
429    let mut started = false;
430    time[start_offset..upper_bound].iter().map(move |lower| {
431        // Fast path for duplicates.
432        if *lower == last && started {
433            let len = end - start;
434            let offset = start as IdxSize;
435            return Ok((offset, len as IdxSize));
436        }
437        started = true;
438        last = *lower;
439
440        let lower = offset.add(tu, *lower, tz.as_ref())?;
441        let upper = period.add(tu, lower, tz.as_ref())?;
442
443        let b = Bounds::new(lower, upper);
444
445        for &t in &time[start..] {
446            if b.is_member_entry(t, closed_window) {
447                break;
448            }
449            start += 1;
450        }
451
452        end = std::cmp::max(start, end);
453        for &t in &time[end..] {
454            if !b.is_member_exit(t, closed_window) {
455                break;
456            }
457            end += 1;
458        }
459
460        let len = end - start;
461        let offset = start as IdxSize;
462
463        Ok((offset, len as IdxSize))
464    })
465}
466
467/// Checks if the boundary elements don't split on duplicates.
468/// If they do we remove them
469fn prune_splits_on_duplicates(time: &[i64], thread_offsets: &mut Vec<(usize, usize)>) {
470    let is_valid = |window: &[(usize, usize)]| -> bool {
471        debug_assert_eq!(window.len(), 2);
472        let left_block_end = window[0].0 + window[0].1.saturating_sub(1);
473        let right_block_start = window[1].0;
474        time[left_block_end] != time[right_block_start]
475    };
476
477    if time.is_empty() || thread_offsets.len() <= 1 || thread_offsets.windows(2).all(is_valid) {
478        return;
479    }
480
481    let mut new = vec![];
482    for window in thread_offsets.windows(2) {
483        let this_block_is_valid = is_valid(window);
484        if this_block_is_valid {
485            // Only push left block
486            new.push(window[0])
487        }
488    }
489    // Check last block
490    if thread_offsets.len().is_multiple_of(2) {
491        let window = &thread_offsets[thread_offsets.len() - 2..];
492        if is_valid(window) {
493            new.push(thread_offsets[thread_offsets.len() - 1])
494        }
495    }
496    // We pruned invalid blocks, now we must correct the lengths.
497    if new.len() <= 1 {
498        new = vec![(0, time.len())];
499    } else {
500        let mut previous_start = time.len();
501        for window in new.iter_mut().rev() {
502            window.1 = previous_start - window.0;
503            previous_start = window.0;
504        }
505        new[0].0 = 0;
506        new[0].1 = new[1].0;
507        debug_assert_eq!(new.iter().map(|w| w.1).sum::<usize>(), time.len());
508        // Call again to check.
509        prune_splits_on_duplicates(time, &mut new)
510    }
511    std::mem::swap(thread_offsets, &mut new);
512}
513
514#[allow(clippy::too_many_arguments)]
515pub(crate) fn group_by_values_iter_lookbehind_collected(
516    period: Duration,
517    offset: Duration,
518    time: &[i64],
519    closed_window: ClosedWindow,
520    tu: TimeUnit,
521    tz: Option<Tz>,
522    start_offset: usize,
523    upper_bound: Option<usize>,
524) -> PolarsResult<Vec<[IdxSize; 2]>> {
525    let iter = group_by_values_iter_lookbehind(
526        period,
527        offset,
528        time,
529        closed_window,
530        tu,
531        tz,
532        start_offset,
533        upper_bound,
534    )?;
535    let mut windows = Vec::with_capacity(iter.size_hint().0);
536    for result in iter {
537        let (offset, len) = result?;
538        windows.push([offset, len]);
539    }
540    Ok(windows)
541}
542
543#[allow(clippy::too_many_arguments)]
544pub(crate) fn group_by_values_iter_lookahead_collected(
545    period: Duration,
546    offset: Duration,
547    time: &[i64],
548    closed_window: ClosedWindow,
549    tu: TimeUnit,
550    tz: Option<Tz>,
551    start_offset: usize,
552    upper_bound: Option<usize>,
553) -> PolarsResult<Vec<[IdxSize; 2]>> {
554    let iter = group_by_values_iter_lookahead(
555        period,
556        offset,
557        time,
558        closed_window,
559        tu,
560        tz,
561        start_offset,
562        upper_bound,
563    );
564    iter.map(|result| result.map(|(offset, len)| [offset as IdxSize, len]))
565        .collect::<PolarsResult<Vec<_>>>()
566}
567
568/// Different from `group_by_windows`, where define window buckets and search which values fit that
569/// pre-defined bucket.
570///
571/// This function defines every window based on the:
572///     - timestamp (lower bound)
573///     - timestamp + period (upper bound)
574/// where timestamps are the individual values in the array `time`
575///
576/// Only the rows in `rows` get a window; the windows still index into the whole of `time`.
577/// `rows` must not start or end inside a run of equal values.
578pub fn group_by_values(
579    period: Duration,
580    offset: Duration,
581    time: &[i64],
582    closed_window: ClosedWindow,
583    tu: TimeUnit,
584    tz: Option<Tz>,
585    rows: std::ops::Range<usize>,
586) -> PolarsResult<GroupsSlice> {
587    if rows.is_empty() {
588        return Ok(GroupsSlice::from(vec![]));
589    }
590    assert!(rows.start == 0 || time[rows.start - 1] < time[rows.start]);
591    assert!(rows.end == time.len() || time[rows.end - 1] < time[rows.end]);
592    let (start_offset, upper_bound) = (rows.start, rows.end);
593
594    // The threads split the whole of `time` and each takes the part of its split inside `rows`,
595    // so the windows do not depend on `rows`.
596    let mut thread_offsets = _split_offsets(time.len(), RAYON.current_num_threads());
597    // there are duplicates in the splits, so we opt for a single partition
598    prune_splits_on_duplicates(time, &mut thread_offsets);
599    thread_offsets.retain_mut(|(offset, len)| {
600        let start = (*offset).max(start_offset);
601        let end = (*offset + *len).min(upper_bound);
602        (*offset, *len) = (start, end.saturating_sub(start));
603        *len > 0
604    });
605
606    // If we start from within parallel work we will do this single threaded.
607    let run_parallel = !RAYON.current_thread_has_pending_tasks().unwrap_or(false);
608
609    // we have a (partial) lookbehind window
610    if offset.negative && !offset.is_zero() {
611        // lookbehind
612        if offset == -period {
613            // t is right at the end of the window
614            // ------t---
615            // [------]
616            if !run_parallel {
617                let vecs = group_by_values_iter_lookbehind_collected(
618                    period,
619                    offset,
620                    time,
621                    closed_window,
622                    tu,
623                    tz,
624                    start_offset,
625                    Some(upper_bound),
626                )?;
627                return Ok(GroupsSlice::from(vecs));
628            }
629
630            RAYON.install(|| {
631                let vals = thread_offsets
632                    .par_iter()
633                    .copied()
634                    .map(|(base_offset, len)| {
635                        let upper_bound = base_offset + len;
636                        group_by_values_iter_lookbehind_collected(
637                            period,
638                            offset,
639                            time,
640                            closed_window,
641                            tu,
642                            tz,
643                            base_offset,
644                            Some(upper_bound),
645                        )
646                    })
647                    .collect::<PolarsResult<Vec<_>>>()?;
648                Ok(flatten_par(&vals))
649            })
650        } else if ((offset.duration_ns() >= period.duration_ns())
651            && matches!(closed_window, ClosedWindow::Left | ClosedWindow::None))
652            || ((offset.duration_ns() > period.duration_ns())
653                && matches!(closed_window, ClosedWindow::Right | ClosedWindow::Both))
654        {
655            // The window is likely completely behind t. `duration_ns` is only an estimate for
656            // calendar units, but both this and the partial lookbehind below are correct for any
657            // negative offset, so it only picks the faster one.
658            // ---------------t---
659            //  [---]
660            let iter = group_by_values_iter_window_behind_t(
661                period,
662                offset,
663                time,
664                closed_window,
665                tu,
666                tz,
667                start_offset,
668                Some(upper_bound),
669            )?;
670            iter.map(|result| result.map(|(offset, len)| [offset, len]))
671                .collect::<PolarsResult<_>>()
672        }
673        // partial lookbehind
674        // this one is still single threaded
675        // can make it parallel later, it's a bit more complicated because the boundaries are unknown
676        // window is within -1 periods of t
677        // ----t---
678        //  [---]
679        else {
680            let iter = group_by_values_iter_partial_lookbehind(
681                period,
682                offset,
683                time,
684                closed_window,
685                tu,
686                tz,
687                start_offset,
688                Some(upper_bound),
689            )?;
690            iter.map(|result| result.map(|(offset, len)| [offset, len]))
691                .collect::<PolarsResult<_>>()
692        }
693    } else if !offset.is_zero()
694        || closed_window == ClosedWindow::Right
695        || closed_window == ClosedWindow::None
696    {
697        // window is completely ahead of t and t itself is not a member
698        // --t-----------
699        //        [---]
700
701        if !run_parallel {
702            let vecs = group_by_values_iter_lookahead_collected(
703                period,
704                offset,
705                time,
706                closed_window,
707                tu,
708                tz,
709                start_offset,
710                Some(upper_bound),
711            )?;
712            return Ok(GroupsSlice::from(vecs));
713        }
714
715        RAYON.install(|| {
716            let vals = thread_offsets
717                .par_iter()
718                .copied()
719                .map(|(base_offset, len)| {
720                    let lower_bound = base_offset;
721                    let upper_bound = base_offset + len;
722                    group_by_values_iter_lookahead_collected(
723                        period,
724                        offset,
725                        time,
726                        closed_window,
727                        tu,
728                        tz,
729                        lower_bound,
730                        Some(upper_bound),
731                    )
732                })
733                .collect::<PolarsResult<Vec<_>>>()?;
734            Ok(flatten_par(&vals))
735        })
736    } else {
737        if !run_parallel {
738            let vecs = group_by_values_iter_lookahead_collected(
739                period,
740                offset,
741                time,
742                closed_window,
743                tu,
744                tz,
745                start_offset,
746                Some(upper_bound),
747            )?;
748            return Ok(GroupsSlice::from(vecs));
749        }
750
751        // Offset is 0 and window is closed on the left:
752        // it must be that the window starts at t and t is a member
753        // --t-----------
754        //  [---]
755        RAYON.install(|| {
756            let vals = thread_offsets
757                .par_iter()
758                .copied()
759                .map(|(base_offset, len)| {
760                    let lower_bound = base_offset;
761                    let upper_bound = base_offset + len;
762                    group_by_values_iter_lookahead_collected(
763                        period,
764                        offset,
765                        time,
766                        closed_window,
767                        tu,
768                        tz,
769                        lower_bound,
770                        Some(upper_bound),
771                    )
772                })
773                .collect::<PolarsResult<Vec<_>>>()?;
774            Ok(flatten_par(&vals))
775        })
776    }
777}
778
779pub struct RollingWindower {
780    period: Duration,
781    offset: Duration,
782    closed: ClosedWindow,
783
784    tu: TimeUnit,
785    tz: Option<Tz>,
786
787    start: IdxSize,
788    end: IdxSize,
789    length: IdxSize,
790
791    active: VecDeque<ActiveWindow>,
792}
793
794struct ActiveWindow {
795    start: i64,
796    end: i64,
797}
798
799impl ActiveWindow {
800    #[inline(always)]
801    fn above_lower_bound(&self, t: i64, closed: ClosedWindow) -> bool {
802        (t > self.start)
803            | (matches!(closed, ClosedWindow::Left | ClosedWindow::Both) & (t == self.start))
804    }
805
806    #[inline(always)]
807    fn below_upper_bound(&self, t: i64, closed: ClosedWindow) -> bool {
808        (t < self.end)
809            | (matches!(closed, ClosedWindow::Right | ClosedWindow::Both) & (t == self.end))
810    }
811}
812
813fn skip_in_2d_list(l: &[&[i64]], mut n: usize) -> (usize, usize) {
814    let mut y = 0;
815    while y < l.len() && (n >= l[y].len() || l[y].is_empty()) {
816        n -= l[y].len();
817        y += 1;
818    }
819    assert!(n == 0 || y < l.len());
820    (n, y)
821}
822fn increment_2d(x: &mut usize, y: &mut usize, l: &[&[i64]]) {
823    *x += 1;
824    while *y < l.len() && *x == l[*y].len() {
825        *y += 1;
826        *x = 0;
827    }
828}
829
830impl RollingWindower {
831    pub fn new(
832        period: Duration,
833        offset: Duration,
834        closed: ClosedWindow,
835        tu: TimeUnit,
836        tz: Option<Tz>,
837    ) -> Self {
838        Self {
839            period,
840            offset,
841            closed,
842
843            tu,
844            tz,
845
846            start: 0,
847            end: 0,
848            length: 0,
849
850            active: Default::default(),
851        }
852    }
853
854    /// Insert new values into the windower.
855    ///
856    /// This should be given all the old values that were not processed yet.
857    pub fn insert(
858        &mut self,
859        time: &[&[i64]],
860        windows: &mut Vec<[IdxSize; 2]>,
861    ) -> PolarsResult<IdxSize> {
862        let (mut i_x, mut i_y) = skip_in_2d_list(time, (self.length - self.start) as usize);
863        let (mut s_x, mut s_y) = skip_in_2d_list(time, 0); // skip over empty lists
864        let (mut e_x, mut e_y) = skip_in_2d_list(time, (self.end - self.start) as usize);
865
866        let time_start = self.start;
867        let mut i = self.length;
868        while i_y < time.len() {
869            let t = time[i_y][i_x];
870            let window_start = self.offset.add(self.tu, t, self.tz.as_ref())?;
871            // For datetime arithmetic, it does *NOT* hold 0 + a - a == 0. Therefore, we make sure
872            // that if `offset` and `period` are inverses we keep the `t`.
873            let window_end = if self.offset == -self.period {
874                t
875            } else {
876                self.period.add(self.tu, window_start, self.tz.as_ref())?
877            };
878
879            self.active.push_back(ActiveWindow {
880                start: window_start,
881                end: window_end,
882            });
883
884            while let Some(w) = self.active.front() {
885                if w.below_upper_bound(t, self.closed) {
886                    break;
887                }
888
889                let w = self.active.pop_front().unwrap();
890                while self.start < i && !w.above_lower_bound(time[s_y][s_x], self.closed) {
891                    increment_2d(&mut s_x, &mut s_y, time);
892                    self.start += 1;
893                }
894                while self.end < i && w.below_upper_bound(time[e_y][e_x], self.closed) {
895                    increment_2d(&mut e_x, &mut e_y, time);
896                    self.end += 1;
897                }
898                windows.push([self.start, self.end - self.start]);
899            }
900
901            increment_2d(&mut i_x, &mut i_y, time);
902            i += 1;
903        }
904
905        self.length = i;
906        Ok(self.start - time_start)
907    }
908
909    /// Process all remaining items and signal that no more items are coming.
910    pub fn finalize(&mut self, time: &[&[i64]], windows: &mut Vec<[IdxSize; 2]>) {
911        assert_eq!(
912            time.iter().map(|t| t.len()).sum::<usize>() as IdxSize,
913            self.length - self.start
914        );
915
916        let (mut s_x, mut s_y) = skip_in_2d_list(time, 0);
917        let (mut e_x, mut e_y) = skip_in_2d_list(time, (self.end - self.start) as usize);
918
919        windows.extend(self.active.drain(..).map(|w| {
920            while self.start < self.length && !w.above_lower_bound(time[s_y][s_x], self.closed) {
921                increment_2d(&mut s_x, &mut s_y, time);
922                self.start += 1;
923            }
924            while self.end < self.length && w.below_upper_bound(time[e_y][e_x], self.closed) {
925                increment_2d(&mut e_x, &mut e_y, time);
926                self.end += 1;
927            }
928            [self.start, self.end - self.start]
929        }));
930
931        self.start = 0;
932        self.end = 0;
933        self.length = 0;
934    }
935
936    pub fn reset(&mut self) {
937        self.active.clear();
938        self.start = 0;
939        self.end = 0;
940        self.length = 0;
941    }
942}
943
944#[derive(Debug)]
945struct ActiveDynWindow {
946    start: IdxSize,
947    end: Option<IdxSize>,
948    lower_bound: i64,
949    upper_bound: i64,
950}
951
952#[inline(always)]
953fn is_above_lower_bound(t: i64, lb: i64, closed: ClosedWindow) -> bool {
954    (t > lb) | (matches!(closed, ClosedWindow::Left | ClosedWindow::Both) & (t == lb))
955}
956#[inline(always)]
957fn is_below_upper_bound(t: i64, ub: i64, closed: ClosedWindow) -> bool {
958    (t < ub) | (matches!(closed, ClosedWindow::Right | ClosedWindow::Both) & (t == ub))
959}
960
961pub struct GroupByDynamicWindower {
962    period: Duration,
963    offset: Duration,
964    every: Duration,
965    closed: ClosedWindow,
966
967    start_by: StartBy,
968
969    tu: TimeUnit,
970    tz: Option<Tz>,
971
972    include_lower_bound: bool,
973    include_upper_bound: bool,
974
975    placement: Option<DynamicWindowPlacement>,
976    /// No window can start in the placement's range any more.
977    past_range: bool,
978
979    num_seen: IdxSize,
980    /// Window `k` starts at `origin + every * k`.
981    origin: i64,
982    /// Index and start of the next window that may open.
983    next_k: i64,
984    next_lower_bound: i64,
985    active: VecDeque<ActiveDynWindow>,
986
987    /// Upper bound of the most recently opened window.
988    prev_upper_bound: Option<i64>,
989    // Kept track of because of clamping/DST
990    non_monotonic_upper_bounds: bool,
991}
992
993impl GroupByDynamicWindower {
994    #[expect(clippy::too_many_arguments)]
995    pub fn new(
996        period: Duration,
997        offset: Duration,
998        every: Duration,
999        start_by: StartBy,
1000        closed: ClosedWindow,
1001        tu: TimeUnit,
1002        tz: Option<Tz>,
1003        include_lower_bound: bool,
1004        include_upper_bound: bool,
1005        placement: Option<DynamicWindowPlacement>,
1006    ) -> Self {
1007        Self {
1008            period,
1009            offset,
1010            every,
1011            closed,
1012
1013            start_by,
1014
1015            tu,
1016            tz,
1017
1018            include_lower_bound,
1019            include_upper_bound,
1020
1021            placement,
1022            past_range: false,
1023
1024            num_seen: 0,
1025            origin: 0,
1026            next_k: 0,
1027            next_lower_bound: 0,
1028            active: Default::default(),
1029            prev_upper_bound: None,
1030            non_monotonic_upper_bounds: false,
1031        }
1032    }
1033
1034    fn window_start(&self, k: i64) -> PolarsResult<i64> {
1035        (self.every * k).add(self.tu, self.origin, self.tz.as_ref())
1036    }
1037
1038    /// Find the first window from window `k` on whose upper bound is not behind `target`.
1039    /// Returns its index and bounds if it contains `target`, otherwise its index and start.
1040    fn find_first_window_around(&self, mut k: i64, target: i64) -> PolarsResult<FirstWindowAround> {
1041        let mut lower_bound = self.window_start(k)?;
1042        let mut upper_bound = self.period.add(self.tu, lower_bound, self.tz.as_ref())?;
1043        while !is_below_upper_bound(target, upper_bound, self.closed) {
1044            let gap = target - lower_bound;
1045            let every = self.every.nte_duration(self.tu);
1046            let period = self.period.nte_duration(self.tu);
1047            let nth = if gap > every + period {
1048                (gap - period) / every
1049            } else {
1050                1
1051            };
1052
1053            k += nth;
1054            lower_bound = self.window_start(k)?;
1055            upper_bound = self.period.add(self.tu, lower_bound, self.tz.as_ref())?;
1056        }
1057
1058        if is_above_lower_bound(target, lower_bound, self.closed) {
1059            Ok(FirstWindowAround::ContainingTarget {
1060                k,
1061                lower_bound,
1062                upper_bound,
1063            })
1064        } else {
1065            Ok(FirstWindowAround::NotContainingTarget { k, lower_bound })
1066        }
1067    }
1068
1069    fn start_lower_bound(&self, first: i64) -> PolarsResult<i64> {
1070        match self.placement {
1071            Some(placement) => Ok(placement.origin),
1072            None => Window::new(self.every, self.period, self.offset).first_window_start(
1073                first,
1074                self.closed,
1075                self.tu,
1076                self.tz.as_ref(),
1077                self.start_by,
1078            ),
1079        }
1080    }
1081
1082    pub fn insert(
1083        &mut self,
1084        time: &[i64],
1085        windows: &mut Vec<[IdxSize; 2]>,
1086        lower_bound: &mut Vec<i64>,
1087        upper_bound: &mut Vec<i64>,
1088    ) -> PolarsResult<()> {
1089        if time.is_empty() {
1090            return Ok(());
1091        }
1092
1093        if self.num_seen == 0 {
1094            debug_assert!(self.active.is_empty());
1095            self.origin = self.start_lower_bound(time[0])?;
1096            self.next_k = 0;
1097            self.next_lower_bound = self.origin;
1098        }
1099
1100        for &t in time {
1101            // Close every window that `t` has moved past.
1102            // This sets flags for monotonicity.
1103            if self.non_monotonic_upper_bounds {
1104                for w in self.active.iter_mut() {
1105                    if w.end.is_none() && !is_below_upper_bound(t, w.upper_bound, self.closed) {
1106                        w.end = Some(self.num_seen);
1107                    }
1108                }
1109
1110                while let Some(w) = self.active.front()
1111                    && w.end.is_some()
1112                {
1113                    let w = self.active.pop_front().unwrap();
1114                    Self::emit(
1115                        &w,
1116                        self.num_seen,
1117                        self.include_lower_bound,
1118                        self.include_upper_bound,
1119                        windows,
1120                        lower_bound,
1121                        upper_bound,
1122                    );
1123                }
1124            } else {
1125                while let Some(w) = self.active.front()
1126                    && !is_below_upper_bound(t, w.upper_bound, self.closed)
1127                {
1128                    let w = self.active.pop_front().unwrap();
1129                    Self::emit(
1130                        &w,
1131                        self.num_seen,
1132                        self.include_lower_bound,
1133                        self.include_upper_bound,
1134                        windows,
1135                        lower_bound,
1136                        upper_bound,
1137                    );
1138                }
1139            }
1140
1141            while !self.past_range && is_above_lower_bound(t, self.next_lower_bound, self.closed) {
1142                match self.find_first_window_around(self.next_k, t)? {
1143                    FirstWindowAround::ContainingTarget {
1144                        k,
1145                        lower_bound,
1146                        upper_bound,
1147                    } => {
1148                        self.next_k = k + 1;
1149                        self.next_lower_bound = self.window_start(self.next_k)?;
1150                        if let Some(placement) = &self.placement {
1151                            if placement.start_range.is_past(lower_bound) {
1152                                self.past_range = true;
1153                                break;
1154                            }
1155                            if placement.start_range.is_before(lower_bound) {
1156                                continue;
1157                            }
1158                        }
1159                        self.non_monotonic_upper_bounds |=
1160                            self.prev_upper_bound.is_some_and(|prev| upper_bound < prev);
1161                        self.prev_upper_bound = Some(upper_bound);
1162                        self.active.push_back(ActiveDynWindow {
1163                            start: self.num_seen,
1164                            end: None,
1165                            lower_bound,
1166                            upper_bound,
1167                        });
1168                    },
1169                    FirstWindowAround::NotContainingTarget { k, lower_bound } => {
1170                        self.next_k = k;
1171                        self.next_lower_bound = lower_bound;
1172                        break;
1173                    },
1174                }
1175            }
1176
1177            self.num_seen += 1
1178        }
1179
1180        Ok(())
1181    }
1182
1183    fn emit(
1184        w: &ActiveDynWindow,
1185        num_seen: IdxSize,
1186        include_lower_bound: bool,
1187        include_upper_bound: bool,
1188        windows: &mut Vec<[IdxSize; 2]>,
1189        lower_bound: &mut Vec<i64>,
1190        upper_bound: &mut Vec<i64>,
1191    ) {
1192        let end = w.end.unwrap_or(num_seen);
1193        windows.push([w.start, end - w.start]);
1194        if include_lower_bound {
1195            lower_bound.push(w.lower_bound);
1196        }
1197        if include_upper_bound {
1198            upper_bound.push(w.upper_bound);
1199        }
1200    }
1201
1202    pub fn lowest_needed_index(&self) -> IdxSize {
1203        self.active.front().map_or(self.num_seen, |w| w.start)
1204    }
1205
1206    /// Whether no further input can produce a window: every window that could start in the
1207    /// placement's range has been opened and closed.
1208    pub fn is_done(&self) -> bool {
1209        self.past_range && self.active.is_empty()
1210    }
1211
1212    pub fn finalize(
1213        &mut self,
1214        windows: &mut Vec<[IdxSize; 2]>,
1215        lower_bound: &mut Vec<i64>,
1216        upper_bound: &mut Vec<i64>,
1217    ) {
1218        let num_seen = self.num_seen;
1219        let (include_lower_bound, include_upper_bound) =
1220            (self.include_lower_bound, self.include_upper_bound);
1221        for w in self.active.drain(..) {
1222            Self::emit(
1223                &w,
1224                num_seen,
1225                include_lower_bound,
1226                include_upper_bound,
1227                windows,
1228                lower_bound,
1229                upper_bound,
1230            );
1231        }
1232
1233        self.origin = 0;
1234        self.next_k = 0;
1235        self.next_lower_bound = 0;
1236        self.num_seen = 0;
1237        self.prev_upper_bound = None;
1238        self.non_monotonic_upper_bounds = false;
1239        self.past_range = false;
1240    }
1241
1242    pub fn num_seen(&self) -> IdxSize {
1243        self.num_seen
1244    }
1245
1246    pub fn time_unit(&self) -> TimeUnit {
1247        self.tu
1248    }
1249}
1250
1251enum FirstWindowAround {
1252    ContainingTarget {
1253        k: i64,
1254        lower_bound: i64,
1255        upper_bound: i64,
1256    },
1257    NotContainingTarget {
1258        k: i64,
1259        lower_bound: i64,
1260    },
1261}
1262
1263#[cfg(test)]
1264mod test {
1265    use super::*;
1266
1267    #[test]
1268    fn test_prune_duplicates() {
1269        //                     |--|------------|----|---------|
1270        //                     0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
1271        let time = &[0, 1, 1, 2, 2, 2, 3, 4, 5, 6, 5];
1272        let mut splits = vec![(0, 2), (2, 4), (6, 2), (8, 3)];
1273        prune_splits_on_duplicates(time, &mut splits);
1274        assert_eq!(splits, &[(0, 6), (6, 2), (8, 3)]);
1275    }
1276}