arrow-schema 58.1.0

Defines the logical types for arrow arrays
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

//! FixedShapeTensor
//!
//! <https://arrow.apache.org/docs/format/CanonicalExtensions.html#fixed-shape-tensor>

use serde_core::de::{self, MapAccess, Visitor};
use serde_core::ser::SerializeStruct;
use serde_core::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;

use crate::{ArrowError, DataType, extension::ExtensionType};

/// The extension type for fixed shape tensor.
///
/// Extension name: `arrow.fixed_shape_tensor`.
///
/// The storage type of the extension: `FixedSizeList` where:
/// - `value_type` is the data type of individual tensor elements.
/// - `list_size` is the product of all the elements in tensor shape.
///
/// Extension type parameters:
/// - `value_type`: the Arrow data type of individual tensor elements.
/// - `shape`: the physical shape of the contained tensors as an array.
///
/// Optional parameters describing the logical layout:
/// - `dim_names`: explicit names to tensor dimensions as an array. The
///   length of it should be equal to the shape length and equal to the
///   number of dimensions.
///   `dim_names` can be used if the dimensions have
///   well-known names and they map to the physical layout (row-major).
/// - `permutation`: indices of the desired ordering of the original
///   dimensions, defined as an array.
///   The indices contain a permutation of the values `[0, 1, .., N-1]`
///   where `N` is the number of dimensions. The permutation indicates
///   which dimension of the logical layout corresponds to which dimension
///   of the physical tensor (the i-th dimension of the logical view
///   corresponds to the dimension with number `permutations[i]` of the
///   physical tensor).
///   Permutation can be useful in case the logical order of the tensor is
///   a permutation of the physical order (row-major).
///   When logical and physical layout are equal, the permutation will
///   always be `([0, 1, .., N-1])` and can therefore be left out.
///
/// Description of the serialization:
/// The metadata must be a valid JSON object including shape of the
/// contained tensors as an array with key `shape` plus optional
/// dimension names with keys `dim_names` and ordering of the
/// dimensions with key `permutation`.
/// Example: `{ "shape": [2, 5]}`
/// Example with `dim_names` metadata for NCHW ordered data:
/// `{ "shape": [100, 200, 500], "dim_names": ["C", "H", "W"]}`
/// Example of permuted 3-dimensional tensor:
/// `{ "shape": [100, 200, 500], "permutation": [2, 0, 1]}`
///
/// This is the physical layout shape and the shape of the logical layout
/// would in this case be `[500, 100, 200]`.
///
/// <https://arrow.apache.org/docs/format/CanonicalExtensions.html#fixed-shape-tensor>
#[derive(Debug, Clone, PartialEq)]
pub struct FixedShapeTensor {
    /// The data type of individual tensor elements.
    value_type: DataType,

    /// The metadata of this extension type.
    metadata: FixedShapeTensorMetadata,
}

impl FixedShapeTensor {
    /// Returns a new fixed shape tensor extension type.
    ///
    /// # Error
    ///
    /// Return an error if the provided dimension names or permutations are
    /// invalid.
    pub fn try_new(
        value_type: DataType,
        shape: impl IntoIterator<Item = usize>,
        dimension_names: Option<Vec<String>>,
        permutations: Option<Vec<usize>>,
    ) -> Result<Self, ArrowError> {
        // TODO: are all data types are suitable as value type?
        FixedShapeTensorMetadata::try_new(shape, dimension_names, permutations).map(|metadata| {
            Self {
                value_type,
                metadata,
            }
        })
    }

    /// Returns the value type of the individual tensor elements.
    pub fn value_type(&self) -> &DataType {
        &self.value_type
    }

    /// Returns the product of all the elements in tensor shape.
    pub fn list_size(&self) -> usize {
        self.metadata.list_size()
    }

    /// Returns the number of dimensions in this fixed shape tensor.
    pub fn dimensions(&self) -> usize {
        self.metadata.dimensions()
    }

    /// Returns the names of the dimensions in this fixed shape tensor, if
    /// set.
    pub fn dimension_names(&self) -> Option<&[String]> {
        self.metadata.dimension_names()
    }

    /// Returns the indices of the desired ordering of the original
    /// dimensions, if set.
    pub fn permutations(&self) -> Option<&[usize]> {
        self.metadata.permutations()
    }
}

/// Extension type metadata for [`FixedShapeTensor`].
#[derive(Debug, Clone, PartialEq)]
pub struct FixedShapeTensorMetadata {
    /// The physical shape of the contained tensors.
    shape: Vec<usize>,

