polars_core/chunked_array/ops/sort/
options.rs

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
#[cfg(feature = "serde-lazy")]
use serde::{Deserialize, Serialize};
pub use slice::*;

use crate::prelude::*;

/// Options for single series sorting.
///
/// Indicating the order of sorting, nulls position, multithreading, and maintaining order.
///
/// # Example
///
/// ```
/// # use polars_core::prelude::*;
/// let s = Series::new("a".into(), [Some(5), Some(2), Some(3), Some(4), None].as_ref());
/// let sorted = s
///     .sort(
///         SortOptions::default()
///             .with_order_descending(true)
///             .with_nulls_last(true)
///             .with_multithreaded(false),
///     )
///     .unwrap();
/// assert_eq!(
///     sorted,
///     Series::new("a".into(), [Some(5), Some(4), Some(3), Some(2), None].as_ref())
/// );
/// ```
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
#[cfg_attr(feature = "serde-lazy", derive(Serialize, Deserialize))]
pub struct SortOptions {
    /// If true sort in descending order.
    /// Default `false`.
    pub descending: bool,
    /// Whether place null values last.
    /// Default `false`.
    pub nulls_last: bool,
    /// If true sort in multiple threads.
    /// Default `true`.
    pub multithreaded: bool,
    /// If true maintain the order of equal elements.
    /// Default `false`.
    pub maintain_order: bool,
    /// Limit a sort output, this is for optimization purposes and might be ignored.
    /// - Len
    /// - Descending
    pub limit: Option<(IdxSize, bool)>,
}

/// Sort options for multi-series sorting.
///
/// Indicating the order of sorting, nulls position, multithreading, and maintaining order.
///
/// # Example
/// ```
/// # use polars_core::prelude::*;
///
/// # fn main() -> PolarsResult<()> {
/// let df = df! {
///     "a" => [Some(1), Some(2), None, Some(4), None],
///     "b" => [Some(5), None, Some(3), Some(2), Some(1)]
/// }?;
///
/// let out = df
///     .sort(
///         ["a", "b"],
///         SortMultipleOptions::default()
///             .with_maintain_order(true)
///             .with_multithreaded(false)
///             .with_order_descending_multi([false, true])
///             .with_nulls_last(true),
///     )?;
///
/// let expected = df! {
///     "a" => [Some(1), Some(2), Some(4), None, None],
///     "b" => [Some(5), None, Some(2), Some(3), Some(1)]
/// }?;
///
/// assert_eq!(out, expected);
///
/// # Ok(())
/// # }
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde-lazy", derive(Serialize, Deserialize))]
pub struct SortMultipleOptions {
    /// Order of the columns. Default all `false``.
    ///
    /// If only one value is given, it will broadcast to all columns.
    ///
    /// Use [`SortMultipleOptions::with_order_descending_multi`]
    /// or [`SortMultipleOptions::with_order_descending`] to modify.
    ///
    /// # Safety
    ///
    /// Len must match the number of columns, or equal 1.
    pub descending: Vec<bool>,
    /// Whether place null values last. Default `false`.
    pub nulls_last: Vec<bool>,
    /// Whether sort in multiple threads. Default `true`.
    pub multithreaded: bool,
    /// Whether maintain the order of equal elements. Default `false`.
    pub maintain_order: bool,
    /// Limit a sort output, this is for optimization purposes and might be ignored.
    /// - Len
    /// - Descending
    pub limit: Option<(IdxSize, bool)>,
}

impl Default for SortOptions {
    fn default() -> Self {
        Self {
            descending: false,
            nulls_last: false,
            multithreaded: true,
            maintain_order: false,
            limit: None,
        }
    }
}

impl Default for SortMultipleOptions {
    fn default() -> Self {
        Self {
            descending: vec![false],
            nulls_last: vec![false],
            multithreaded: true,
            maintain_order: false,
            limit: None,
        }
    }
}

impl SortMultipleOptions {
    /// Create `SortMultipleOptions` with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Specify order for each column. Defaults all `false`.
    ///
    /// # Safety
    ///
    /// Len must match the number of columns, or be equal to 1.
    pub fn with_order_descending_multi(
        mut self,
        descending: impl IntoIterator<Item = bool>,
    ) -> Self {
        self.descending = descending.into_iter().collect();
        self
    }

    /// Sort order for all columns. Default `false` which is ascending.
    pub fn with_order_descending(mut self, descending: bool) -> Self {
        self.descending = vec![descending];
        self
    }

    /// Specify whether to place nulls last, per-column. Defaults all `false`.
    ///
    /// # Safety
    ///
    /// Len must match the number of columns, or be equal to 1.
    pub fn with_nulls_last_multi(mut self, nulls_last: impl IntoIterator<Item = bool>) -> Self {
        self.nulls_last = nulls_last.into_iter().collect();
        self
    }

    /// Whether to place null values last. Default `false`.
    pub fn with_nulls_last(mut self, enabled: bool) -> Self {
        self.nulls_last = vec![enabled];
        self
    }

    /// Whether to sort in multiple threads. Default `true`.
    pub fn with_multithreaded(mut self, enabled: bool) -> Self {
        self.multithreaded = enabled;
        self
    }

    /// Whether to maintain the order of equal elements. Default `false`.
    pub fn with_maintain_order(mut self, enabled: bool) -> Self {
        self.maintain_order = enabled;
        self
    }

    /// Reverse the order of sorting for each column.
    pub fn with_order_reversed(mut self) -> Self {
        self.descending.iter_mut().for_each(|x| *x = !*x);
        self
    }
}

impl SortOptions {
    /// Create `SortOptions` with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Specify sorting order for the column. Default `false`.
    pub fn with_order_descending(mut self, enabled: bool) -> Self {
        self.descending = enabled;
        self
    }

    /// Whether place null values last. Default `false`.
    pub fn with_nulls_last(mut self, enabled: bool) -> Self {
        self.nulls_last = enabled;
        self
    }

    /// Whether sort in multiple threads. Default `true`.
    pub fn with_multithreaded(mut self, enabled: bool) -> Self {
        self.multithreaded = enabled;
        self
    }

    /// Whether maintain the order of equal elements. Default `false`.
    pub fn with_maintain_order(mut self, enabled: bool) -> Self {
        self.maintain_order = enabled;
        self
    }

    /// Reverse the order of sorting.
    pub fn with_order_reversed(mut self) -> Self {
        self.descending = !self.descending;
        self
    }
}

impl From<&SortOptions> for SortMultipleOptions {
    fn from(value: &SortOptions) -> Self {
        SortMultipleOptions {
            descending: vec![value.descending],
            nulls_last: vec![value.nulls_last],
            multithreaded: value.multithreaded,
            maintain_order: value.maintain_order,
            limit: value.limit,
        }
    }
}

impl From<&SortMultipleOptions> for SortOptions {
    fn from(value: &SortMultipleOptions) -> Self {
        SortOptions {
            descending: value.descending.first().copied().unwrap_or(false),
            nulls_last: value.nulls_last.first().copied().unwrap_or(false),
            multithreaded: value.multithreaded,
            maintain_order: value.maintain_order,
            limit: value.limit,
        }
    }
}