Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/crates/polars-ops/src/chunked_array/peaks.rs
6939 views
1
use polars_core::prelude::*;
2
use polars_core::with_match_physical_numeric_polars_type;
3
4
pub fn peak_min_max(
5
column: &Column,
6
start: &AnyValue<'_>,
7
end: &AnyValue<'_>,
8
is_peak_max: bool,
9
) -> PolarsResult<BooleanChunked> {
10
let name = column.name().clone();
11
let column = column.to_physical_repr();
12
let column = column.as_materialized_series();
13
match column.dtype() {
14
dt if dt.is_bool() => {
15
let series = column.cast(&DataType::Int8)?;
16
let column = series.into_column();
17
peak_min_max(&column, start, end, is_peak_max)
18
},
19
dt if dt.is_primitive_numeric() => {
20
with_match_physical_numeric_polars_type!(dt, |$T| {
21
let ca: &ChunkedArray<$T> = column.as_ref().as_ref().as_ref();
22
let start = start.extract();
23
let end = end.extract();
24
Ok(if is_peak_max {
25
peak_max_with_start_end(ca, start, end)
26
} else {
27
peak_min_with_start_end(ca, start, end)
28
}.with_name(name))
29
})
30
},
31
dt => polars_bail!(opq = peak_max, dt),
32
}
33
}
34
35
/// Get a boolean mask of the local maximum peaks.
36
pub fn peak_max_with_start_end<T: PolarsNumericType>(
37
ca: &ChunkedArray<T>,
38
start: Option<T::Native>,
39
end: Option<T::Native>,
40
) -> BooleanChunked
41
where
42
ChunkedArray<T>: for<'a> ChunkCompareIneq<&'a ChunkedArray<T>, Item = BooleanChunked>,
43
{
44
let shift_left = ca.shift_and_fill(1, start);
45
let shift_right = ca.shift_and_fill(-1, end);
46
ChunkedArray::lt(&shift_left, ca) & ChunkedArray::lt(&shift_right, ca)
47
}
48
49
/// Get a boolean mask of the local minimum peaks.
50
pub fn peak_min_with_start_end<T: PolarsNumericType>(
51
ca: &ChunkedArray<T>,
52
start: Option<T::Native>,
53
end: Option<T::Native>,
54
) -> BooleanChunked
55
where
56
ChunkedArray<T>: for<'a> ChunkCompareIneq<&'a ChunkedArray<T>, Item = BooleanChunked>,
57
{
58
let shift_left = ca.shift_and_fill(1, start);
59
let shift_right = ca.shift_and_fill(-1, end);
60
ChunkedArray::gt(&shift_left, ca) & ChunkedArray::gt(&shift_right, ca)
61
}
62
63