Struct RectangularChunkGrid

Source
pub struct RectangularChunkGrid { /* private fields */ }
Expand description

A rectangular chunk grid.

Implementations§

Source§

impl RectangularChunkGrid

Source

pub fn new(chunk_shapes: &[RectangularChunkGridDimensionConfiguration]) -> Self

Create a new rectangular chunk grid with chunk shapes chunk_shapes.

Examples found in repository?
examples/rectangular_array_write_read.rs (lines 62-65)
8fn rectangular_array_write_read() -> Result<(), Box<dyn std::error::Error>> {
9    use rayon::prelude::{IntoParallelIterator, ParallelIterator};
10    use zarrs::array::ChunkGrid;
11    use zarrs::{
12        array::{chunk_grid::RectangularChunkGrid, codec, FillValue},
13        node::Node,
14    };
15    use zarrs::{
16        array::{DataType, ZARR_NAN_F32},
17        array_subset::ArraySubset,
18        storage::store,
19    };
20
21    // Create a store
22    // let path = tempfile::TempDir::new()?;
23    // let mut store: ReadableWritableListableStorage =
24    //     Arc::new(zarrs::filesystem::FilesystemStore::new(path.path())?);
25    let mut store: ReadableWritableListableStorage = Arc::new(store::MemoryStore::new());
26    if let Some(arg1) = std::env::args().collect::<Vec<_>>().get(1) {
27        if arg1 == "--usage-log" {
28            let log_writer = Arc::new(std::sync::Mutex::new(
29                // std::io::BufWriter::new(
30                std::io::stdout(),
31                //    )
32            ));
33            store = Arc::new(UsageLogStorageAdapter::new(store, log_writer, || {
34                chrono::Utc::now().format("[%T%.3f] ").to_string()
35            }));
36        }
37    }
38
39    // Create the root group
40    zarrs::group::GroupBuilder::new()
41        .build(store.clone(), "/")?
42        .store_metadata()?;
43
44    // Create a group with attributes
45    let group_path = "/group";
46    let mut group = zarrs::group::GroupBuilder::new().build(store.clone(), group_path)?;
47    group
48        .attributes_mut()
49        .insert("foo".into(), serde_json::Value::String("bar".into()));
50    group.store_metadata()?;
51
52    println!(
53        "The group metadata is:\n{}\n",
54        group.metadata().to_string_pretty()
55    );
56
57    // Create an array
58    let array_path = "/group/array";
59    let array = zarrs::array::ArrayBuilder::new(
60        vec![8, 8], // array shape
61        DataType::Float32,
62        ChunkGrid::new(RectangularChunkGrid::new(&[
63            [1, 2, 3, 2].try_into()?,
64            4.try_into()?,
65        ])),
66        FillValue::from(ZARR_NAN_F32),
67    )
68    .bytes_to_bytes_codecs(vec![
69        #[cfg(feature = "gzip")]
70        Arc::new(codec::GzipCodec::new(5)?),
71    ])
72    .dimension_names(["y", "x"].into())
73    // .storage_transformers(vec![].into())
74    .build(store.clone(), array_path)?;
75
76    // Write array metadata to store
77    array.store_metadata()?;
78
79    // Write some chunks (in parallel)
80    (0..4).into_par_iter().try_for_each(|i| {
81        let chunk_grid = array.chunk_grid();
82        let chunk_indices = vec![i, 0];
83        if let Some(chunk_shape) = chunk_grid.chunk_shape(&chunk_indices, array.shape())? {
84            let chunk_array = ndarray::ArrayD::<f32>::from_elem(
85                chunk_shape
86                    .iter()
87                    .map(|u| u.get() as usize)
88                    .collect::<Vec<_>>(),
89                i as f32,
90            );
91            array.store_chunk_ndarray(&chunk_indices, chunk_array)
92        } else {
93            Err(zarrs::array::ArrayError::InvalidChunkGridIndicesError(
94                chunk_indices.to_vec(),
95            ))
96        }
97    })?;
98
99    println!(
100        "The array metadata is:\n{}\n",
101        array.metadata().to_string_pretty()
102    );
103
104    // Write a subset spanning multiple chunks, including updating chunks already written
105    array.store_array_subset_ndarray(
106        &[3, 3], // start
107        ndarray::ArrayD::<f32>::from_shape_vec(
108            vec![3, 3],
109            vec![0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9],
110        )?,
111    )?;
112
113    // Store elements directly, in this case set the 7th column to 123.0
114    array.store_array_subset_elements::<f32>(
115        &ArraySubset::new_with_ranges(&[0..8, 6..7]),
116        &[123.0; 8],
117    )?;
118
119    // Store elements directly in a chunk, in this case set the last row of the bottom right chunk
120    array.store_chunk_subset_elements::<f32>(
121        // chunk indices
122        &[3, 1],
123        // subset within chunk
124        &ArraySubset::new_with_ranges(&[1..2, 0..4]),
125        &[-4.0; 4],
126    )?;
127
128    // Read the whole array
129    let data_all = array.retrieve_array_subset_ndarray::<f32>(&array.subset_all())?;
130    println!("The whole array is:\n{data_all}\n");
131
132    // Read a chunk back from the store
133    let chunk_indices = vec![1, 0];
134    let data_chunk = array.retrieve_chunk_ndarray::<f32>(&chunk_indices)?;
135    println!("Chunk [1,0] is:\n{data_chunk}\n");
136
137    // Read the central 4x2 subset of the array
138    let subset_4x2 = ArraySubset::new_with_ranges(&[2..6, 3..5]); // the center 4x2 region
139    let data_4x2 = array.retrieve_array_subset_ndarray::<f32>(&subset_4x2)?;
140    println!("The middle 4x2 subset is:\n{data_4x2}\n");
141
142    // Show the hierarchy
143    let node = Node::open(&store, "/").unwrap();
144    let tree = node.hierarchy_tree();
145    println!("The Zarr hierarchy tree is:\n{tree}");
146
147    Ok(())
148}

