1515import logging
1616import pathlib
1717from typing import Callable
18+ from typing import Mapping
1819from typing import Optional
1920from typing import Sequence
2021from typing import Union
2122
2223import dask .array as da
2324import numpy as np
25+ import zarr .errors
2426
2527logger = logging .getLogger (__name__ )
2628
@@ -33,6 +35,7 @@ def build_pyramid(
3335 coarsening_xy : int = 2 ,
3436 chunksize : Optional [Sequence [int ]] = None ,
3537 aggregation_function : Optional [Callable ] = None ,
38+ open_array_kwargs : Optional [Mapping ] = None ,
3639) -> None :
3740
3841 """
@@ -48,6 +51,7 @@ def build_pyramid(
4851 coarsening_xy: Linear coarsening factor between subsequent levels.
4952 chunksize: Shape of a single chunk.
5053 aggregation_function: Function to be used when downsampling.
54+ open_array_kwargs: Additional arguments for zarr.open.
5155 """
5256
5357 # Clean up zarrurl
@@ -100,10 +104,33 @@ def build_pyramid(
100104 f"{ str (newlevel_rechunked )} "
101105 )
102106
107+ if open_array_kwargs is None :
108+ open_array_kwargs = {}
109+
110+ # If overwrite is false, check that the array doesn't exist yet
111+ if not overwrite :
112+ try :
113+ zarr .open (f"{ zarrurl } /{ ind_level } " , mode = "r" )
114+ raise ValueError (
115+ f"While building the pyramids, pyramid level { ind_level } "
116+ "already existed, but `build_pyramid` was called with "
117+ f"{ overwrite = } ."
118+ )
119+ except zarr .errors .PathNotFoundError :
120+ pass
121+
122+ zarrarr = zarr .open (
123+ f"{ zarrurl } /{ ind_level } " ,
124+ shape = newlevel_rechunked .shape ,
125+ chunks = newlevel_rechunked .chunksize ,
126+ dtype = newlevel_rechunked .dtype ,
127+ mode = "w" ,
128+ ** open_array_kwargs ,
129+ )
130+
103131 # Write zarr and store output (useful to construct next level)
104132 previous_level = newlevel_rechunked .to_zarr (
105- zarrurl ,
106- component = f"{ ind_level } " ,
133+ zarrarr ,
107134 overwrite = overwrite ,
108135 compute = True ,
109136 return_stored = True ,
0 commit comments