Skip to main content

polars_core/chunked_array/ops/
explode_and_offsets.rs

1use polars_arrow::offset::OffsetsBuffer;
2use polars_compute::gather::take_unchecked;
3
4use super::*;
5
6impl ListChunked {
7    fn explode_specialized(
8        &self,
9        values: ArrayRef,
10        offsets: &[i64],
11        offsets_buf: OffsetsBuffer<i64>,
12        options: ExplodeOptions,
13    ) -> (Series, OffsetsBuffer<i64>) {
14        // SAFETY: inner_dtype should be correct
15        let values = unsafe {
16            Series::from_chunks_and_dtype_unchecked(
17                self.name().clone(),
18                vec![values],
19                &self.inner_dtype().to_physical(),
20            )
21        };
22
23        use crate::chunked_array::ops::explode::ExplodeByOffsets;
24
25        let mut values = match values.dtype() {
26            DataType::Boolean => {
27                let t = values.bool().unwrap();
28                ExplodeByOffsets::explode_by_offsets(t, offsets, options).into_series()
29            },
30            DataType::Null => {
31                let t = values.null().unwrap();
32                ExplodeByOffsets::explode_by_offsets(t, offsets, options).into_series()
33            },
34            dtype => {
35                with_match_physical_numeric_polars_type!(dtype, |$T| {
36                    let t: &ChunkedArray<$T> = values.as_ref().as_ref();
37                    ExplodeByOffsets::explode_by_offsets(t, offsets, options).into_series()
38                })
39            },
40        };
41
42        // let mut values = values.explode_by_offsets(offsets);
43        // restore logical type
44        values = unsafe { values.from_physical_unchecked(self.inner_dtype()) }.unwrap();
45
46        (values, offsets_buf)
47    }
48}
49
50impl ChunkExplode for ListChunked {
51    fn offsets(&self) -> PolarsResult<OffsetsBuffer<i64>> {
52        let ca = self.rechunk();
53        let listarr: &LargeListArray = ca.downcast_iter().next().unwrap();
54        let offsets = listarr.offsets().clone();
55        Ok(offsets)
56    }
57
58    fn explode_and_offsets(
59        &self,
60        options: ExplodeOptions,
61    ) -> PolarsResult<(Series, OffsetsBuffer<i64>)> {
62        // A list array's memory layout is actually already 'exploded', so we can just take the
63        // values array of the list. And we also return a slice of the offsets. This slice can be
64        // used to find the old list layout or indexes to expand a DataFrame in the same manner as
65        // the `explode` operation.
66        let ca = self.rechunk();
67        let listarr: &LargeListArray = ca.downcast_iter().next().unwrap();
68        let offsets_buf = listarr.offsets().clone();
69        let offsets = listarr.offsets().as_slice();
70        let mut values = listarr.values().clone();
71
72        // Without null rows the values between the first and last offset are exactly the
73        // exploded values, so the fast-explode flag is not needed to take them as they are.
74        let (mut s, offsets) = if (ca._can_fast_explode() || listarr.null_count() == 0)
75            && (!options.keep_nulls || !ca.has_nulls())
76            && (!options.empty_as_null || !ca.has_empty_lists())
77        {
78            // ensure that the value array is sliced
79            // as a list only slices its offsets on a slice operation
80
81            // we only do this in fast-explode as for the other
82            // branch the offsets must coincide with the values.
83            if !offsets.is_empty() {
84                let start = offsets[0] as usize;
85                let len = offsets[offsets.len() - 1] as usize - start;
86                // SAFETY:
87                // we are in bounds
88                values = unsafe { values.sliced_unchecked(start, len) };
89            }
90            // SAFETY: inner_dtype should be correct
91            (
92                unsafe {
93                    Series::from_chunks_and_dtype_unchecked(
94                        self.name().clone(),
95                        vec![values],
96                        &self.inner_dtype().to_physical(),
97                    )
98                },
99                offsets_buf,
100            )
101        } else {
102            // during tests
103            // test that this code branch is not hit with list arrays that could be fast exploded
104            #[cfg(test)]
105            assert!(
106                listarr.null_count() > 0 || (options.empty_as_null && ca.has_empty_lists()),
107                "could have fast exploded"
108            );
109            let (indices, new_offsets) = if listarr.null_count() == 0 {
110                // SPECIALIZED path.
111                let inner_phys = self.inner_dtype().to_physical();
112                if inner_phys.is_primitive_numeric() || inner_phys.is_null() || inner_phys.is_bool()
113                {
114                    return Ok(self.explode_specialized(values, offsets, offsets_buf, options));
115                }
116                // Use gather
117                let mut indices =
118                    MutablePrimitiveArray::<IdxSize>::with_capacity(*offsets_buf.last() as usize);
119                let mut new_offsets = Vec::with_capacity(listarr.len() + 1);
120                let mut current_offset = 0i64;
121                let mut iter = offsets.iter();
122                if let Some(mut previous) = iter.next().copied() {
123                    new_offsets.push(current_offset);
124                    iter.for_each(|&offset| {
125                        let len = offset - previous;
126                        let start = previous as IdxSize;
127                        let end = offset as IdxSize;
128
129                        if options.empty_as_null && len == 0 {
130                            indices.push_null();
131                        } else {
132                            indices.extend_trusted_len_values(start..end);
133                        }
134                        current_offset += len;
135                        previous = offset;
136                        new_offsets.push(current_offset);
137                    })
138                }
139                (indices, new_offsets)
140            } else {
141                // we have already ensured that validity is not none.
142                let validity = listarr.validity().unwrap();
143
144                let mut indices =
145                    MutablePrimitiveArray::<IdxSize>::with_capacity(*offsets_buf.last() as usize);
146                let mut new_offsets = Vec::with_capacity(listarr.len() + 1);
147                let mut current_offset = 0i64;
148                let mut iter = offsets.iter();
149                if let Some(mut previous) = iter.next().copied() {
150                    new_offsets.push(current_offset);
151                    iter.enumerate().for_each(|(i, &offset)| {
152                        let len = offset - previous;
153                        let start = previous as IdxSize;
154                        let end = offset as IdxSize;
155                        // SAFETY: we are within bounds
156                        if unsafe { validity.get_bit_unchecked(i) } {
157                            // explode expects null value if sublist is empty.
158                            if options.empty_as_null && len == 0 {
159                                indices.push_null();
160                            } else {
161                                indices.extend_trusted_len_values(start..end);
162                            }
163                            current_offset += len;
164                        } else if options.keep_nulls {
165                            indices.push_null();
166                        }
167                        previous = offset;
168                        new_offsets.push(current_offset);
169                    })
170                }
171                (indices, new_offsets)
172            };
173
174            // SAFETY: the indices we generate are in bounds
175            let chunk = unsafe { take_unchecked(values.as_ref(), &indices.into()) };
176            // SAFETY: inner_dtype should be correct
177            let s = unsafe {
178                Series::from_chunks_and_dtype_unchecked(
179                    self.name().clone(),
180                    vec![chunk],
181                    &self.inner_dtype().to_physical(),
182                )
183            };
184            // SAFETY: monotonically increasing
185            let new_offsets = unsafe { OffsetsBuffer::new_unchecked(new_offsets.into()) };
186            (s, new_offsets)
187        };
188        debug_assert_eq!(s.name(), self.name());
189        // restore logical type
190        s = unsafe { s.from_physical_unchecked(self.inner_dtype()) }.unwrap();
191
192        Ok((s, offsets))
193    }
194}
195
196#[cfg(feature = "dtype-array")]
197impl ChunkExplode for ArrayChunked {
198    fn offsets(&self) -> PolarsResult<OffsetsBuffer<i64>> {
199        // fast-path for non-null array.
200        if self.null_count() == 0 {
201            let width = self.width() as i64;
202            let offsets = (0..self.len() + 1)
203                .map(|i| {
204                    let i = i as i64;
205                    i * width
206                })
207                .collect::<Vec<_>>();
208            // SAFETY: monotonically increasing
209            let offsets = unsafe { OffsetsBuffer::new_unchecked(offsets.into()) };
210
211            return Ok(offsets);
212        }
213
214        let ca = self.rechunk();
215        let arr = ca.downcast_iter().next().unwrap();
216        // we have already ensured that validity is not none.
217        let validity = arr.validity().unwrap();
218        let width = arr.size();
219
220        let mut current_offset = 0i64;
221        let offsets = (0..=arr.len())
222            .map(|i| {
223                if i == 0 {
224                    return current_offset;
225                }
226                // SAFETY: we are within bounds
227                if unsafe { validity.get_bit_unchecked(i - 1) } {
228                    current_offset += width as i64
229                }
230                current_offset
231            })
232            .collect::<Vec<_>>();
233        // SAFETY: monotonically increasing
234        let offsets = unsafe { OffsetsBuffer::new_unchecked(offsets.into()) };
235        Ok(offsets)
236    }
237
238    fn explode_and_offsets(
239        &self,
240        options: ExplodeOptions,
241    ) -> PolarsResult<(Series, OffsetsBuffer<i64>)> {
242        if self.width() == 0 {
243            let mut num_nulls = 0;
244            if options.empty_as_null {
245                num_nulls += self.len() - self.null_count();
246            }
247            if options.keep_nulls {
248                num_nulls += self.null_count();
249            }
250            let offsets = (0..num_nulls as i64 + 1).collect::<Vec<i64>>();
251            // SAFETY: monotonically increasing
252            let offsets = unsafe { OffsetsBuffer::new_unchecked(offsets.into()) };
253            let s = Column::new_scalar(
254                self.name().clone(),
255                Scalar::null(self.inner_dtype().clone()),
256                num_nulls,
257            )
258            .take_materialized_series();
259
260            return Ok((s, offsets));
261        }
262
263        let ca = self.rechunk();
264        let arr = ca.downcast_iter().next().unwrap();
265        // fast-path for non-null array.
266        if arr.null_count() == 0 {
267            let s = unsafe {
268                Series::from_chunks_and_dtype_unchecked(
269                    self.name().clone(),
270                    vec![arr.values().clone()],
271                    ca.inner_dtype(),
272                )
273            };
274            let width = self.width() as i64;
275            let offsets = (0..self.len() + 1)
276                .map(|i| {
277                    let i = i as i64;
278                    i * width
279                })
280                .collect::<Vec<_>>();
281            // SAFETY: monotonically increasing
282            let offsets = unsafe { OffsetsBuffer::new_unchecked(offsets.into()) };
283            return Ok((s, offsets));
284        }
285
286        // we have already ensured that validity is not none.
287        let validity = arr.validity().unwrap();
288        let values = arr.values();
289        let width = arr.size();
290
291        let mut indices = MutablePrimitiveArray::<IdxSize>::with_capacity(
292            values.len() - arr.null_count() * (width - 1),
293        );
294        let mut offsets = Vec::with_capacity(arr.len() + 1);
295        let mut current_offset = 0i64;
296        offsets.push(current_offset);
297        (0..arr.len()).for_each(|i| {
298            // SAFETY: we are within bounds
299            if unsafe { validity.get_bit_unchecked(i) } {
300                let start = (i * width) as IdxSize;
301                let end = start + width as IdxSize;
302                indices.extend_trusted_len_values(start..end);
303                current_offset += width as i64;
304            } else if options.keep_nulls {
305                indices.push_null();
306            }
307            offsets.push(current_offset);
308        });
309
310        // SAFETY: the indices we generate are in bounds
311        let chunk = unsafe { take_unchecked(&**values, &indices.into()) };
312        // SAFETY: monotonically increasing
313        let offsets = unsafe { OffsetsBuffer::new_unchecked(offsets.into()) };
314
315        Ok((
316            // SAFETY: inner_dtype should be correct
317            unsafe {
318                Series::from_chunks_and_dtype_unchecked(
319                    ca.name().clone(),
320                    vec![chunk],
321                    ca.inner_dtype(),
322                )
323            },
324            offsets,
325        ))
326    }
327}