Debian Codegraph @

docs/source/advanced.rst

raw ◀ ▶
1 Debian patch touch this file
1 Advanced Topics
2 ===============
3
4 Using Dask
5 ----------
6
7 Scanning and combining datasets can be computationally intensive and may
8 require a lot of bandwidth for some data formats. Where the target data
9 contains many input files, it makes sense to parallelise the job with
10 dask and maybe distribute the workload on a cluster to get additional
11 CPUs and network performance.
12
13 Simple parallel
14 ~~~~~~~~~~~~~~~
15
16 The simplest case is for processing many individual files in parallel.
17 Let's say you have a list of input files; you will need to encapsulate
18 the processing on each in a single function. In this mode, it is typical
19 to save the single-file outputs to files, although returning them is OK
20 too (especially if you mean to combine them immediately).
21
22 Here is an example for HDF5 files. The caller should make sure the
23 storage options and any parameters needed for the transformer are in place.
24
25 .. code-block:: python
26
27 import ujson, fsspec, dask
28
29 def process(url, outputfile, storage_options_in={}, storage_options_out={}):
30 transformer = kerchunk.hdf.SingleHdf5ToZarr(url, **storage_options_in)
31 refs = transformer.translate()
32 with fsspec.open(outputfile, mode="wt", **storage_options_out) as f:
33 ujson.dump(refs, f)
34
35 tasks = [dask.delayed(process)(u, o)
36 for u, o in zip(infilenames, outfilenames)]
37 dask.compute(tasks)
38
39 Tree reduction
40 ~~~~~~~~~~~~~~
41
42 In some cases, the combine process can itself be slow or memory hungry.
43 In such cases, it is useful to combine the single-file reference sets in
44 batches (which reduce a lot of redundancy between them) and then
45 combine the results of the batches. This technique is known as tree
46 reduction. An example of doing this by hand can be seen `here`_.
47
48 .. _here: https://gist.github.com/peterm790/5f901453ed7ac75ac28ed21a7138dcf8
49
50 We also provide :func:`kerchunk.combine.auto_dask` as a convenience. This
51 function is a one-stop call to process the individual inputs, combine
52 them in batches, and then combine the results of those batches into a
53 final combined references set.
54
55 The ``auto_dask`` function takes a number of dicts as arguments, and users
56 should consult the docstrings of the specific class which decodes the
57 input files, and also of :class:`kerchunk.combine.MultiZarrToZarr`. Note that
58 any "preprocessing" for ``MultiZarrToZarr`` will be performed *before* the
59 batch stage, and any "postprocessing" only *after* the final combine.
60
61 Archive Files
62 -------------
63
64 It is often convenient to distribute datasets by wrapping multiple files
65 into an archive, ZIP or TAR. If those files are of formats supported by
66 ``kerchunk``, they can be directly scanned with something like
67
68 .. code-block:: python
69
70 transformer = kerchunk.netCDF3.NetCDF3ToZarr(
71 "tar://myfile.nc::file://archive.tar",
72 inline_threshold=0
73 )
74 out = transformer.translate()
75
76
77 where "myfile.nc" is a member file of the local archive.
78
79 .. note::
80
81 We have turned off inlining here (it can be done
82 later with :func:`kerchunk.utils.do_inline`; support for this
83 will come later.
84
85 At this point, the
86 generated references will contain URLs "tar://myfile.nc::file://archive.tar",
87 which are problematic for loading, so we can transform them to point to
88 ranges in the original tar file instead, and then transform back to
89 nominal form, ready to use. We may automate these steps in the future.
90
91 .. code-block:: python
92
93 out2 = kerchunk.utils.dereference_archives(out)
94 # optional out2 = kerchunk.utils.do_inline(out2, 100)
95 final = kerchunk.utils.consolidate(out2)
96
97 Now the references are all "file://archive.tar", and the reference set
98 can be used directly or in combining.
99
100 .. warning::
101
102 For ZIP archives, only uncompressed members can be accessed this way
103
104 Parquet Storage
105 ---------------
106
107 JSON is very convenient as a storage format for references, because it is
108 simple, human-readable and ubiquitously supported. However, it is not the most
109 efficient in terms of storage size of parsing speed. For python, in particular,
110 it comes with the added downside of repeated strings becoming separate python
111 string instances, greatly inflating memory footprint at load time.
112
113 To overcome these problems, and in particular keep down the memory use for the
114 end-user of kerchunked data, we can convert references to be stored in parquet,
115 and use them with ``fsspec.implementations.reference.ReferenceFileSystem``,
116 an alternative new implementation designed to work only with parquet input.
117
118 The principle benefits of the parquet path are:
119
120 - much more compact storage, typically 2x smaller than compressed JSON or 10x
121 smaller than uncompressed
122
123 - correspondingly faster instantiation of a filesystem, since much of that time
124 is taken by loading in the bytes of the references
125
126 - smaller in-memory size (e.g., a python int requires 28 bytes, but an int in
127 an array needs 4 or 8.
128
129 - optional lazy loading, by partitioning the references into files by key; only
130 the variables you actually access need to have their references loaded
131
132 - optional dictionary encoding of URLs in the case that there are may repeated
133 URLs (many references per target file). In this format, each unique URL is only
134 stored in memory once.
135
136 The only access point to the new parquet storage is
137 :func:`kerchunk.df.refs_to_dataframe`, which transforms an existing kerchunk
138 reference set (in memory as dicts or in a JSON file) to parquet. Careful reading
139 of the docstring is recommended, to understand the options. More options may
140 be added.
141
142 .. note::
143
144 For now, :class:`kerchunk.combine.MultiZarrToZarr` only operates on JSON/dict
145 input. Therefore, ``refs_to_dataframe`` can only be used on the final output
146 reference set. For a very large merge of many/large inputs, this may mean
147 that the combine step requires a lot of memory, as will converting the
148 output to parquet. However, the end-user should be able to access data via
149 these references with much smaller memory requirements.
150
151 A concrete workflow may be something like the following. Note that
152 :func:`kerchunk.combine.auto_dask` can execute the first three stages in
153 one go and may be faster, if you have a Dask cluster available.
154
155 .. code-block:: python
156
157 from kerchunk import hdf, combine, df
158 import fsspec.implementations.reference
159 from fsspec.implementations.reference import LazyReferenceMapper
160 from tempfile import TemporaryDirectory
161
162 import xarray as xr
163
164 files = fsspec.open(location_of_data)
165
166 # Create LazyReferenceMapper to pass to MultiZarrToZarr
167 fs = fsspec.filesystem("file")
168
169 os.makedirs("combined.parq")
170 out = LazyReferenceMapper.create(record_size=1000, root="combined.parq", fs=fs)
171
172 # Create references from input files
173 single_ref_sets = [hdf.SingleHdf5ToZarr(_).translate() for _ in files]
174
175 out_dict = MultiZarrToZarr(
176 single_ref_sets,
177 remote_protocol="s3",
178 concat_dims=["time"],
179 remote_options={"anon": True},
180 out=out
181 ).translate()
182
183 out.flush()
184
185 df.refs_to_dataframe(out_dict, "combined.parq")
186
187 fs = fsspec.implementations.reference.ReferenceFileSystem(
188 "combined.parq", remote_protocol="s3", target_protocol="file", lazy=True)
189 ds = xr.open_dataset(
190 fs.get_mapper(), engine="zarr",
191 backend_kwargs={"consolidated": False}
192 )
193
194
195 At this point, xarray has loaded the metadata and coordinates only, so the
196 main reference files corresponding to the data variables have not been touched.
197 Even for a very large reference set, the memory use at this point should be <500MB.
198
199 As you access the variables of ``ds``, they will be loaded on demand and cached.
200 If using ``dask``, workers will also only load those references they need.