polars_core/series/implementations/
decimal.rs

1use polars_compute::rolling::QuantileMethod;
2
3use super::*;
4use crate::prelude::*;
5
6unsafe impl IntoSeries for DecimalChunked {
7    fn into_series(self) -> Series {
8        Series(Arc::new(SeriesWrap(self)))
9    }
10}
11
12impl private::PrivateSeriesNumeric for SeriesWrap<DecimalChunked> {
13    fn bit_repr(&self) -> Option<BitRepr> {
14        None
15    }
16}
17
18impl SeriesWrap<DecimalChunked> {
19    fn apply_physical_to_s<F: Fn(&Int128Chunked) -> Int128Chunked>(&self, f: F) -> Series {
20        f(&self.0)
21            .into_decimal_unchecked(self.0.precision(), self.0.scale())
22            .into_series()
23    }
24
25    fn apply_physical<T, F: Fn(&Int128Chunked) -> T>(&self, f: F) -> T {
26        f(&self.0)
27    }
28
29    fn scale_factor(&self) -> u128 {
30        10u128.pow(self.0.scale() as u32)
31    }
32
33    fn apply_scale(&self, mut scalar: Scalar) -> Scalar {
34        if scalar.is_null() {
35            return scalar;
36        }
37
38        debug_assert_eq!(scalar.dtype(), &DataType::Float64);
39        let v = scalar
40            .value()
41            .try_extract::<f64>()
42            .expect("should be f64 scalar");
43        scalar.update((v / self.scale_factor() as f64).into());
44        scalar
45    }
46
47    fn agg_helper<F: Fn(&Int128Chunked) -> Series>(&self, f: F) -> Series {
48        let agg_s = f(&self.0);
49        match agg_s.dtype() {
50            DataType::Int128 => {
51                let ca = agg_s.i128().unwrap();
52                let ca = ca.as_ref().clone();
53                let precision = self.0.precision();
54                let scale = self.0.scale();
55                ca.into_decimal_unchecked(precision, scale).into_series()
56            },
57            DataType::List(dtype) if matches!(dtype.as_ref(), DataType::Int128) => {
58                let dtype = self.0.dtype();
59                let ca = agg_s.list().unwrap();
60                let arr = ca.downcast_iter().next().unwrap();
61                // SAFETY: dtype is passed correctly
62                let precision = self.0.precision();
63                let scale = self.0.scale();
64                let s = unsafe {
65                    Series::from_chunks_and_dtype_unchecked(
66                        PlSmallStr::EMPTY,
67                        vec![arr.values().clone()],
68                        dtype,
69                    )
70                }
71                .into_decimal(precision, scale)
72                .unwrap();
73                let new_values = s.array_ref(0).clone();
74                let dtype = DataType::Int128;
75                let arrow_dtype =
76                    ListArray::<i64>::default_datatype(dtype.to_arrow(CompatLevel::newest()));
77                let new_arr = ListArray::<i64>::new(
78                    arrow_dtype,
79                    arr.offsets().clone(),
80                    new_values,
81                    arr.validity().cloned(),
82                );
83                unsafe {
84                    ListChunked::from_chunks_and_dtype_unchecked(
85                        agg_s.name().clone(),
86                        vec![Box::new(new_arr)],
87                        DataType::List(Box::new(DataType::Decimal(precision, Some(scale)))),
88                    )
89                    .into_series()
90                }
91            },
92            _ => unreachable!(),
93        }
94    }
95}
96
97impl private::PrivateSeries for SeriesWrap<DecimalChunked> {
98    fn compute_len(&mut self) {
99        self.0.compute_len()
100    }
101
102    fn _field(&self) -> Cow<Field> {
103        Cow::Owned(self.0.field())
104    }
105
106    fn _dtype(&self) -> &DataType {
107        self.0.dtype()
108    }
109    fn _get_flags(&self) -> StatisticsFlags {
110        self.0.get_flags()
111    }
112    fn _set_flags(&mut self, flags: StatisticsFlags) {
113        self.0.set_flags(flags)
114    }
115
116    #[cfg(feature = "zip_with")]
117    fn zip_with_same_type(&self, mask: &BooleanChunked, other: &Series) -> PolarsResult<Series> {
118        let other = other.decimal()?;
119
120        Ok(self
121            .0
122            .physical()
123            .zip_with(mask, other.physical())?
124            .into_decimal_unchecked(self.0.precision(), self.0.scale())
125            .into_series())
126    }
127    fn into_total_eq_inner<'a>(&'a self) -> Box<dyn TotalEqInner + 'a> {
128        (&self.0).into_total_eq_inner()
129    }
130    fn into_total_ord_inner<'a>(&'a self) -> Box<dyn TotalOrdInner + 'a> {
131        (&self.0).into_total_ord_inner()
132    }
133
134    fn vec_hash(
135        &self,
136        random_state: PlSeedableRandomStateQuality,
137        buf: &mut Vec<u64>,
138    ) -> PolarsResult<()> {
139        self.0.vec_hash(random_state, buf)?;
140        Ok(())
141    }
142
143    fn vec_hash_combine(
144        &self,
145        build_hasher: PlSeedableRandomStateQuality,
146        hashes: &mut [u64],
147    ) -> PolarsResult<()> {
148        self.0.vec_hash_combine(build_hasher, hashes)?;
149        Ok(())
150    }
151
152    #[cfg(feature = "algorithm_group_by")]
153    unsafe fn agg_sum(&self, groups: &GroupsType) -> Series {
154        self.agg_helper(|ca| ca.agg_sum(groups))
155    }
156
157    #[cfg(feature = "algorithm_group_by")]
158    unsafe fn agg_min(&self, groups: &GroupsType) -> Series {
159        self.agg_helper(|ca| ca.agg_min(groups))
160    }
161
162    #[cfg(feature = "algorithm_group_by")]
163    unsafe fn agg_max(&self, groups: &GroupsType) -> Series {
164        self.agg_helper(|ca| ca.agg_max(groups))
165    }
166
167    #[cfg(feature = "algorithm_group_by")]
168    unsafe fn agg_list(&self, groups: &GroupsType) -> Series {
169        self.agg_helper(|ca| ca.agg_list(groups))
170    }
171
172    fn subtract(&self, rhs: &Series) -> PolarsResult<Series> {
173        let rhs = rhs.decimal()?;
174        ((&self.0) - rhs).map(|ca| ca.into_series())
175    }
176    fn add_to(&self, rhs: &Series) -> PolarsResult<Series> {
177        let rhs = rhs.decimal()?;
178        ((&self.0) + rhs).map(|ca| ca.into_series())
179    }
180    fn multiply(&self, rhs: &Series) -> PolarsResult<Series> {
181        let rhs = rhs.decimal()?;
182        ((&self.0) * rhs).map(|ca| ca.into_series())
183    }
184    fn divide(&self, rhs: &Series) -> PolarsResult<Series> {
185        let rhs = rhs.decimal()?;
186        ((&self.0) / rhs).map(|ca| ca.into_series())
187    }
188    #[cfg(feature = "algorithm_group_by")]
189    fn group_tuples(&self, multithreaded: bool, sorted: bool) -> PolarsResult<GroupsType> {
190        self.0.group_tuples(multithreaded, sorted)
191    }
192    fn arg_sort_multiple(
193        &self,
194        by: &[Column],
195        options: &SortMultipleOptions,
196    ) -> PolarsResult<IdxCa> {
197        self.0.arg_sort_multiple(by, options)
198    }
199}
200
201impl SeriesTrait for SeriesWrap<DecimalChunked> {
202    fn rename(&mut self, name: PlSmallStr) {
203        self.0.rename(name)
204    }
205
206    fn chunk_lengths(&self) -> ChunkLenIter {
207        self.0.chunk_lengths()
208    }
209
210    fn name(&self) -> &PlSmallStr {
211        self.0.name()
212    }
213
214    fn chunks(&self) -> &Vec<ArrayRef> {
215        self.0.chunks()
216    }
217    unsafe fn chunks_mut(&mut self) -> &mut Vec<ArrayRef> {
218        self.0.chunks_mut()
219    }
220
221    fn slice(&self, offset: i64, length: usize) -> Series {
222        self.apply_physical_to_s(|ca| ca.slice(offset, length))
223    }
224
225    fn split_at(&self, offset: i64) -> (Series, Series) {
226        let (a, b) = self.0.split_at(offset);
227        let a = a
228            .into_decimal_unchecked(self.0.precision(), self.0.scale())
229            .into_series();
230        let b = b
231            .into_decimal_unchecked(self.0.precision(), self.0.scale())
232            .into_series();
233        (a, b)
234    }
235
236    fn append(&mut self, other: &Series) -> PolarsResult<()> {
237        polars_ensure!(self.0.dtype() == other.dtype(), append);
238        let mut other = other.to_physical_repr().into_owned();
239        self.0
240            .append_owned(std::mem::take(other._get_inner_mut().as_mut()))
241    }
242    fn append_owned(&mut self, mut other: Series) -> PolarsResult<()> {
243        polars_ensure!(self.0.dtype() == other.dtype(), append);
244        self.0.append_owned(std::mem::take(
245            &mut other
246                ._get_inner_mut()
247                .as_any_mut()
248                .downcast_mut::<DecimalChunked>()
249                .unwrap()
250                .0,
251        ))
252    }
253
254    fn extend(&mut self, other: &Series) -> PolarsResult<()> {
255        polars_ensure!(self.0.dtype() == other.dtype(), extend);
256        // 3 refs
257        // ref Cow
258        // ref SeriesTrait
259        // ref ChunkedArray
260        let other = other.to_physical_repr();
261        self.0.extend(other.as_ref().as_ref().as_ref())?;
262        Ok(())
263    }
264
265    fn filter(&self, filter: &BooleanChunked) -> PolarsResult<Series> {
266        Ok(self
267            .0
268            .filter(filter)?
269            .into_decimal_unchecked(self.0.precision(), self.0.scale())
270            .into_series())
271    }
272
273    fn take(&self, indices: &IdxCa) -> PolarsResult<Series> {
274        Ok(self
275            .0
276            .take(indices)?
277            .into_decimal_unchecked(self.0.precision(), self.0.scale())
278            .into_series())
279    }
280
281    unsafe fn take_unchecked(&self, indices: &IdxCa) -> Series {
282        self.0
283            .take_unchecked(indices)
284            .into_decimal_unchecked(self.0.precision(), self.0.scale())
285            .into_series()
286    }
287
288    fn take_slice(&self, indices: &[IdxSize]) -> PolarsResult<Series> {
289        Ok(self
290            .0
291            .take(indices)?
292            .into_decimal_unchecked(self.0.precision(), self.0.scale())
293            .into_series())
294    }
295
296    unsafe fn take_slice_unchecked(&self, indices: &[IdxSize]) -> Series {
297        self.0
298            .take_unchecked(indices)
299            .into_decimal_unchecked(self.0.precision(), self.0.scale())
300            .into_series()
301    }
302
303    fn len(&self) -> usize {
304        self.0.len()
305    }
306
307    fn rechunk(&self) -> Series {
308        let ca = self.0.rechunk().into_owned();
309        ca.into_decimal_unchecked(self.0.precision(), self.0.scale())
310            .into_series()
311    }
312
313    fn new_from_index(&self, index: usize, length: usize) -> Series {
314        self.0
315            .new_from_index(index, length)
316            .into_decimal_unchecked(self.0.precision(), self.0.scale())
317            .into_series()
318    }
319
320    fn cast(&self, dtype: &DataType, cast_options: CastOptions) -> PolarsResult<Series> {
321        self.0.cast_with_options(dtype, cast_options)
322    }
323
324    #[inline]
325    unsafe fn get_unchecked(&self, index: usize) -> AnyValue {
326        self.0.get_any_value_unchecked(index)
327    }
328
329    fn sort_with(&self, options: SortOptions) -> PolarsResult<Series> {
330        Ok(self
331            .0
332            .sort_with(options)
333            .into_decimal_unchecked(self.0.precision(), self.0.scale())
334            .into_series())
335    }
336
337    fn arg_sort(&self, options: SortOptions) -> IdxCa {
338        self.0.arg_sort(options)
339    }
340
341    fn null_count(&self) -> usize {
342        self.0.null_count()
343    }
344
345    fn has_nulls(&self) -> bool {
346        self.0.has_nulls()
347    }
348
349    #[cfg(feature = "algorithm_group_by")]
350    fn unique(&self) -> PolarsResult<Series> {
351        Ok(self.apply_physical_to_s(|ca| ca.unique().unwrap()))
352    }
353
354    #[cfg(feature = "algorithm_group_by")]
355    fn n_unique(&self) -> PolarsResult<usize> {
356        self.0.n_unique()
357    }
358
359    #[cfg(feature = "algorithm_group_by")]
360    fn arg_unique(&self) -> PolarsResult<IdxCa> {
361        self.0.arg_unique()
362    }
363
364    fn is_null(&self) -> BooleanChunked {
365        self.0.is_null()
366    }
367
368    fn is_not_null(&self) -> BooleanChunked {
369        self.0.is_not_null()
370    }
371
372    fn reverse(&self) -> Series {
373        self.apply_physical_to_s(|ca| ca.reverse())
374    }
375
376    fn shift(&self, periods: i64) -> Series {
377        self.apply_physical_to_s(|ca| ca.shift(periods))
378    }
379
380    fn clone_inner(&self) -> Arc<dyn SeriesTrait> {
381        Arc::new(SeriesWrap(Clone::clone(&self.0)))
382    }
383
384    fn sum_reduce(&self) -> PolarsResult<Scalar> {
385        Ok(self.apply_physical(|ca| {
386            let sum = ca.sum();
387            let DataType::Decimal(_, Some(scale)) = self.dtype() else {
388                unreachable!()
389            };
390            let av = AnyValue::Decimal(sum.unwrap(), *scale);
391            Scalar::new(self.dtype().clone(), av)
392        }))
393    }
394    fn min_reduce(&self) -> PolarsResult<Scalar> {
395        Ok(self.apply_physical(|ca| {
396            let min = ca.min();
397            let DataType::Decimal(_, Some(scale)) = self.dtype() else {
398                unreachable!()
399            };
400            let av = if let Some(min) = min {
401                AnyValue::Decimal(min, *scale)
402            } else {
403                AnyValue::Null
404            };
405            Scalar::new(self.dtype().clone(), av)
406        }))
407    }
408    fn max_reduce(&self) -> PolarsResult<Scalar> {
409        Ok(self.apply_physical(|ca| {
410            let max = ca.max();
411            let DataType::Decimal(_, Some(scale)) = self.dtype() else {
412                unreachable!()
413            };
414            let av = if let Some(m) = max {
415                AnyValue::Decimal(m, *scale)
416            } else {
417                AnyValue::Null
418            };
419            Scalar::new(self.dtype().clone(), av)
420        }))
421    }
422
423    fn _sum_as_f64(&self) -> f64 {
424        self.0._sum_as_f64() / self.scale_factor() as f64
425    }
426
427    fn mean(&self) -> Option<f64> {
428        self.0.mean().map(|v| v / self.scale_factor() as f64)
429    }
430
431    fn median(&self) -> Option<f64> {
432        self.0.median().map(|v| v / self.scale_factor() as f64)
433    }
434    fn median_reduce(&self) -> PolarsResult<Scalar> {
435        Ok(self.apply_scale(self.0.median_reduce()))
436    }
437
438    fn std(&self, ddof: u8) -> Option<f64> {
439        self.0.std(ddof).map(|v| v / self.scale_factor() as f64)
440    }
441    fn std_reduce(&self, ddof: u8) -> PolarsResult<Scalar> {
442        Ok(self.apply_scale(self.0.std_reduce(ddof)))
443    }
444
445    fn quantile_reduce(&self, quantile: f64, method: QuantileMethod) -> PolarsResult<Scalar> {
446        self.0
447            .quantile_reduce(quantile, method)
448            .map(|v| self.apply_scale(v))
449    }
450
451    fn as_any(&self) -> &dyn Any {
452        &self.0
453    }
454
455    fn as_any_mut(&mut self) -> &mut dyn Any {
456        &mut self.0
457    }
458
459    fn as_phys_any(&self) -> &dyn Any {
460        self.0.physical()
461    }
462
463    fn as_arc_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
464        self as _
465    }
466}