1use std::any::Any;
2use std::borrow::Cow;
3
4use polars_arrow::bitmap::{Bitmap, BitmapBuilder};
5use polars_arrow::compute::utils::combine_validities_and;
6use polars_compute::rolling::QuantileMethod;
7
8use crate::chunked_array::cast::CastOptions;
9#[cfg(feature = "object")]
10use crate::chunked_array::object::PolarsObjectSafe;
11use crate::prelude::*;
12use crate::utils::{first_non_null, last_non_null};
13
14#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
15pub enum IsSorted {
16 Ascending,
17 Descending,
18 Not,
19}
20
21impl IsSorted {
22 pub fn reverse(self) -> Self {
23 use IsSorted::*;
24 match self {
25 Ascending => Descending,
26 Descending => Ascending,
27 Not => Not,
28 }
29 }
30}
31
32pub enum BitRepr {
33 U8(UInt8Chunked),
34 U16(UInt16Chunked),
35 U32(UInt32Chunked),
36 U64(UInt64Chunked),
37 #[cfg(feature = "dtype-u128")]
38 U128(UInt128Chunked),
39}
40
41pub(crate) mod private {
42 use polars_utils::aliases::PlSeedableRandomStateQuality;
43
44 use super::*;
45 use crate::chunked_array::flags::StatisticsFlags;
46 use crate::chunked_array::ops::compare_inner::TotalOrdInner;
47
48 pub trait PrivateSeriesNumeric {
49 fn bit_repr(&self) -> Option<BitRepr>;
53 }
54
55 pub trait PrivateSeries {
56 #[cfg(feature = "object")]
57 fn get_list_builder(
58 &self,
59 _name: PlSmallStr,
60 _values_capacity: usize,
61 _list_capacity: usize,
62 ) -> Box<dyn ListBuilderTrait> {
63 invalid_operation_panic!(get_list_builder, self)
64 }
65
66 fn _field(&self) -> Cow<'_, Field>;
68
69 fn _dtype(&self) -> &DataType;
70
71 fn compute_len(&mut self);
72
73 fn _get_flags(&self) -> StatisticsFlags;
74
75 fn _set_flags(&mut self, flags: StatisticsFlags);
76
77 #[expect(clippy::wrong_self_convention)]
78 fn into_total_ord_inner<'a>(&'a self) -> Box<dyn TotalOrdInner + 'a>;
79
80 fn vec_hash(
81 &self,
82 _build_hasher: PlSeedableRandomStateQuality,
83 _buf: &mut Vec<u64>,
84 ) -> PolarsResult<()>;
85 fn vec_hash_combine(
86 &self,
87 _build_hasher: PlSeedableRandomStateQuality,
88 _hashes: &mut [u64],
89 ) -> PolarsResult<()>;
90
91 #[cfg(feature = "algorithm_group_by")]
95 unsafe fn agg_min(&self, groups: &GroupsType) -> Series {
96 Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
97 }
98 #[cfg(feature = "algorithm_group_by")]
102 unsafe fn agg_max(&self, groups: &GroupsType) -> Series {
103 Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
104 }
105 #[cfg(feature = "algorithm_group_by")]
109 unsafe fn agg_arg_min(&self, groups: &GroupsType) -> Series {
110 Series::full_null(self._field().name().clone(), groups.len(), &IDX_DTYPE)
111 }
112
113 #[cfg(feature = "algorithm_group_by")]
117 unsafe fn agg_arg_max(&self, groups: &GroupsType) -> Series {
118 Series::full_null(self._field().name().clone(), groups.len(), &IDX_DTYPE)
119 }
120
121 #[cfg(feature = "algorithm_group_by")]
124 unsafe fn agg_sum(&self, groups: &GroupsType) -> Series {
125 Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
126 }
127 #[cfg(feature = "algorithm_group_by")]
131 unsafe fn agg_std(&self, groups: &GroupsType, _ddof: u8) -> Series {
132 Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
133 }
134 #[cfg(feature = "algorithm_group_by")]
138 unsafe fn agg_var(&self, groups: &GroupsType, _ddof: u8) -> Series {
139 Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
140 }
141 #[cfg(feature = "algorithm_group_by")]
145 unsafe fn agg_list(&self, groups: &GroupsType) -> Series {
146 Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
147 }
148
149 #[cfg(feature = "bitwise")]
153 unsafe fn agg_and(&self, groups: &GroupsType) -> Series {
154 Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
155 }
156
157 #[cfg(feature = "bitwise")]
161 unsafe fn agg_or(&self, groups: &GroupsType) -> Series {
162 Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
163 }
164
165 #[cfg(feature = "bitwise")]
169 unsafe fn agg_xor(&self, groups: &GroupsType) -> Series {
170 Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
171 }
172
173 fn subtract(&self, _rhs: &Series) -> PolarsResult<Series> {
174 polars_bail!(opq = subtract, self._dtype());
175 }
176 fn add_to(&self, _rhs: &Series) -> PolarsResult<Series> {
177 polars_bail!(opq = add, self._dtype());
178 }
179 fn multiply(&self, _rhs: &Series) -> PolarsResult<Series> {
180 polars_bail!(opq = multiply, self._dtype());
181 }
182 fn divide(&self, _rhs: &Series) -> PolarsResult<Series> {
183 polars_bail!(opq = divide, self._dtype());
184 }
185 fn remainder(&self, _rhs: &Series) -> PolarsResult<Series> {
186 polars_bail!(opq = remainder, self._dtype());
187 }
188 #[cfg(feature = "algorithm_group_by")]
189 fn group_tuples(&self, _multithreaded: bool, _sorted: bool) -> PolarsResult<GroupsType> {
190 polars_bail!(opq = group_tuples, self._dtype());
191 }
192 #[cfg(feature = "zip_with")]
193 fn zip_with_same_type(
194 &self,
195 _mask: &BooleanChunked,
196 _other: &Series,
197 ) -> PolarsResult<Series> {
198 polars_bail!(opq = zip_with_same_type, self._dtype());
199 }
200
201 #[allow(unused_variables)]
202 fn arg_sort_multiple(
203 &self,
204 by: &[Column],
205 _options: &SortMultipleOptions,
206 ) -> PolarsResult<IdxCa> {
207 polars_bail!(opq = arg_sort_multiple, self._dtype());
208 }
209 }
210}
211
212pub trait SeriesTrait:
213 Send + Sync + private::PrivateSeries + private::PrivateSeriesNumeric
214{
215 fn rename(&mut self, name: PlSmallStr);
217
218 fn chunk_lengths(&self) -> ChunkLenIter<'_>;
220
221 fn name(&self) -> &PlSmallStr;
223
224 fn field(&self) -> Cow<'_, Field> {
226 self._field()
227 }
228
229 #[inline(always)]
231 fn dtype(&self) -> &DataType {
232 self._dtype()
233 }
234
235 fn chunks(&self) -> &Vec<ArrayRef>;
237
238 unsafe fn chunks_mut(&mut self) -> &mut Vec<ArrayRef>;
243
244 fn n_chunks(&self) -> usize {
246 self.chunks().len()
247 }
248
249 fn shrink_to_fit(&mut self) {
251 }
253
254 fn limit(&self, num_elements: usize) -> Series {
256 self.slice(Slice::head(num_elements))
257 }
258
259 fn slice(&self, _slice: Slice) -> Series;
261
262 fn split_at(&self, _offset: i64) -> (Series, Series);
267
268 fn append(&mut self, other: &Series) -> PolarsResult<()>;
269 fn append_owned(&mut self, other: Series) -> PolarsResult<()>;
270
271 #[doc(hidden)]
272 fn extend(&mut self, _other: &Series) -> PolarsResult<()>;
273
274 fn filter(&self, _filter: &BooleanChunked) -> PolarsResult<Series>;
276
277 fn take(&self, _indices: &IdxCa) -> PolarsResult<Series>;
283
284 unsafe fn take_unchecked(&self, _idx: &IdxCa) -> Series;
291
292 fn take_slice(&self, _indices: &[IdxSize]) -> PolarsResult<Series>;
296
297 unsafe fn take_slice_unchecked(&self, _idx: &[IdxSize]) -> Series;
302
303 fn len(&self) -> usize;
305
306 fn is_empty(&self) -> bool {
308 self.len() == 0
309 }
310
311 fn is_full_null(&self) -> bool {
313 self.len() == self.null_count()
314 }
315
316 fn rechunk(&self) -> Series;
318
319 fn rechunk_validity(&self) -> Option<Bitmap> {
321 if self.chunks().len() == 1 {
322 return self.chunks()[0].validity().cloned();
323 }
324
325 if !self.has_nulls() || self.is_empty() {
326 return None;
327 }
328
329 let mut bm = BitmapBuilder::with_capacity(self.len());
330 for arr in self.chunks() {
331 if let Some(v) = arr.validity() {
332 bm.extend_from_bitmap(v);
333 } else {
334 bm.extend_constant(arr.len(), true);
335 }
336 }
337 bm.into_opt_validity()
338 }
339
340 fn with_validity(&self, validity: Option<Bitmap>) -> Series;
342
343 fn mask(&self, validity: &Bitmap) -> Series {
347 if validity.len() == 1 {
348 if validity.get_bit(0) {
349 Series(self.clone_inner())
350 } else {
351 Series::full_null(self._field().name().clone(), self.len(), self._dtype())
352 }
353 } else if self.len() == 1 && validity.len() != 1 {
354 self.new_from_index(0, validity.len()).mask(validity)
355 } else {
356 self.with_validity(combine_validities_and(
357 self.rechunk_validity().as_ref(),
358 Some(validity),
359 ))
360 }
361 }
362
363 fn drop_nulls(&self) -> Series {
365 if self.null_count() == 0 {
366 Series(self.clone_inner())
367 } else {
368 self.filter(&self.is_not_null()).unwrap()
369 }
370 }
371
372 fn _sum_as_f64(&self) -> f64 {
374 invalid_operation_panic!(_sum_as_f64, self)
375 }
376
377 fn mean(&self) -> Option<f64> {
380 None
381 }
382
383 fn std(&self, _ddof: u8) -> Option<f64> {
386 None
387 }
388
389 fn var(&self, _ddof: u8) -> Option<f64> {
392 None
393 }
394
395 fn median(&self) -> Option<f64> {
398 None
399 }
400
401 fn new_from_index(&self, _index: usize, _length: usize) -> Series;
412
413 fn trim_lists_to_normalized_offsets(&self) -> Option<Series> {
418 None
419 }
420
421 fn propagate_nulls(&self) -> Option<Series> {
426 None
427 }
428
429 fn deposit(&self, validity: &Bitmap) -> Series;
430
431 fn find_validity_mismatch(&self, other: &Series, idxs: &mut Vec<IdxSize>);
433
434 fn cast(&self, _dtype: &DataType, options: CastOptions) -> PolarsResult<Series>;
435
436 fn get(&self, index: usize) -> PolarsResult<AnyValue<'_>> {
439 polars_ensure!(index < self.len(), oob = index, self.len());
440 let value = unsafe { self.get_unchecked(index) };
442 Ok(value)
443 }
444
445 unsafe fn get_unchecked(&self, _index: usize) -> AnyValue<'_>;
453
454 fn sort_with(&self, _options: SortOptions) -> PolarsResult<Series> {
455 polars_bail!(opq = sort_with, self._dtype());
456 }
457
458 #[allow(unused)]
460 fn arg_sort(&self, options: SortOptions) -> IdxCa {
461 invalid_operation_panic!(arg_sort, self)
462 }
463
464 fn null_count(&self) -> usize;
466
467 fn has_nulls(&self) -> bool;
469
470 fn unique(&self) -> PolarsResult<Series> {
472 polars_bail!(opq = unique, self._dtype());
473 }
474
475 fn n_unique(&self) -> PolarsResult<usize> {
479 polars_bail!(opq = n_unique, self._dtype());
480 }
481
482 fn arg_unique(&self) -> PolarsResult<IdxCa> {
484 polars_bail!(opq = arg_unique, self._dtype());
485 }
486
487 fn unique_id(&self) -> PolarsResult<(IdxSize, Vec<IdxSize>)> {
491 polars_bail!(opq = unique_id, self._dtype());
492 }
493
494 fn is_null(&self) -> BooleanChunked;
496
497 fn is_not_null(&self) -> BooleanChunked;
499
500 fn reverse(&self) -> Series;
502
503 fn as_single_ptr(&mut self) -> PolarsResult<usize> {
506 polars_bail!(opq = as_single_ptr, self._dtype());
507 }
508
509 fn shift(&self, _periods: i64) -> Series;
536
537 fn sum_reduce(&self) -> PolarsResult<Scalar> {
542 polars_bail!(opq = sum, self._dtype());
543 }
544 fn max_reduce(&self) -> PolarsResult<Scalar> {
546 polars_bail!(opq = max, self._dtype());
547 }
548 fn min_reduce(&self) -> PolarsResult<Scalar> {
550 polars_bail!(opq = min, self._dtype());
551 }
552 fn median_reduce(&self) -> PolarsResult<Scalar> {
554 polars_bail!(opq = median, self._dtype());
555 }
556 fn mean_reduce(&self) -> PolarsResult<Scalar> {
558 polars_bail!(opq = mean, self._dtype());
559 }
560 fn var_reduce(&self, _ddof: u8) -> PolarsResult<Scalar> {
562 polars_bail!(opq = var, self._dtype());
563 }
564 fn std_reduce(&self, _ddof: u8) -> PolarsResult<Scalar> {
566 polars_bail!(opq = std, self._dtype());
567 }
568 fn quantile_reduce(&self, _quantile: f64, _method: QuantileMethod) -> PolarsResult<Scalar> {
570 polars_bail!(opq = quantile, self._dtype());
571 }
572 fn quantiles_reduce(
574 &self,
575 _quantiles: &[f64],
576 _method: QuantileMethod,
577 ) -> PolarsResult<Scalar> {
578 polars_bail!(opq = quantiles, self._dtype());
579 }
580 fn and_reduce(&self) -> PolarsResult<Scalar> {
582 polars_bail!(opq = and_reduce, self._dtype());
583 }
584 fn or_reduce(&self) -> PolarsResult<Scalar> {
586 polars_bail!(opq = or_reduce, self._dtype());
587 }
588 fn xor_reduce(&self) -> PolarsResult<Scalar> {
590 polars_bail!(opq = xor_reduce, self._dtype());
591 }
592
593 fn first(&self) -> Scalar {
597 let dt = self.dtype();
598 let av = self.get(0).map_or(AnyValue::Null, AnyValue::into_static);
599
600 Scalar::new(dt.clone(), av)
601 }
602
603 fn first_non_null(&self) -> Scalar {
607 let av = if self.len() == 0 {
608 AnyValue::Null
609 } else {
610 let idx = if self.has_nulls() {
611 first_non_null(self.chunks().iter().map(|c| c.as_ref())).unwrap_or(0)
612 } else {
613 0
614 };
615 self.get(idx).map_or(AnyValue::Null, AnyValue::into_static)
616 };
617 Scalar::new(self.dtype().clone(), av)
618 }
619
620 fn last(&self) -> Scalar {
624 let dt = self.dtype();
625 let av = if self.len() == 0 {
626 AnyValue::Null
627 } else {
628 unsafe { self.get_unchecked(self.len() - 1) }.into_static()
630 };
631
632 Scalar::new(dt.clone(), av)
633 }
634
635 fn last_non_null(&self) -> Scalar {
639 let n = self.len();
640 let av = if n == 0 {
641 AnyValue::Null
642 } else {
643 let idx = if self.has_nulls() {
644 last_non_null(self.chunks().iter().map(|c| c.as_ref()), n).unwrap_or(n - 1)
645 } else {
646 n - 1
647 };
648 unsafe { self.get_unchecked(idx) }.into_static()
650 };
651 Scalar::new(self.dtype().clone(), av)
652 }
653
654 #[cfg(feature = "approx_unique")]
655 fn approx_n_unique(&self) -> PolarsResult<IdxSize> {
656 polars_bail!(opq = approx_n_unique, self._dtype());
657 }
658
659 fn clone_inner(&self) -> Arc<dyn SeriesTrait>;
661
662 #[cfg(feature = "object")]
663 fn get_object(&self, _index: usize) -> Option<&dyn PolarsObjectSafe> {
665 invalid_operation_panic!(get_object, self)
666 }
667
668 #[cfg(feature = "object")]
669 unsafe fn get_object_chunked_unchecked(
674 &self,
675 _chunk: usize,
676 _index: usize,
677 ) -> Option<&dyn PolarsObjectSafe> {
678 invalid_operation_panic!(get_object_chunked_unchecked, self)
679 }
680
681 fn as_any(&self) -> &dyn Any;
684
685 fn as_any_mut(&mut self) -> &mut dyn Any;
688
689 fn as_phys_any(&self) -> &dyn Any;
692
693 fn as_arc_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
694
695 #[cfg(feature = "checked_arithmetic")]
696 fn checked_div(&self, _rhs: &Series) -> PolarsResult<Series> {
697 polars_bail!(opq = checked_div, self._dtype());
698 }
699
700 #[cfg(feature = "rolling_window")]
701 fn rolling_map(
704 &self,
705 _f: &dyn Fn(&Series) -> PolarsResult<Series>,
706 _options: RollingOptionsFixedWindow,
707 ) -> PolarsResult<Series> {
708 polars_bail!(opq = rolling_map, self._dtype());
709 }
710}
711
712impl dyn SeriesTrait + '_ {
713 pub fn unpack<T: PolarsPhysicalType>(&self) -> PolarsResult<&ChunkedArray<T>> {
714 polars_ensure!(&T::get_static_dtype() == self.dtype(), unpack);
715 Ok(self.as_ref())
716 }
717}