    /// Explicit names to tensor dimensions.
    dim_names: Option<Vec<String>>,

    /// Indices of the desired ordering of the original dimensions.
    permutations: Option<Vec<usize>>,
}

impl Serialize for FixedShapeTensorMetadata {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("FixedShapeTensorMetadata", 3)?;
        state.serialize_field("shape", &self.shape)?;
        state.serialize_field("dim_names", &self.dim_names)?;
        state.serialize_field("permutations", &self.permutations)?;
        state.end()
    }
}

#[derive(Debug)]
enum MetadataField {
    Shape,
    DimNames,
    Permutations,
}

struct MetadataFieldVisitor;

impl<'de> Visitor<'de> for MetadataFieldVisitor {
    type Value = MetadataField;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("`shape`, `dim_names`, or `permutations`")
    }

    fn visit_str<E>(self, value: &str) -> Result<MetadataField, E>
    where
        E: de::Error,
    {
        match value {
            "shape" => Ok(MetadataField::Shape),
            "dim_names" => Ok(MetadataField::DimNames),
            "permutations" => Ok(MetadataField::Permutations),
            _ => Err(de::Error::unknown_field(
                value,
                &["shape", "dim_names", "permutations"],
            )),
        }
    }
}

impl<'de> Deserialize<'de> for MetadataField {
    fn deserialize<D>(deserializer: D) -> Result<MetadataField, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_identifier(MetadataFieldVisitor)
    }
}

struct FixedShapeTensorMetadataVisitor;

impl<'de> Visitor<'de> for FixedShapeTensorMetadataVisitor {
    type Value = FixedShapeTensorMetadata;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("struct FixedShapeTensorMetadata")
    }

    fn visit_seq<V>(self, mut seq: V) -> Result<FixedShapeTensorMetadata, V::Error>
    where
        V: de::SeqAccess<'de>,
    {
        let shape = seq
            .next_element()?
            .ok_or_else(|| de::Error::invalid_length(0, &self))?;
        let dim_names = seq
            .next_element()?
            .ok_or_else(|| de::Error::invalid_length(1, &self))?;
        let permutations = seq
            .next_element()?
            .ok_or_else(|| de::Error::invalid_length(2, &self))?;
        Ok(FixedShapeTensorMetadata {
            shape,
            dim_names,
            permutations,
        })
    }

    fn visit_map<V>(self, mut map: V) -> Result<FixedShapeTensorMetadata, V::Error>
    where
        V: MapAccess<'de>,
    {
        let mut shape = None;
        let mut dim_names = None;
        let mut permutations = None;

        while let Some(key) = map.next_key()? {
            match key {
                MetadataField::Shape => {
                    if shape.is_some() {
                        return Err(de::Error::duplicate_field("shape"));
                    }
                    shape = Some(map.next_value()?);
                }
                MetadataField::DimNames => {
                    if dim_names.is_some() {
                        return Err(de::Error::duplicate_field("dim_names"));
                    }
                    dim_names = Some(map.next_value()?);
                }
                MetadataField::Permutations => {
                    if permutations.is_some() {
                        return Err(de::Error::duplicate_field("permutations"));
                    }
                    permutations = Some(map.next_value()?);
                }
            }
        }

        let shape = shape.ok_or_else(|| de::Error::missing_field("shape"))?;

        Ok(FixedShapeTensorMetadata {
            shape,
            dim_names,
            permutations,
        })
    }
}

impl<'de> Deserialize<'de> for FixedShapeTensorMetadata {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_struct(
            "FixedShapeTensorMetadata",
            &["shape", "dim_names", "permutations"],
            FixedShapeTensorMetadataVisitor,
        )
    }
}

