Skip to main content

polars_core/chunked_array/ops/sort/
options.rs

1#[cfg(feature = "serde-lazy")]
2use serde::{Deserialize, Serialize};
3pub use slice::*;
4
5use crate::prelude::*;
6
7/// Options for single series sorting.
8///
9/// Indicating the order of sorting, nulls position, multithreading, and maintaining order.
10///
11/// # Example
12///
13/// ```
14/// # use polars_core::prelude::*;
15/// let s = Series::new("a".into(), [Some(5), Some(2), Some(3), Some(4), None].as_ref());
16/// let sorted = s
17///     .sort(
18///         SortOptions::default()
19///             .with_order_descending(true)
20///             .with_nulls_last(true)
21///             .with_multithreaded(false),
22///     )
23///     .unwrap();
24/// assert_eq!(
25///     sorted,
26///     Series::new("a".into(), [Some(5), Some(4), Some(3), Some(2), None].as_ref())
27/// );
28/// ```
29#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
30#[cfg_attr(feature = "serde-lazy", derive(Serialize, Deserialize))]
31#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
32pub struct SortOptions {
33    /// If true sort in descending order.
34    /// Default `false`.
35    pub descending: bool,
36    /// Whether place null values last.
37    /// Default `false`.
38    pub nulls_last: bool,
39    /// If true sort in multiple threads.
40    /// Default `true`.
41    pub multithreaded: bool,
42    /// If true maintain the order of equal elements.
43    /// Default `false`.
44    pub maintain_order: bool,
45    /// Limit a sort output, this is for optimization purposes and might be ignored.
46    pub limit: Option<IdxSize>,
47}
48
49/// Sort options for multi-series sorting.
50///
51/// Indicating the order of sorting, nulls position, multithreading, and maintaining order.
52///
53/// # Example
54/// ```
55/// # use polars_core::prelude::*;
56///
57/// # fn main() -> PolarsResult<()> {
58/// let df = df! {
59///     "a" => [Some(1), Some(2), None, Some(4), None],
60///     "b" => [Some(5), None, Some(3), Some(2), Some(1)]
61/// }?;
62///
63/// let out = df
64///     .sort(
65///         ["a", "b"],
66///         SortMultipleOptions::default()
67///             .with_maintain_order(true)
68///             .with_multithreaded(false)
69///             .with_order_descending_multi([false, true])
70///             .with_nulls_last(true),
71///     )?;
72///
73/// let expected = df! {
74///     "a" => [Some(1), Some(2), Some(4), None, None],
75///     "b" => [Some(5), None, Some(2), Some(3), Some(1)]
76/// }?;
77///
78/// assert_eq!(out, expected);
79///
80/// # Ok(())
81/// # }
82#[derive(Clone, Debug, Eq, PartialEq, Hash)]
83#[cfg_attr(feature = "serde-lazy", derive(Serialize, Deserialize))]
84#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
85pub struct SortMultipleOptions {
86    /// Order of the columns. Default all `false``.
87    ///
88    /// If only one value is given, it will broadcast to all columns. This
89    /// should happen when entering Polars - internally we store broadcast values.
90    ///
91    /// Use [`SortMultipleOptions::with_order_descending_multi`]
92    /// or [`SortMultipleOptions::with_order_descending`] to modify.
93    pub descending: Vec<bool>,
94    /// Whether place null values last. Default `false`.
95    pub nulls_last: Vec<bool>,
96    /// Whether sort in multiple threads. Default `true`.
97    pub multithreaded: bool,
98    /// Whether maintain the order of equal elements. Default `false`.
99    pub maintain_order: bool,
100    /// Limit a sort output, this is for optimization purposes and might be ignored.
101    pub limit: Option<IdxSize>,
102}
103
104impl Default for SortOptions {
105    fn default() -> Self {
106        Self {
107            descending: false,
108            nulls_last: false,
109            multithreaded: true,
110            maintain_order: false,
111            limit: None,
112        }
113    }
114}
115
116impl Default for SortMultipleOptions {
117    fn default() -> Self {
118        Self {
119            descending: vec![false],
120            nulls_last: vec![false],
121            multithreaded: true,
122            maintain_order: false,
123            limit: None,
124        }
125    }
126}
127
128impl SortMultipleOptions {
129    /// Create `SortMultipleOptions` with default values.
130    pub fn new() -> Self {
131        Self::default()
132    }
133
134    /// Expands `descending` and `nulls_last` given as a single flag for all keys to one flag per
135    /// key.
136    pub fn expand_flags(mut self, num_keys: usize) -> PolarsResult<Self> {
137        for (flags, name) in [
138            (&mut self.descending, "descending"),
139            (&mut self.nulls_last, "nulls_last"),
140        ] {
141            if flags.len() == 1 {
142                *flags = vec![flags[0]; num_keys];
143            }
144            polars_ensure!(
145                flags.len() == num_keys,
146                ComputeError: "the length of `{}` ({}) does not match the length of `by` ({})",
147                name, flags.len(), num_keys
148            );
149        }
150        Ok(self)
151    }
152
153    /// Specify order for each column. Defaults all `false`.
154    ///
155    /// # Safety
156    ///
157    /// Len must match the number of columns, or be equal to 1.
158    pub fn with_order_descending_multi(
159        mut self,
160        descending: impl IntoIterator<Item = bool>,
161    ) -> Self {
162        self.descending = descending.into_iter().collect();
163        self
164    }
165
166    /// Sort order for all columns. Default `false` which is ascending.
167    pub fn with_order_descending(mut self, descending: bool) -> Self {
168        self.descending = vec![descending];
169        self
170    }
171
172    /// Specify whether to place nulls last, per-column. Defaults all `false`.
173    ///
174    /// # Safety
175    ///
176    /// Len must match the number of columns, or be equal to 1.
177    pub fn with_nulls_last_multi(mut self, nulls_last: impl IntoIterator<Item = bool>) -> Self {
178        self.nulls_last = nulls_last.into_iter().collect();
179        self
180    }
181
182    /// Whether to place null values last. Default `false`.
183    pub fn with_nulls_last(mut self, enabled: bool) -> Self {
184        self.nulls_last = vec![enabled];
185        self
186    }
187
188    /// Whether to sort in multiple threads. Default `true`.
189    pub fn with_multithreaded(mut self, enabled: bool) -> Self {
190        self.multithreaded = enabled;
191        self
192    }
193
194    /// Whether to maintain the order of equal elements. Default `false`.
195    pub fn with_maintain_order(mut self, enabled: bool) -> Self {
196        self.maintain_order = enabled;
197        self
198    }
199
200    /// Reverse the order of sorting for each column.
201    pub fn with_order_reversed(mut self) -> Self {
202        self.descending.iter_mut().for_each(|x| *x = !*x);
203        self
204    }
205}
206
207impl SortOptions {
208    /// Create `SortOptions` with default values.
209    pub fn new() -> Self {
210        Self::default()
211    }
212
213    /// Specify sorting order for the column. Default `false`.
214    pub fn with_order_descending(mut self, enabled: bool) -> Self {
215        self.descending = enabled;
216        self
217    }
218
219    /// Whether place null values last. Default `false`.
220    pub fn with_nulls_last(mut self, enabled: bool) -> Self {
221        self.nulls_last = enabled;
222        self
223    }
224
225    /// Whether sort in multiple threads. Default `true`.
226    pub fn with_multithreaded(mut self, enabled: bool) -> Self {
227        self.multithreaded = enabled;
228        self
229    }
230
231    /// Whether maintain the order of equal elements. Default `false`.
232    pub fn with_maintain_order(mut self, enabled: bool) -> Self {
233        self.maintain_order = enabled;
234        self
235    }
236
237    /// Reverse the order of sorting.
238    pub fn with_order_reversed(mut self) -> Self {
239        self.descending = !self.descending;
240        self
241    }
242}
243
244impl From<&SortOptions> for SortMultipleOptions {
245    fn from(value: &SortOptions) -> Self {
246        SortMultipleOptions {
247            descending: vec![value.descending],
248            nulls_last: vec![value.nulls_last],
249            multithreaded: value.multithreaded,
250            maintain_order: value.maintain_order,
251            limit: value.limit,
252        }
253    }
254}
255
256impl From<&SortMultipleOptions> for SortOptions {
257    fn from(value: &SortMultipleOptions) -> Self {
258        SortOptions {
259            descending: value.descending.first().copied().unwrap_or(false),
260            nulls_last: value.nulls_last.first().copied().unwrap_or(false),
261            multithreaded: value.multithreaded,
262            maintain_order: value.maintain_order,
263            limit: value.limit,
264        }
265    }
266}