re_types/archetypes/
tensor.rs

1// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/rust/api.rs
2// Based on "crates/store/re_types/definitions/rerun/archetypes/tensor.fbs".
3
4#![allow(unused_braces)]
5#![allow(unused_imports)]
6#![allow(unused_parens)]
7#![allow(clippy::allow_attributes)]
8#![allow(clippy::clone_on_copy)]
9#![allow(clippy::cloned_instead_of_copied)]
10#![allow(clippy::map_flatten)]
11#![allow(clippy::needless_question_mark)]
12#![allow(clippy::new_without_default)]
13#![allow(clippy::redundant_closure)]
14#![allow(clippy::too_many_arguments)]
15#![allow(clippy::too_many_lines)]
16#![allow(clippy::wildcard_imports)]
17
18use ::re_types_core::SerializationResult;
19use ::re_types_core::try_serialize_field;
20use ::re_types_core::{ComponentBatch as _, SerializedComponentBatch};
21use ::re_types_core::{ComponentDescriptor, ComponentType};
22use ::re_types_core::{DeserializationError, DeserializationResult};
23
24/// **Archetype**: An N-dimensional array of numbers.
25///
26/// ## Example
27///
28/// ### Simple tensor
29/// ```ignore
30/// use ndarray::{Array, ShapeBuilder as _};
31/// use rand::prelude::*;
32///
33/// fn main() -> Result<(), Box<dyn std::error::Error>> {
34///     let rec = rerun::RecordingStreamBuilder::new("rerun_example_tensor").spawn()?;
35///
36///     let mut data = Array::<u8, _>::default((8, 6, 3, 5).f());
37///     let mut rng = rand::rngs::SmallRng::seed_from_u64(42);
38///     data.map_inplace(|x| *x = rng.random());
39///
40///     let tensor =
41///         rerun::Tensor::try_from(data)?.with_dim_names(["width", "height", "channel", "batch"]);
42///     rec.log("tensor", &tensor)?;
43///
44///     Ok(())
45/// }
46/// ```
47/// <center>
48/// <picture>
49///   <source media="(max-width: 480px)" srcset="https://static.rerun.io/tensor_simple/baacb07712f7b706e3c80e696f70616c6c20b367/480w.png">
50///   <source media="(max-width: 768px)" srcset="https://static.rerun.io/tensor_simple/baacb07712f7b706e3c80e696f70616c6c20b367/768w.png">
51///   <source media="(max-width: 1024px)" srcset="https://static.rerun.io/tensor_simple/baacb07712f7b706e3c80e696f70616c6c20b367/1024w.png">
52///   <source media="(max-width: 1200px)" srcset="https://static.rerun.io/tensor_simple/baacb07712f7b706e3c80e696f70616c6c20b367/1200w.png">
53///   <img src="https://static.rerun.io/tensor_simple/baacb07712f7b706e3c80e696f70616c6c20b367/full.png" width="640">
54/// </picture>
55/// </center>
56#[derive(Clone, Debug, PartialEq, Default)]
57pub struct Tensor {
58    /// The tensor data
59    pub data: Option<SerializedComponentBatch>,
60
61    /// The expected range of values.
62    ///
63    /// This is typically the expected range of valid values.
64    /// Everything outside of the range is clamped to the range for the purpose of colormpaping.
65    /// Any colormap applied for display, will map this range.
66    ///
67    /// If not specified, the range will be automatically estimated from the data.
68    /// Note that the Viewer may try to guess a wider range than the minimum/maximum of values
69    /// in the contents of the tensor.
70    /// E.g. if all values are positive, some bigger than 1.0 and all smaller than 255.0,
71    /// the Viewer will guess that the data likely came from an 8bit image, thus assuming a range of 0-255.
72    pub value_range: Option<SerializedComponentBatch>,
73}
74
75impl Tensor {
76    /// Returns the [`ComponentDescriptor`] for [`Self::data`].
77    ///
78    /// The corresponding component is [`crate::components::TensorData`].
79    #[inline]
80    pub fn descriptor_data() -> ComponentDescriptor {
81        ComponentDescriptor {
82            archetype: Some("rerun.archetypes.Tensor".into()),
83            component: "Tensor:data".into(),
84            component_type: Some("rerun.components.TensorData".into()),
85        }
86    }
87
88    /// Returns the [`ComponentDescriptor`] for [`Self::value_range`].
89    ///
90    /// The corresponding component is [`crate::components::ValueRange`].
91    #[inline]
92    pub fn descriptor_value_range() -> ComponentDescriptor {
93        ComponentDescriptor {
94            archetype: Some("rerun.archetypes.Tensor".into()),
95            component: "Tensor:value_range".into(),
96            component_type: Some("rerun.components.ValueRange".into()),
97        }
98    }
99}
100
101static REQUIRED_COMPONENTS: std::sync::LazyLock<[ComponentDescriptor; 1usize]> =
102    std::sync::LazyLock::new(|| [Tensor::descriptor_data()]);
103
104static RECOMMENDED_COMPONENTS: std::sync::LazyLock<[ComponentDescriptor; 0usize]> =
105    std::sync::LazyLock::new(|| []);
106
107static OPTIONAL_COMPONENTS: std::sync::LazyLock<[ComponentDescriptor; 1usize]> =
108    std::sync::LazyLock::new(|| [Tensor::descriptor_value_range()]);
109
110static ALL_COMPONENTS: std::sync::LazyLock<[ComponentDescriptor; 2usize]> =
111    std::sync::LazyLock::new(|| [Tensor::descriptor_data(), Tensor::descriptor_value_range()]);
112
113impl Tensor {
114    /// The total number of components in the archetype: 1 required, 0 recommended, 1 optional
115    pub const NUM_COMPONENTS: usize = 2usize;
116}
117
118impl ::re_types_core::Archetype for Tensor {
119    #[inline]
120    fn name() -> ::re_types_core::ArchetypeName {
121        "rerun.archetypes.Tensor".into()
122    }
123
124    #[inline]
125    fn display_name() -> &'static str {
126        "Tensor"
127    }
128
129    #[inline]
130    fn required_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
131        REQUIRED_COMPONENTS.as_slice().into()
132    }
133
134    #[inline]
135    fn recommended_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
136        RECOMMENDED_COMPONENTS.as_slice().into()
137    }
138
139    #[inline]
140    fn optional_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
141        OPTIONAL_COMPONENTS.as_slice().into()
142    }
143
144    #[inline]
145    fn all_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
146        ALL_COMPONENTS.as_slice().into()
147    }
148
149    #[inline]
150    fn from_arrow_components(
151        arrow_data: impl IntoIterator<Item = (ComponentDescriptor, arrow::array::ArrayRef)>,
152    ) -> DeserializationResult<Self> {
153        re_tracing::profile_function!();
154        use ::re_types_core::{Loggable as _, ResultExt as _};
155        let arrays_by_descr: ::nohash_hasher::IntMap<_, _> = arrow_data.into_iter().collect();
156        let data = arrays_by_descr
157            .get(&Self::descriptor_data())
158            .map(|array| SerializedComponentBatch::new(array.clone(), Self::descriptor_data()));
159        let value_range = arrays_by_descr
160            .get(&Self::descriptor_value_range())
161            .map(|array| {
162                SerializedComponentBatch::new(array.clone(), Self::descriptor_value_range())
163            });
164        Ok(Self { data, value_range })
165    }
166}
167
168impl ::re_types_core::AsComponents for Tensor {
169    #[inline]
170    fn as_serialized_batches(&self) -> Vec<SerializedComponentBatch> {
171        use ::re_types_core::Archetype as _;
172        [self.data.clone(), self.value_range.clone()]
173            .into_iter()
174            .flatten()
175            .collect()
176    }
177}
178
179impl ::re_types_core::ArchetypeReflectionMarker for Tensor {}
180
181impl Tensor {
182    /// Create a new `Tensor`.
183    #[inline]
184    pub fn new(data: impl Into<crate::components::TensorData>) -> Self {
185        Self {
186            data: try_serialize_field(Self::descriptor_data(), [data]),
187            value_range: None,
188        }
189    }
190
191    /// Update only some specific fields of a `Tensor`.
192    #[inline]
193    pub fn update_fields() -> Self {
194        Self::default()
195    }
196
197    /// Clear all the fields of a `Tensor`.
198    #[inline]
199    pub fn clear_fields() -> Self {
200        use ::re_types_core::Loggable as _;
201        Self {
202            data: Some(SerializedComponentBatch::new(
203                crate::components::TensorData::arrow_empty(),
204                Self::descriptor_data(),
205            )),
206            value_range: Some(SerializedComponentBatch::new(
207                crate::components::ValueRange::arrow_empty(),
208                Self::descriptor_value_range(),
209            )),
210        }
211    }
212
213    /// Partitions the component data into multiple sub-batches.
214    ///
215    /// Specifically, this transforms the existing [`SerializedComponentBatch`]es data into [`SerializedComponentColumn`]s
216    /// instead, via [`SerializedComponentBatch::partitioned`].
217    ///
218    /// This makes it possible to use `RecordingStream::send_columns` to send columnar data directly into Rerun.
219    ///
220    /// The specified `lengths` must sum to the total length of the component batch.
221    ///
222    /// [`SerializedComponentColumn`]: [::re_types_core::SerializedComponentColumn]
223    #[inline]
224    pub fn columns<I>(
225        self,
226        _lengths: I,
227    ) -> SerializationResult<impl Iterator<Item = ::re_types_core::SerializedComponentColumn>>
228    where
229        I: IntoIterator<Item = usize> + Clone,
230    {
231        let columns = [
232            self.data
233                .map(|data| data.partitioned(_lengths.clone()))
234                .transpose()?,
235            self.value_range
236                .map(|value_range| value_range.partitioned(_lengths.clone()))
237                .transpose()?,
238        ];
239        Ok(columns.into_iter().flatten())
240    }
241
242    /// Helper to partition the component data into unit-length sub-batches.
243    ///
244    /// This is semantically similar to calling [`Self::columns`] with `std::iter::take(1).repeat(n)`,
245    /// where `n` is automatically guessed.
246    #[inline]
247    pub fn columns_of_unit_batches(
248        self,
249    ) -> SerializationResult<impl Iterator<Item = ::re_types_core::SerializedComponentColumn>> {
250        let len_data = self.data.as_ref().map(|b| b.array.len());
251        let len_value_range = self.value_range.as_ref().map(|b| b.array.len());
252        let len = None.or(len_data).or(len_value_range).unwrap_or(0);
253        self.columns(std::iter::repeat_n(1, len))
254    }
255
256    /// The tensor data
257    #[inline]
258    pub fn with_data(mut self, data: impl Into<crate::components::TensorData>) -> Self {
259        self.data = try_serialize_field(Self::descriptor_data(), [data]);
260        self
261    }
262
263    /// This method makes it possible to pack multiple [`crate::components::TensorData`] in a single component batch.
264    ///
265    /// This only makes sense when used in conjunction with [`Self::columns`]. [`Self::with_data`] should
266    /// be used when logging a single row's worth of data.
267    #[inline]
268    pub fn with_many_data(
269        mut self,
270        data: impl IntoIterator<Item = impl Into<crate::components::TensorData>>,
271    ) -> Self {
272        self.data = try_serialize_field(Self::descriptor_data(), data);
273        self
274    }
275
276    /// The expected range of values.
277    ///
278    /// This is typically the expected range of valid values.
279    /// Everything outside of the range is clamped to the range for the purpose of colormpaping.
280    /// Any colormap applied for display, will map this range.
281    ///
282    /// If not specified, the range will be automatically estimated from the data.
283    /// Note that the Viewer may try to guess a wider range than the minimum/maximum of values
284    /// in the contents of the tensor.
285    /// E.g. if all values are positive, some bigger than 1.0 and all smaller than 255.0,
286    /// the Viewer will guess that the data likely came from an 8bit image, thus assuming a range of 0-255.
287    #[inline]
288    pub fn with_value_range(
289        mut self,
290        value_range: impl Into<crate::components::ValueRange>,
291    ) -> Self {
292        self.value_range = try_serialize_field(Self::descriptor_value_range(), [value_range]);
293        self
294    }
295
296    /// This method makes it possible to pack multiple [`crate::components::ValueRange`] in a single component batch.
297    ///
298    /// This only makes sense when used in conjunction with [`Self::columns`]. [`Self::with_value_range`] should
299    /// be used when logging a single row's worth of data.
300    #[inline]
301    pub fn with_many_value_range(
302        mut self,
303        value_range: impl IntoIterator<Item = impl Into<crate::components::ValueRange>>,
304    ) -> Self {
305        self.value_range = try_serialize_field(Self::descriptor_value_range(), value_range);
306        self
307    }
308}
309
310impl ::re_byte_size::SizeBytes for Tensor {
311    #[inline]
312    fn heap_size_bytes(&self) -> u64 {
313        self.data.heap_size_bytes() + self.value_range.heap_size_bytes()
314    }
315}