impl FixedShapeTensorMetadata {
    /// Returns metadata for a fixed shape tensor extension type.
    ///
    /// # Error
    ///
    /// Return an error if the provided dimension names or permutations are
    /// invalid.
    pub fn try_new(
        shape: impl IntoIterator<Item = usize>,
        dimension_names: Option<Vec<String>>,
        permutations: Option<Vec<usize>>,
    ) -> Result<Self, ArrowError> {
        let shape = shape.into_iter().collect::<Vec<_>>();
        let dimensions = shape.len();

        let dim_names = dimension_names.map(|dimension_names| {
            if dimension_names.len() != dimensions {
                Err(ArrowError::InvalidArgumentError(format!(
                    "FixedShapeTensor dimension names size mismatch, expected {dimensions}, found {}", dimension_names.len()
                )))
            } else {
                Ok(dimension_names)
            }
        }).transpose()?;

        let permutations = permutations
            .map(|permutations| {
                if permutations.len() != dimensions {
                    Err(ArrowError::InvalidArgumentError(format!(
                        "FixedShapeTensor permutations size mismatch, expected {dimensions}, found {}",
                        permutations.len()
                    )))
                } else {
                    let mut sorted_permutations = permutations.clone();
                    sorted_permutations.sort_unstable();
                    if (0..dimensions).zip(sorted_permutations).any(|(a, b)| a != b) {
                        Err(ArrowError::InvalidArgumentError(format!(
                            "FixedShapeTensor permutations invalid, expected a permutation of [0, 1, .., N-1], where N is the number of dimensions: {dimensions}"
                        )))
                    } else {
                        Ok(permutations)
                    }
                }
            })
            .transpose()?;

        Ok(Self {
            shape,
            dim_names,
            permutations,
        })
    }

    /// Returns the product of all the elements in tensor shape.
    pub fn list_size(&self) -> usize {
        self.shape.iter().product()
    }

    /// Returns the number of dimensions in this fixed shape tensor.
    pub fn dimensions(&self) -> usize {
        self.shape.len()
    }

    /// Returns the names of the dimensions in this fixed shape tensor, if
    /// set.
    pub fn dimension_names(&self) -> Option<&[String]> {
        self.dim_names.as_ref().map(AsRef::as_ref)
    }

    /// Returns the indices of the desired ordering of the original
    /// dimensions, if set.
    pub fn permutations(&self) -> Option<&[usize]> {
        self.permutations.as_ref().map(AsRef::as_ref)
    }
}

impl ExtensionType for FixedShapeTensor {
    const NAME: &'static str = "arrow.fixed_shape_tensor";

    type Metadata = FixedShapeTensorMetadata;

    fn metadata(&self) -> &Self::Metadata {
        &self.metadata
    }

    fn serialize_metadata(&self) -> Option<String> {
        Some(serde_json::to_string(&self.metadata).expect("metadata serialization"))
    }

    fn deserialize_metadata(metadata: Option<&str>) -> Result<Self::Metadata, ArrowError> {
        metadata.map_or_else(
            || {
                Err(ArrowError::InvalidArgumentError(
                    "FixedShapeTensor extension types requires metadata".to_owned(),
                ))
            },
            |value| {
                serde_json::from_str(value).map_err(|e| {
                    ArrowError::InvalidArgumentError(format!(
                        "FixedShapeTensor metadata deserialization failed: {e}"
                    ))
                })
            },
        )
    }

    fn supports_data_type(&self, data_type: &DataType) -> Result<(), ArrowError> {
        let expected = DataType::new_fixed_size_list(
            self.value_type.clone(),
            i32::try_from(self.list_size()).expect("overflow"),
            false,
        );
        data_type
            .equals_datatype(&expected)
            .then_some(())
            .ok_or_else(|| {
                ArrowError::InvalidArgumentError(format!(
                    "FixedShapeTensor data type mismatch, expected {expected}, found {data_type}"
                ))
            })
    }

