Skip to main content

vortex_functions/
change_time_unit.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Convert a temporal value to a coarser unit with an explicit rounding mode.
5//!
6//! `cast` performs only the temporal conversions that are exact for every valid value. A coarser
7//! unit can drop part of a count, so this function makes the caller choose a [`TemporalRounding`].
8
9use std::fmt;
10
11use prost::Message;
12use vortex_array::ArrayRef;
13use vortex_array::ExecutionCtx;
14use vortex_array::dtype::DType;
15use vortex_array::extension::datetime::AnyTemporal;
16use vortex_array::extension::datetime::Date;
17use vortex_array::extension::datetime::Duration;
18use vortex_array::extension::datetime::TemporalMetadata;
19use vortex_array::extension::datetime::TemporalRounding;
20use vortex_array::extension::datetime::Time;
21use vortex_array::extension::datetime::TimeUnit;
22use vortex_array::extension::datetime::Timestamp;
23use vortex_array::extension::datetime::check_time_of_day;
24use vortex_array::extension::datetime::map_counts;
25use vortex_array::proto::expr as pb;
26use vortex_array::proto::expr::change_time_unit_opts::Rounding as PbRounding;
27use vortex_array::scalar_fn::Arity;
28use vortex_array::scalar_fn::ChildName;
29use vortex_array::scalar_fn::ExecutionArgs;
30use vortex_array::scalar_fn::ScalarFnId;
31use vortex_array::scalar_fn::ScalarFnVTable;
32use vortex_error::VortexExpect;
33use vortex_error::VortexResult;
34use vortex_error::vortex_bail;
35use vortex_error::vortex_ensure;
36use vortex_error::vortex_err;
37use vortex_session::VortexSession;
38use vortex_session::registry::CachedId;
39
40/// Options for [`ChangeTimeUnit`].
41#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
42pub struct ChangeTimeUnitOptions {
43    /// The target unit, which must be coarser than the input unit.
44    pub unit: TimeUnit,
45    /// How to round a count that the target unit cannot represent exactly.
46    pub rounding: TemporalRounding,
47}
48
49impl fmt::Display for ChangeTimeUnitOptions {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        write!(f, "unit={}, rounding={}", self.unit, self.rounding)
52    }
53}
54
55/// Convert a [`Date`], [`Time`], or [`Timestamp`] to a coarser unit.
56///
57/// See [`change_time_unit`](crate::expr::change_time_unit) for the contract.
58#[derive(Clone)]
59pub struct ChangeTimeUnit;
60
61impl ScalarFnVTable for ChangeTimeUnit {
62    type Options = ChangeTimeUnitOptions;
63
64    fn id(&self) -> ScalarFnId {
65        static ID: CachedId = CachedId::new("vortex.change_time_unit");
66        *ID
67    }
68
69    fn serialize(&self, options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
70        let rounding = match options.rounding {
71            TemporalRounding::Exact => PbRounding::Exact,
72            TemporalRounding::TowardZero => PbRounding::TowardZero,
73            TemporalRounding::Floor => PbRounding::Floor,
74            TemporalRounding::NearestTiesAwayFromZero => PbRounding::NearestTiesAwayFromZero,
75        };
76
77        Ok(Some(
78            pb::ChangeTimeUnitOpts {
79                unit: u32::from(u8::from(options.unit)),
80                rounding: rounding.into(),
81            }
82            .encode_to_vec(),
83        ))
84    }
85
86    fn deserialize(
87        &self,
88        metadata: &[u8],
89        _session: &VortexSession,
90    ) -> VortexResult<Self::Options> {
91        let options = pb::ChangeTimeUnitOpts::decode(metadata)?;
92        let rounding = match PbRounding::try_from(options.rounding) {
93            Ok(PbRounding::Exact) => TemporalRounding::Exact,
94            Ok(PbRounding::TowardZero) => TemporalRounding::TowardZero,
95            Ok(PbRounding::Floor) => TemporalRounding::Floor,
96            Ok(PbRounding::NearestTiesAwayFromZero) => TemporalRounding::NearestTiesAwayFromZero,
97            Err(_) => vortex_bail!(
98                "Expected a known temporal rounding mode, got {}",
99                options.rounding
100            ),
101        };
102
103        Ok(ChangeTimeUnitOptions {
104            unit: TimeUnit::try_from(u8::try_from(options.unit)?)?,
105            rounding,
106        })
107    }
108
109    fn arity(&self, _options: &Self::Options) -> Arity {
110        Arity::Exact(1)
111    }
112
113    fn child_name(&self, _options: &Self::Options, _child_idx: usize) -> ChildName {
114        ChildName::from("input")
115    }
116
117    fn return_dtype(&self, options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
118        let input = &arg_dtypes[0];
119        let metadata = input
120            .as_extension_opt()
121            .and_then(|ext| ext.metadata_opt::<AnyTemporal>())
122            .ok_or_else(|| vortex_err!("Expected a temporal dtype, got {input}"))?;
123        let source_unit = metadata.time_unit();
124        let unit = options.unit;
125        vortex_ensure!(
126            unit.nanos_per_unit() > source_unit.nanos_per_unit(),
127            "Expected a unit coarser than {source_unit}, got {unit}"
128        );
129
130        let nullability = input.nullability();
131        let target = match metadata {
132            TemporalMetadata::Timestamp(_, zone) => {
133                Timestamp::try_new_with_tz(unit, zone.clone(), nullability)?.erased()
134            }
135            TemporalMetadata::Time(_) => Time::try_new(unit, nullability)?.erased(),
136            TemporalMetadata::Date(_) => Date::try_new(unit, nullability)?.erased(),
137            TemporalMetadata::Duration(_) => Duration::try_new(unit, nullability)?.erased(),
138        };
139        Ok(DType::Extension(target))
140    }
141
142    fn execute(
143        &self,
144        options: &Self::Options,
145        args: &dyn ExecutionArgs,
146        ctx: &mut ExecutionCtx,
147    ) -> VortexResult<ArrayRef> {
148        let input = args.get(0)?;
149        let target = self.return_dtype(options, std::slice::from_ref(input.dtype()))?;
150        let metadata = input
151            .dtype()
152            .as_extension_opt()
153            .and_then(|ext| ext.metadata_opt::<AnyTemporal>())
154            .vortex_expect("`return_dtype` above accepts only temporal inputs");
155        let is_time = matches!(metadata, TemporalMetadata::Time(_));
156        let source_unit = metadata.time_unit();
157        let ChangeTimeUnitOptions { unit, rounding } = *options;
158        let divisor = unit.nanos_per_unit() / source_unit.nanos_per_unit();
159
160        // A time must stay within one day, and rounding up the last fraction of a day reaches
161        // midnight, which is outside that range.
162        if is_time {
163            return map_counts(input, &target, ctx, |value| {
164                check_time_of_day(value, source_unit)?;
165                let result = rounding.divide(value, divisor)?;
166                check_time_of_day(result, unit)?;
167                Ok(result)
168            });
169        }
170
171        map_counts(input, &target, ctx, |value| rounding.divide(value, divisor))
172    }
173
174    fn is_strict(&self, _options: &Self::Options) -> bool {
175        true
176    }
177}
178
179#[cfg(test)]
180mod tests {
181    use rstest::rstest;
182    use vortex_array::ArrayRef;
183    use vortex_array::IntoArray;
184    use vortex_array::VortexSessionExecute;
185    use vortex_array::arrays::ExtensionArray;
186    use vortex_array::arrays::PrimitiveArray;
187    use vortex_array::dtype::Nullability;
188    use vortex_array::dtype::extension::ExtDTypeRef;
189    use vortex_array::extension::datetime::TemporalRounding;
190    use vortex_array::extension::datetime::Time;
191    use vortex_array::extension::datetime::TimeUnit;
192    use vortex_array::extension::datetime::Timestamp;
193    use vortex_array::test_harness::ExpectedOutcome;
194    use vortex_array::test_harness::assert_execution_paths;
195    use vortex_buffer::buffer;
196    use vortex_error::VortexResult;
197    use vortex_expr::ArrayExprExt;
198    use vortex_expr::Expression;
199    use vortex_expr::proto::ExprSerializeProtoExt;
200    use vortex_expr::root;
201    use vortex_session::VortexSession;
202
203    use crate::expr::change_time_unit;
204
205    const NON_NULLABLE: Nullability = Nullability::NonNullable;
206
207    #[rstest]
208    #[case::toward_zero(TemporalRounding::TowardZero, [Some(0), Some(0), None])]
209    #[case::floor(TemporalRounding::Floor, [Some(-1), Some(0), None])]
210    #[case::nearest(TemporalRounding::NearestTiesAwayFromZero, [Some(-1), Some(1), None])]
211    fn test_change_timestamp_unit_rounding(
212        #[case] mode: TemporalRounding,
213        #[case] values: [Option<i64>; 3],
214    ) -> VortexResult<()> {
215        let source = Timestamp::new(TimeUnit::Nanoseconds, Nullability::Nullable).erased();
216        let target = Timestamp::new(TimeUnit::Milliseconds, Nullability::Nullable).erased();
217        let input = ExtensionArray::try_new(
218            source,
219            PrimitiveArray::from_option_iter([Some(-750_000i64), Some(500_000), None]).into_array(),
220        )?
221        .into_array();
222        let expected = ExtensionArray::try_new(
223            target,
224            PrimitiveArray::from_option_iter(values).into_array(),
225        )?;
226        let session = VortexSession::empty();
227        crate::initialize(&session);
228        let mut ctx = session.create_execution_ctx();
229        let operation = change_time_unit(root(), TimeUnit::Milliseconds, mode);
230        let restored = Expression::from_proto(&operation.serialize_proto()?, &session)?;
231        assert_execution_paths(
232            &[input],
233            |inputs| inputs[0].clone().apply(&restored),
234            ExpectedOutcome::Array(expected.into_array()),
235            &mut ctx,
236        );
237        Ok(())
238    }
239
240    #[rstest]
241    #[case::time_rounds_up_to_midnight(
242        Time::new(TimeUnit::Milliseconds, NON_NULLABLE).erased(),
243        buffer![86_399_500i32].into_array(),
244        TimeUnit::Seconds,
245        TemporalRounding::NearestTiesAwayFromZero,
246    )]
247    #[case::exact_with_remainder(
248        Timestamp::new(TimeUnit::Nanoseconds, NON_NULLABLE).erased(),
249        buffer![1_500_000i64].into_array(),
250        TimeUnit::Milliseconds,
251        TemporalRounding::Exact,
252    )]
253    fn test_change_time_unit_errors(
254        #[case] source: ExtDTypeRef,
255        #[case] storage: ArrayRef,
256        #[case] unit: TimeUnit,
257        #[case] rounding: TemporalRounding,
258    ) -> VortexResult<()> {
259        let input = ExtensionArray::try_new(source, storage)?;
260        let operation = change_time_unit(root(), unit, rounding);
261        assert_execution_paths(
262            &[input.into_array()],
263            |inputs| inputs[0].clone().apply(&operation),
264            ExpectedOutcome::Error,
265            &mut VortexSession::empty().create_execution_ctx(),
266        );
267        Ok(())
268    }
269}