Trait Implementations§

Source§

impl ChunkGridTraits for RectangularChunkGrid

Source§

unsafe fn chunk_element_indices_unchecked( &self, array_indices: &[u64], array_shape: &[u64], ) -> Option<ArrayIndices>

§Safety

The length of array_indices and array_shape must match the dimensionality of the chunk grid.

Source§

fn create_metadata(&self) -> MetadataV3

Create metadata.
Source§

fn dimensionality(&self) -> usize

The dimensionality of the grid.
Source§

unsafe fn grid_shape_unchecked(&self, array_shape: &[u64]) -> Option<ArrayShape>

Source§

unsafe fn chunk_shape_unchecked( &self, chunk_indices: &[u64], _array_shape: &[u64], ) -> Option<ChunkShape>

Source§

unsafe fn chunk_shape_u64_unchecked( &self, chunk_indices: &[u64], _array_shape: &[u64], ) -> Option<ArrayShape>

Source§

unsafe fn chunk_origin_unchecked( &self, chunk_indices: &[u64], _array_shape: &[u64], ) -> Option<ArrayIndices>

Source§

unsafe fn chunk_indices_unchecked( &self, array_indices: &[u64], _array_shape: &[u64], ) -> Option<ArrayIndices>

Source§

fn array_indices_inbounds( &self, array_indices: &[u64], array_shape: &[u64], ) -> bool

Check if array indices are in-bounds. Read more
Source§

fn grid_shape( &self, array_shape: &[u64], ) -> Result<Option<ArrayShape>, IncompatibleDimensionalityError>

The grid shape (i.e. number of chunks). Read more
Source§

fn chunk_shape( &self, chunk_indices: &[u64], array_shape: &[u64], ) -> Result<Option<ChunkShape>, IncompatibleDimensionalityError>

The shape of the chunk at chunk_indices. Read more
Source§

fn chunk_shape_u64( &self, chunk_indices: &[u64], array_shape: &[u64], ) -> Result<Option<ArrayShape>, IncompatibleDimensionalityError>

The shape of the chunk at chunk_indices as an ArrayShape (Vec<u64>). Read more
Source§

fn chunk_origin( &self, chunk_indices: &[u64], array_shape: &[u64], ) -> Result<Option<ArrayIndices>, IncompatibleDimensionalityError>

The origin of the chunk at chunk_indices. Read more
Source§

fn subset( &self, chunk_indices: &[u64], array_shape: &[u64], ) -> Result<Option<ArraySubset>, IncompatibleDimensionalityError>

Return the ArraySubset of the chunk at chunk_indices. Read more
Source§

fn chunks_subset( &self, chunks: &ArraySubset, array_shape: &[u64], ) -> Result<Option<ArraySubset>, IncompatibleDimensionalityError>

Return the ArraySubset of the chunks in chunks. Read more
Source§

fn chunk_indices( &self, array_indices: &[u64], array_shape: &[u64], ) -> Result<Option<ArrayIndices>, IncompatibleDimensionalityError>

The indices of a chunk which has the element at array_indices. Read more
Source§

fn chunk_element_indices( &self, array_indices: &[u64], array_shape: &[u64], ) -> Result<Option<ArrayIndices>, IncompatibleDimensionalityError>

The indices within the chunk of the element at array_indices. Read more
Source§

fn chunk_indices_inbounds( &self, chunk_indices: &[u64], array_shape: &[u64], ) -> bool

Check if chunk indices are in-bounds. Read more
Source§

unsafe fn subset_unchecked( &self, chunk_indices: &[u64], array_shape: &[u64], ) -> Option<ArraySubset>

Source§

fn chunks_in_array_subset( &self, array_subset: &ArraySubset, array_shape: &[u64], ) -> Result<Option<ArraySubset>, IncompatibleDimensionalityError>

Return an array subset indicating the chunks intersecting array_subset. Read more
Source§

impl Clone for RectangularChunkGrid

Source§

fn clone(&self) -> RectangularChunkGrid

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for RectangularChunkGrid

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.