    fn try_new(data_type: &DataType, metadata: Self::Metadata) -> Result<Self, ArrowError> {
        match data_type {
            DataType::FixedSizeList(field, list_size) if !field.is_nullable() => {
                // Make sure the metadata is valid.
                let metadata = FixedShapeTensorMetadata::try_new(
                    metadata.shape,
                    metadata.dim_names,
                    metadata.permutations,
                )?;
                // Make sure it is compatible with this data type.
                let expected_size = i32::try_from(metadata.list_size()).expect("overflow");
                if *list_size != expected_size {
                    Err(ArrowError::InvalidArgumentError(format!(
                        "FixedShapeTensor list size mismatch, expected {expected_size} (metadata), found {list_size} (data type)"
                    )))
                } else {
                    Ok(Self {
                        value_type: field.data_type().clone(),
                        metadata,
                    })
                }
            }
            data_type => Err(ArrowError::InvalidArgumentError(format!(
                "FixedShapeTensor data type mismatch, expected FixedSizeList with non-nullable field, found {data_type}"
            ))),
        }
    }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "canonical_extension_types")]
    use crate::extension::CanonicalExtensionType;
    use crate::{
        Field,
        extension::{EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY},
    };

    use super::*;

    #[test]
    fn valid() -> Result<(), ArrowError> {
        let fixed_shape_tensor = FixedShapeTensor::try_new(
            DataType::Float32,
            [100, 200, 500],
            Some(vec!["C".to_owned(), "H".to_owned(), "W".to_owned()]),
            Some(vec![2, 0, 1]),
        )?;
        let mut field = Field::new_fixed_size_list(
            "",
            Field::new("", DataType::Float32, false),
            i32::try_from(fixed_shape_tensor.list_size()).expect("overflow"),
            false,
        );
        field.try_with_extension_type(fixed_shape_tensor.clone())?;
        assert_eq!(
            field.try_extension_type::<FixedShapeTensor>()?,
            fixed_shape_tensor
        );
        #[cfg(feature = "canonical_extension_types")]
        assert_eq!(
            field.try_canonical_extension_type()?,
            CanonicalExtensionType::FixedShapeTensor(fixed_shape_tensor)
        );
        Ok(())
    }

    #[test]
    #[should_panic(expected = "Extension type name missing")]
    fn missing_name() {
        let field =
            Field::new_fixed_size_list("", Field::new("", DataType::Float32, false), 3, false)
                .with_metadata(
                    [(
                        EXTENSION_TYPE_METADATA_KEY.to_owned(),
                        r#"{ "shape": [100, 200, 500], }"#.to_owned(),
                    )]
                    .into_iter()
                    .collect(),
                );
        field.extension_type::<FixedShapeTensor>();
    }

    #[test]
    #[should_panic(expected = "FixedShapeTensor data type mismatch, expected FixedSizeList")]
    fn invalid_type() {
        let fixed_shape_tensor =
            FixedShapeTensor::try_new(DataType::Int32, [100, 200, 500], None, None).unwrap();
        let field = Field::new_fixed_size_list(
            "",
            Field::new("", DataType::Float32, false),
            i32::try_from(fixed_shape_tensor.list_size()).expect("overflow"),
            false,
        );
        field.with_extension_type(fixed_shape_tensor);
    }

    #[test]
    #[should_panic(expected = "FixedShapeTensor extension types requires metadata")]
    fn missing_metadata() {
        let field =
            Field::new_fixed_size_list("", Field::new("", DataType::Float32, false), 3, false)
                .with_metadata(
                    [(
                        EXTENSION_TYPE_NAME_KEY.to_owned(),
                        FixedShapeTensor::NAME.to_owned(),
                    )]
                    .into_iter()
                    .collect(),
                );
        field.extension_type::<FixedShapeTensor>();
    }

    #[test]
    #[should_panic(expected = "FixedShapeTensor metadata deserialization failed: \
        unknown field `not-shape`, expected one of `shape`, `dim_names`, `permutations`")]
    fn invalid_metadata() {
        let fixed_shape_tensor =
            FixedShapeTensor::try_new(DataType::Float32, [100, 200, 500], None, None).unwrap();
        let field = Field::new_fixed_size_list(
            "",
            Field::new("", DataType::Float32, false),
            i32::try_from(fixed_shape_tensor.list_size()).expect("overflow"),
            false,
        )
        .with_metadata(
            [
                (
                    EXTENSION_TYPE_NAME_KEY.to_owned(),
                    FixedShapeTensor::NAME.to_owned(),
                ),
                (
                    EXTENSION_TYPE_METADATA_KEY.to_owned(),
                    r#"{ "not-shape": [] }"#.to_owned(),
                ),
            ]
            .into_iter()
            .collect(),
        );
        field.extension_type::<FixedShapeTensor>();
    }

    #[test]
    #[should_panic(
        expected = "FixedShapeTensor dimension names size mismatch, expected 3, found 2"
    )]
    fn invalid_metadata_dimension_names() {
        FixedShapeTensor::try_new(
            DataType::Float32,
            [100, 200, 500],
            Some(vec!["a".to_owned(), "b".to_owned()]),
            None,
        )
        .unwrap();
    }

    #[test]
    #[should_panic(expected = "FixedShapeTensor permutations size mismatch, expected 3, found 2")]
    fn invalid_metadata_permutations_len() {
        FixedShapeTensor::try_new(DataType::Float32, [100, 200, 500], None, Some(vec![1, 0]))
            .unwrap();
    }

    #[test]
    #[should_panic(
        expected = "FixedShapeTensor permutations invalid, expected a permutation of [0, 1, .., N-1], where N is the number of dimensions: 3"
    )]
    fn invalid_metadata_permutations_values() {
        FixedShapeTensor::try_new(
            DataType::Float32,
            [100, 200, 500],
            None,
            Some(vec![4, 3, 2]),
        )
        .unwrap();
    }
}