cima-d3tools 3.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cima_d3tools-3.0.0.dist-info/METADATA +107 -0
- cima_d3tools-3.0.0.dist-info/RECORD +73 -0
- cima_d3tools-3.0.0.dist-info/WHEEL +5 -0
- cima_d3tools-3.0.0.dist-info/entry_points.txt +2 -0
- cima_d3tools-3.0.0.dist-info/licenses/LICENSE +287 -0
- cima_d3tools-3.0.0.dist-info/top_level.txt +1 -0
- d3tools/__init__.py +3 -0
- d3tools/cases/__init__.py +8 -0
- d3tools/cases/case.py +95 -0
- d3tools/cases/case_manager.py +323 -0
- d3tools/cases/utils.py +189 -0
- d3tools/cli.py +60 -0
- d3tools/config/__init__.py +34 -0
- d3tools/config/options.py +186 -0
- d3tools/config/parsers.py +251 -0
- d3tools/config/parsing_pipeline.py +342 -0
- d3tools/config/utils.py +90 -0
- d3tools/config/workflow_definition.py +323 -0
- d3tools/config/workflow_section.py +313 -0
- d3tools/data/__init__.py +40 -0
- d3tools/data/data_catalogue.py +870 -0
- d3tools/data/datasets/__init__.py +12 -0
- d3tools/data/datasets/dataset.py +902 -0
- d3tools/data/datasets/local_dataset.py +92 -0
- d3tools/data/datasets/memory_dataset.py +83 -0
- d3tools/data/datasets/remote_dataset.py +598 -0
- d3tools/data/format_mixins/__init__.py +23 -0
- d3tools/data/format_mixins/base.py +205 -0
- d3tools/data/format_mixins/file_mixin.py +81 -0
- d3tools/data/format_mixins/plaintext_mixin.py +89 -0
- d3tools/data/format_mixins/raster_mixin.py +498 -0
- d3tools/data/format_mixins/structuredtext_mixin.py +186 -0
- d3tools/data/format_mixins/table_mixin.py +109 -0
- d3tools/data/format_mixins/vector_mixin.py +213 -0
- d3tools/data/io_utils.py +207 -0
- d3tools/data/io_utils_raster.py +310 -0
- d3tools/errors/__init__.py +16 -0
- d3tools/errors/gdal_import.py +37 -0
- d3tools/errors/template_errors.py +165 -0
- d3tools/errors/workflow_import.py +36 -0
- d3tools/exit/__init__.py +9 -0
- d3tools/exit/exit_handler.py +117 -0
- d3tools/logging/__init__.py +12 -0
- d3tools/logging/dataset_log_manager.py +233 -0
- d3tools/logging/utils.py +139 -0
- d3tools/logging/workflow_log_manager.py +435 -0
- d3tools/notification/__init__.py +9 -0
- d3tools/notification/email_notification.py +160 -0
- d3tools/parse/__init__.py +14 -0
- d3tools/parse/config_resolution.py +105 -0
- d3tools/parse/key_parser.py +481 -0
- d3tools/parse/parse_utils.py +266 -0
- d3tools/parse/string_rendering.py +165 -0
- d3tools/spatial/__init__.py +11 -0
- d3tools/spatial/bounding_box.py +185 -0
- d3tools/spatial/space_utils.py +118 -0
- d3tools/spatial/template_manager.py +440 -0
- d3tools/thumbnails/__init__.py +12 -0
- d3tools/thumbnails/colors.py +167 -0
- d3tools/thumbnails/dataset_thumbnail_manager.py +121 -0
- d3tools/thumbnails/thumbnail.py +555 -0
- d3tools/thumbnails/thumbnail_collection.py +152 -0
- d3tools/timestepping/__init__.py +41 -0
- d3tools/timestepping/time_parsing.py +76 -0
- d3tools/timestepping/time_utils.py +324 -0
- d3tools/timestepping/timeperiods/__init__.py +20 -0
- d3tools/timestepping/timeperiods/fixed_doy_timestep.py +245 -0
- d3tools/timestepping/timeperiods/fixed_len_timestep.py +284 -0
- d3tools/timestepping/timeperiods/fixed_num_timestep.py +349 -0
- d3tools/timestepping/timeperiods/timeperiod.py +224 -0
- d3tools/timestepping/timeperiods/timerange.py +288 -0
- d3tools/timestepping/timeperiods/timestep.py +292 -0
- d3tools/timestepping/timewindow.py +372 -0
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
"""Manage combinations of cases arranged in named layers."""
|
|
2
|
+
|
|
3
|
+
from typing import Optional, Iterator
|
|
4
|
+
import copy
|
|
5
|
+
|
|
6
|
+
from .case import Case, get_cases
|
|
7
|
+
from .utils import rand_str, split_id, get_parents
|
|
8
|
+
|
|
9
|
+
class CaseManager():
|
|
10
|
+
"""Build and traverse layers of cases generated from option mappings.
|
|
11
|
+
|
|
12
|
+
A mapping-valued option is expanded into one case per mapping key, with the
|
|
13
|
+
key recorded as a tag and its value used as the option value. Other option
|
|
14
|
+
values are fixed across that expansion. Each layer is stored as a mapping
|
|
15
|
+
from generated case IDs to :class:`Case` objects.
|
|
16
|
+
|
|
17
|
+
Case IDs are assembled from short random tokens assigned to tag/value
|
|
18
|
+
pairs. The manager keeps those assignments in ``id_map`` so a pair reuses
|
|
19
|
+
its token within this manager.
|
|
20
|
+
|
|
21
|
+
Attributes:
|
|
22
|
+
id_map: Mapping from ``"tag=value"`` strings to generated ID tokens.
|
|
23
|
+
options: Effective option mappings, one per layer.
|
|
24
|
+
tags: Tag names present in each layer.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
_id_len = 2
|
|
28
|
+
|
|
29
|
+
def __init__(self, options: dict|None = None, l0_name: str = 'input'):
|
|
30
|
+
"""Create the root layer from ``options``.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
options: Options for the root layer. Mapping values are expanded
|
|
34
|
+
as case dimensions; other values are fixed options. ``None``
|
|
35
|
+
is treated as an empty mapping.
|
|
36
|
+
l0_name: Name assigned to the root layer.
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
None: The constructor has no return value.
|
|
40
|
+
|
|
41
|
+
Side Effects:
|
|
42
|
+
Initializes the root layer and generates its case IDs.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
if options is None: options = {}
|
|
46
|
+
self.id_map = {}
|
|
47
|
+
|
|
48
|
+
cases = get_cases(options)
|
|
49
|
+
ids = self.get_ids(cases)
|
|
50
|
+
|
|
51
|
+
self._cases = [dict(zip(ids, cases))]
|
|
52
|
+
self.options = [options.copy()]
|
|
53
|
+
self.tags = [list(cases[0].tags.keys())]
|
|
54
|
+
self._lyrmap = {l0_name: 0}
|
|
55
|
+
|
|
56
|
+
self._parsed_options = {k:[v for v in options[k].keys()] for k in options.keys() if isinstance(options[k], dict)}
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def layers(self):
|
|
60
|
+
"""Return layer names in insertion order.
|
|
61
|
+
|
|
62
|
+
Returns:
|
|
63
|
+
list[str]: Layer names in insertion order.
|
|
64
|
+
"""
|
|
65
|
+
return list(self._lyrmap.keys())
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def nlayers(self):
|
|
69
|
+
"""Return the number of layers currently stored.
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
int: Number of stored layers.
|
|
73
|
+
"""
|
|
74
|
+
return len(self.layers)
|
|
75
|
+
|
|
76
|
+
def __iter__(self) -> Iterator[Case]:
|
|
77
|
+
"""Iterate over the stored layer mappings.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
Iterator[dict[str, Case]]: An iterator over dictionaries mapping case IDs to ``Case``
|
|
81
|
+
instances, one dictionary per layer. This is the runtime behavior
|
|
82
|
+
even though the return annotation names ``Case`` as the item type.
|
|
83
|
+
"""
|
|
84
|
+
return iter(self._cases)
|
|
85
|
+
|
|
86
|
+
def __getitem__(self, index: int|str) -> Case:
|
|
87
|
+
"""Get a layer by its integer position or its name.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
index: Integer layer position (including normal negative list
|
|
91
|
+
indices), or a layer name.
|
|
92
|
+
|
|
93
|
+
Returns:
|
|
94
|
+
dict[str, Case]: The selected mapping of case IDs to ``Case`` instances.
|
|
95
|
+
|
|
96
|
+
Raises:
|
|
97
|
+
KeyError: If ``index`` is a string that is not a layer name.
|
|
98
|
+
IndexError: If an integer index is outside the stored layer list.
|
|
99
|
+
"""
|
|
100
|
+
if isinstance(index, str):
|
|
101
|
+
index = self._lyrmap[index]
|
|
102
|
+
return self._cases[index]
|
|
103
|
+
|
|
104
|
+
def get_ids(self, cases: list[Case]) -> list[str]:
|
|
105
|
+
"""Generate one ID per case using this manager's tag-token map.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
cases: Cases whose tags determine their ID components.
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
list[str]: IDs formed by concatenating the tokens for each case's tags in
|
|
112
|
+
tag iteration order. A tag/value pair reuses its token within this
|
|
113
|
+
manager; previously unused pairs receive a random two-character
|
|
114
|
+
token that is not already assigned to another pair.
|
|
115
|
+
|
|
116
|
+
Side Effects:
|
|
117
|
+
Adds tokens for previously unseen tag/value pairs to ``id_map``.
|
|
118
|
+
"""
|
|
119
|
+
ids = []
|
|
120
|
+
for case in cases:
|
|
121
|
+
id = ""
|
|
122
|
+
for key, value in case.tags.items():
|
|
123
|
+
id_map_key = "=".join([key, value])
|
|
124
|
+
if id_map_key in self.id_map:
|
|
125
|
+
id += self.id_map[id_map_key]
|
|
126
|
+
else:
|
|
127
|
+
new_id = rand_str(self._id_len, 0, skip=self.id_map.values())
|
|
128
|
+
self.id_map[id_map_key] = new_id
|
|
129
|
+
id += new_id
|
|
130
|
+
ids.append(id)
|
|
131
|
+
|
|
132
|
+
return ids
|
|
133
|
+
|
|
134
|
+
def add_layer(self, options: dict, name: str|None = None, merge: str|None = None):
|
|
135
|
+
"""Append a layer by combining new cases with the current final layer.
|
|
136
|
+
|
|
137
|
+
Mapping-valued options expand into new cases and fixed values are
|
|
138
|
+
applied to each child. A mapping dimension already parsed in an
|
|
139
|
+
earlier layer is ignored if any of its keys have already been parsed;
|
|
140
|
+
dimensions with no previously parsed keys are accepted. When ``merge``
|
|
141
|
+
names a dimension, cases in the previous layer are first combined
|
|
142
|
+
across that dimension, which is removed from the merged cases.
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
options: Options to add in this layer. Mapping values associate
|
|
146
|
+
tag values with runtime option values.
|
|
147
|
+
name: Name for the new layer. If omitted, a name of the form
|
|
148
|
+
``layerN`` is generated from the resulting layer count.
|
|
149
|
+
merge: Optional tag name whose previous-layer values are combined
|
|
150
|
+
before adding the new layer.
|
|
151
|
+
|
|
152
|
+
Returns:
|
|
153
|
+
None: The method has no return value.
|
|
154
|
+
|
|
155
|
+
Side Effects:
|
|
156
|
+
Appends a case mapping, effective options, and tag list to this
|
|
157
|
+
manager, registers the layer name, and may update ``id_map``.
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
new_options = {}
|
|
161
|
+
for k,v in options.items():
|
|
162
|
+
if k not in self._parsed_options:
|
|
163
|
+
new_options[k] = v
|
|
164
|
+
elif isinstance(options[k], dict) and not any([v in self._parsed_options[k] for v in options[k].keys()]):
|
|
165
|
+
new_options[k] = v
|
|
166
|
+
|
|
167
|
+
new_cases = get_cases(new_options)
|
|
168
|
+
new_ids = self.get_ids(new_cases)
|
|
169
|
+
|
|
170
|
+
these_cases = {}
|
|
171
|
+
prev_layer = self._cases[-1].copy()
|
|
172
|
+
|
|
173
|
+
if merge is not None:
|
|
174
|
+
merge_ids = [v for k,v in self.id_map.items() if k.split('=')[0] == merge]
|
|
175
|
+
groups = [{id.replace(mid, ''): id for id in prev_layer if mid in id} for mid in merge_ids]
|
|
176
|
+
for key in groups[0]:
|
|
177
|
+
prev_keys = [group.get(key) for group in groups]
|
|
178
|
+
case0 = copy.deepcopy(prev_layer[prev_keys[0]])
|
|
179
|
+
case0.options.pop(merge)
|
|
180
|
+
case0.tags.pop(merge)
|
|
181
|
+
casenew = Case(options = case0.options, tags = case0.tags)
|
|
182
|
+
newkey = '&'.join([f'[{k}]' for k in prev_keys])
|
|
183
|
+
prev_layer[newkey] = casenew
|
|
184
|
+
for key in prev_keys: prev_layer.pop(key)
|
|
185
|
+
|
|
186
|
+
for id, case in prev_layer.items():
|
|
187
|
+
_new_case = case # this line is only here beacause otherwise line 99 doesn't work when an empty case set is added
|
|
188
|
+
for new_id, new_case in zip(new_ids, new_cases):
|
|
189
|
+
_new_case = new_case + case
|
|
190
|
+
_new_id = '/'.join([id, new_id])
|
|
191
|
+
these_cases[_new_id] = _new_case
|
|
192
|
+
|
|
193
|
+
self._cases.append(these_cases)
|
|
194
|
+
self.options.append(new_options.copy() | self.options[-1])
|
|
195
|
+
self.tags.append(list(_new_case.tags.keys()))
|
|
196
|
+
|
|
197
|
+
if name is None: name = 'layer' + str(self.nlayers)
|
|
198
|
+
self._lyrmap[name] = self.nlayers
|
|
199
|
+
newly_parsed = {k:[v for v in new_options[k].keys()] for k in new_options.keys() if isinstance(new_options[k], dict)}
|
|
200
|
+
for k in newly_parsed:
|
|
201
|
+
if k in self._parsed_options:
|
|
202
|
+
self._parsed_options[k].extend(newly_parsed[k])
|
|
203
|
+
else:
|
|
204
|
+
self._parsed_options[k] = newly_parsed[k]
|
|
205
|
+
|
|
206
|
+
def find_case(self, id: str, get_layer = False) -> Optional[Case|tuple[Case]]:
|
|
207
|
+
"""Find the first case with ``id`` by scanning layers in order.
|
|
208
|
+
|
|
209
|
+
Args:
|
|
210
|
+
id: Case ID to find.
|
|
211
|
+
get_layer (bool): If true, return the layer index together with the case.
|
|
212
|
+
|
|
213
|
+
Returns:
|
|
214
|
+
Case | tuple[Case, int] | None: The matching ``Case``, or ``(Case, layer_index)`` when
|
|
215
|
+
``get_layer`` is true. Returns ``None`` when no layer contains
|
|
216
|
+
the ID.
|
|
217
|
+
"""
|
|
218
|
+
for lyr_id, lyr_cases in enumerate(self._cases):
|
|
219
|
+
if id in lyr_cases:
|
|
220
|
+
case = lyr_cases[id]
|
|
221
|
+
return case if not get_layer else (case, lyr_id)
|
|
222
|
+
return None
|
|
223
|
+
|
|
224
|
+
def iterate_tree(self, depth = None, get_layer = True):
|
|
225
|
+
"""Yield cases from the root through the selected layer.
|
|
226
|
+
|
|
227
|
+
For each case in the selected layer, its parent cases are yielded
|
|
228
|
+
before it. Parent IDs are deduplicated within that case's traversal,
|
|
229
|
+
allowing converging branches to be represented without repeating a
|
|
230
|
+
shared ancestor for that terminal case.
|
|
231
|
+
|
|
232
|
+
Args:
|
|
233
|
+
depth (int | None): Layer index to traverse through, inclusive. Defaults to the
|
|
234
|
+
final layer. Normal list indexing applies to explicit values.
|
|
235
|
+
get_layer (bool): If true, yield ``(case, layer_index)`` pairs; otherwise
|
|
236
|
+
yield cases only.
|
|
237
|
+
|
|
238
|
+
Yields:
|
|
239
|
+
tuple[Case, int] | Case: Cases on the traversed paths, in
|
|
240
|
+
parent-before-child order.
|
|
241
|
+
"""
|
|
242
|
+
if depth is None: depth = self.nlayers-1
|
|
243
|
+
last_row = self._cases[depth]
|
|
244
|
+
|
|
245
|
+
seen_ids = []
|
|
246
|
+
seen_cases = []
|
|
247
|
+
|
|
248
|
+
for id, case in last_row.items():
|
|
249
|
+
parents = get_parents(id)
|
|
250
|
+
for parent in parents:
|
|
251
|
+
if parent not in seen_ids:
|
|
252
|
+
seen_ids.append(parent)
|
|
253
|
+
seen_cases.append(self.find_case(parent, get_layer = get_layer))
|
|
254
|
+
|
|
255
|
+
seen_ids.append(id)
|
|
256
|
+
seen_cases.append((case, depth))
|
|
257
|
+
|
|
258
|
+
yield from seen_cases
|
|
259
|
+
seen_cases = []
|
|
260
|
+
|
|
261
|
+
def get_subtree(self, start_id: str, depth: int = 999):
|
|
262
|
+
"""Return descendant layer mappings below a case.
|
|
263
|
+
|
|
264
|
+
Descendants are selected from later layers when their IDs start with
|
|
265
|
+
``start_id``. The starting case's own layer is excluded, and at most
|
|
266
|
+
``depth`` subsequent layers are returned.
|
|
267
|
+
|
|
268
|
+
Args:
|
|
269
|
+
start_id: ID of the case at which to start.
|
|
270
|
+
depth (int): Maximum number of layers below the starting case to include.
|
|
271
|
+
Defaults to 999.
|
|
272
|
+
|
|
273
|
+
Returns:
|
|
274
|
+
list[dict[str, Case]]: A list of dictionaries mapping descendant case IDs to cases, with
|
|
275
|
+
one dictionary per included layer. Returns an empty list when no
|
|
276
|
+
later layer is within the requested depth.
|
|
277
|
+
|
|
278
|
+
Raises:
|
|
279
|
+
ValueError: If ``start_id`` does not identify a stored case.
|
|
280
|
+
"""
|
|
281
|
+
start = self.find_case(start_id, get_layer=True)
|
|
282
|
+
if start is None:
|
|
283
|
+
raise ValueError(f"Unknown case ID: {start_id}")
|
|
284
|
+
_, start_layer = start
|
|
285
|
+
end_layer = min(start_layer + depth+1, self.nlayers)
|
|
286
|
+
|
|
287
|
+
subtree = []
|
|
288
|
+
for layer_index in range(start_layer+1, end_layer):
|
|
289
|
+
these_cases = {id: case for id, case in self._cases[layer_index].items() if id.startswith(start_id)}
|
|
290
|
+
subtree.append(these_cases)
|
|
291
|
+
|
|
292
|
+
return subtree
|
|
293
|
+
|
|
294
|
+
def iterate_subtree(self, start_id: str, depth: int = 999, get_layer = True):
|
|
295
|
+
"""Yield descendants of ``start_id`` up to ``depth`` layers below.
|
|
296
|
+
|
|
297
|
+
The traversal follows diverging branches and yields each child before
|
|
298
|
+
recursively visiting its descendants. It does not yield the starting
|
|
299
|
+
case.
|
|
300
|
+
|
|
301
|
+
Args:
|
|
302
|
+
start_id: ID of the case at which to start.
|
|
303
|
+
depth (int): Maximum number of descendant layers to visit. Defaults to
|
|
304
|
+
999.
|
|
305
|
+
get_layer (bool): If true, yield ``(case, layer_index)`` pairs; otherwise
|
|
306
|
+
yield cases only.
|
|
307
|
+
|
|
308
|
+
Yields:
|
|
309
|
+
tuple[Case, int] | Case: Descendant cases in depth-first order, optionally paired with
|
|
310
|
+
their layer indices.
|
|
311
|
+
|
|
312
|
+
Raises:
|
|
313
|
+
ValueError: If ``start_id`` does not identify a stored case.
|
|
314
|
+
"""
|
|
315
|
+
children = self.get_subtree(start_id, depth)
|
|
316
|
+
if len(children) == 0: return
|
|
317
|
+
for child in children[0]:
|
|
318
|
+
case, lyr = self.find_case(child, get_layer=True)
|
|
319
|
+
if get_layer:
|
|
320
|
+
yield case, lyr
|
|
321
|
+
else:
|
|
322
|
+
yield case
|
|
323
|
+
yield from self.iterate_subtree(child, depth - 1, get_layer=get_layer)
|
d3tools/cases/utils.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""Utility helpers for case expansion and case-ID traversal.
|
|
2
|
+
|
|
3
|
+
The helpers in this module support generating case permutations, decorating
|
|
4
|
+
functions to execute over multiple case tags, and resolving ancestor IDs for the
|
|
5
|
+
hierarchical case trees created by :class:`d3tools.cases.case_manager.CaseManager`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import copy
|
|
9
|
+
import itertools
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def withcases(func):
|
|
13
|
+
"""Decorate a function so it can be called once per case in a case list.
|
|
14
|
+
|
|
15
|
+
When the wrapped function receives a ``cases`` keyword containing a list of
|
|
16
|
+
case dictionaries, it executes the function once per case after merging each
|
|
17
|
+
case's ``tags`` mapping into the call arguments. If ``cases`` is missing or
|
|
18
|
+
``None``, the function is invoked normally.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
func: Callable to wrap.
|
|
22
|
+
|
|
23
|
+
Returns:
|
|
24
|
+
Callable: A wrapper that either runs ``func`` normally or expands it over
|
|
25
|
+
a sequence of case-tag dictionaries.
|
|
26
|
+
|
|
27
|
+
Example:
|
|
28
|
+
Generate output names for several variable/season cases while sharing
|
|
29
|
+
the year and file format across all runs::
|
|
30
|
+
|
|
31
|
+
>>> @withcases
|
|
32
|
+
... def output_name(variable, season, year, extension):
|
|
33
|
+
... return f"{variable}_{season}_{year}.{extension}"
|
|
34
|
+
>>> output_name(
|
|
35
|
+
... year=2024,
|
|
36
|
+
... extension='nc',
|
|
37
|
+
... cases=[
|
|
38
|
+
... {'tags': {'variable': 'rain', 'season': 'JJA'}},
|
|
39
|
+
... {'tags': {'variable': 'temperature', 'season': 'DJF'}},
|
|
40
|
+
... ],
|
|
41
|
+
... )
|
|
42
|
+
['rain_JJA_2024.nc', 'temperature_DJF_2024.nc']
|
|
43
|
+
"""
|
|
44
|
+
def wrapper(*args, **kwargs):
|
|
45
|
+
if 'cases' in kwargs:
|
|
46
|
+
cases = kwargs.pop('cases')
|
|
47
|
+
if cases is not None:
|
|
48
|
+
these_kwargs = copy.deepcopy(kwargs)
|
|
49
|
+
output = []
|
|
50
|
+
for case in cases:
|
|
51
|
+
these_kwargs.update(case['tags'])
|
|
52
|
+
output.append(func(*args, **these_kwargs))
|
|
53
|
+
return output
|
|
54
|
+
return func(*args, **kwargs)
|
|
55
|
+
return wrapper
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def permutate_options(options):
|
|
59
|
+
"""Expand a mapping of dictionary-valued options into all permutations.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
options: Mapping whose dictionary entries define case dimensions; all
|
|
63
|
+
non-dictionary entries remain fixed for every generated case.
|
|
64
|
+
|
|
65
|
+
Returns:
|
|
66
|
+
tuple[list[dict], list[dict]]: The first list contains concrete option
|
|
67
|
+
dictionaries for each generated case, and the second contains the tag
|
|
68
|
+
dictionaries that record the selected dimension values.
|
|
69
|
+
"""
|
|
70
|
+
# get the options that need to be permutated and the ones that are fixed
|
|
71
|
+
|
|
72
|
+
# dictionaries need to be permutated
|
|
73
|
+
to_permutate = {k: list(v.keys()) for k, v in options.items() if isinstance(v, dict)}
|
|
74
|
+
|
|
75
|
+
# and everything else is fixed
|
|
76
|
+
fixed_options = {k: v for k, v in options.items() if not isinstance(v, dict)}
|
|
77
|
+
|
|
78
|
+
values_to_permutate = [v for v in to_permutate.values()]
|
|
79
|
+
keys = list(to_permutate.keys())
|
|
80
|
+
|
|
81
|
+
permutations = [dict(zip(keys, p)) for p in itertools.product(*values_to_permutate)]
|
|
82
|
+
identifiers = copy.deepcopy(permutations)
|
|
83
|
+
for permutation in permutations:
|
|
84
|
+
for k in permutation:
|
|
85
|
+
permutation[k] = options[k][permutation[k]]
|
|
86
|
+
permutation.update(fixed_options)
|
|
87
|
+
|
|
88
|
+
return permutations, identifiers
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def rand_str(l=4, n=0, skip=None):
|
|
92
|
+
"""Generate one or more random uppercase/digit identifiers.
|
|
93
|
+
|
|
94
|
+
Args:
|
|
95
|
+
l: Length of each generated identifier.
|
|
96
|
+
n: Number of identifiers to generate. A value of 0 returns a single
|
|
97
|
+
string instead of a list.
|
|
98
|
+
skip: Collection of identifiers that must not be reused.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
str | list[str]: A single identifier when ``n`` is 0, otherwise a list of
|
|
102
|
+
generated identifiers. Values in ``skip`` are avoided when possible.
|
|
103
|
+
"""
|
|
104
|
+
import random
|
|
105
|
+
import string
|
|
106
|
+
|
|
107
|
+
lst = [''.join(random.choices(string.ascii_uppercase + string.digits, k=l)) for _ in range(max(n, 1))]
|
|
108
|
+
|
|
109
|
+
if skip is not None:
|
|
110
|
+
while any([l in skip for l in lst]):
|
|
111
|
+
for s in skip:
|
|
112
|
+
if s in lst:
|
|
113
|
+
lst.remove(s)
|
|
114
|
+
new = rand_str(l, n - len(lst))
|
|
115
|
+
lst = lst + [new] if isinstance(new, str) else lst + new
|
|
116
|
+
|
|
117
|
+
if n == 0:
|
|
118
|
+
return lst[0]
|
|
119
|
+
|
|
120
|
+
return lst
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def split_id(id, sep='/', bracket=('[', ']')):
|
|
124
|
+
"""Split a case ID on top-level separators while preserving grouped values.
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
id: The case ID to split.
|
|
128
|
+
sep: Separator to split on.
|
|
129
|
+
bracket: Opening and closing bracket characters that keep separator
|
|
130
|
+
characters inside grouped subexpressions from being treated as
|
|
131
|
+
top-level separators.
|
|
132
|
+
|
|
133
|
+
Returns:
|
|
134
|
+
list[str]: The ID split into its top-level segments.
|
|
135
|
+
"""
|
|
136
|
+
parts = []
|
|
137
|
+
bracket_level = 0
|
|
138
|
+
current_part = []
|
|
139
|
+
|
|
140
|
+
for char in id:
|
|
141
|
+
if char == bracket[0]:
|
|
142
|
+
bracket_level += 1
|
|
143
|
+
elif char == bracket[1]:
|
|
144
|
+
bracket_level -= 1
|
|
145
|
+
elif char == sep and bracket_level == 0:
|
|
146
|
+
parts.append(''.join(current_part))
|
|
147
|
+
current_part = []
|
|
148
|
+
continue
|
|
149
|
+
current_part.append(char)
|
|
150
|
+
|
|
151
|
+
parts.append(''.join(current_part))
|
|
152
|
+
return parts
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def get_parents(id):
|
|
156
|
+
"""Return parent case IDs for a hierarchical case ID.
|
|
157
|
+
|
|
158
|
+
Args:
|
|
159
|
+
id: Case ID to trace back through its ancestor chain.
|
|
160
|
+
|
|
161
|
+
Returns:
|
|
162
|
+
list[str]: Ancestor IDs, ordered from shortest to longest path and with
|
|
163
|
+
duplicates removed. Root-level IDs return an empty list.
|
|
164
|
+
"""
|
|
165
|
+
id_sep = split_id(id)
|
|
166
|
+
if len(id_sep) == 1:
|
|
167
|
+
return []
|
|
168
|
+
|
|
169
|
+
parents = []
|
|
170
|
+
for i, piece in enumerate(id_sep[:-1]):
|
|
171
|
+
if '&' in piece:
|
|
172
|
+
more_parents = []
|
|
173
|
+
for subpiece in split_id(piece, '&'):
|
|
174
|
+
if subpiece.startswith('[') and subpiece.endswith(']'):
|
|
175
|
+
subpiece = subpiece[1:-1]
|
|
176
|
+
more_parents.append(subpiece)
|
|
177
|
+
for parent in more_parents:
|
|
178
|
+
parents.extend(get_parents(parent))
|
|
179
|
+
parents.extend(more_parents)
|
|
180
|
+
else:
|
|
181
|
+
parents.append('/'.join(id_sep[:i + 1]))
|
|
182
|
+
|
|
183
|
+
# remove duplicates
|
|
184
|
+
parents = list(dict.fromkeys(parents))
|
|
185
|
+
|
|
186
|
+
# order by length
|
|
187
|
+
parents.sort(key=lambda x: len(x))
|
|
188
|
+
|
|
189
|
+
return parents
|
d3tools/cli.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Command-line interface for running D3tools workflows."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
|
|
6
|
+
from d3tools import WorkflowDefinition
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def parse_arguments(argv: Sequence[str] | None = None) -> argparse.Namespace:
|
|
10
|
+
"""Parse command-line arguments for a workflow run.
|
|
11
|
+
|
|
12
|
+
Args:
|
|
13
|
+
argv: Arguments to parse. When omitted, arguments are read from
|
|
14
|
+
:data:`sys.argv`.
|
|
15
|
+
|
|
16
|
+
Returns:
|
|
17
|
+
The parsed command-line arguments.
|
|
18
|
+
"""
|
|
19
|
+
parser = argparse.ArgumentParser(
|
|
20
|
+
description="Run workflow with specified parameters",
|
|
21
|
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
|
22
|
+
)
|
|
23
|
+
parser.add_argument("workflow_json", help="JSON file of the workflow")
|
|
24
|
+
parser.add_argument(
|
|
25
|
+
"-s",
|
|
26
|
+
"--start",
|
|
27
|
+
help="Start date to download the data [YYYY-MM-DD]",
|
|
28
|
+
)
|
|
29
|
+
parser.add_argument(
|
|
30
|
+
"-e",
|
|
31
|
+
"--end",
|
|
32
|
+
help="End date to download the data [YYYY-MM-DD]",
|
|
33
|
+
)
|
|
34
|
+
return parser.parse_args(argv)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def main(argv: Sequence[str] | None = None) -> None:
|
|
38
|
+
"""Load and run the workflow selected on the command line.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
argv: Arguments to parse. When omitted, arguments are read from
|
|
42
|
+
:data:`sys.argv`.
|
|
43
|
+
"""
|
|
44
|
+
args = parse_arguments(argv)
|
|
45
|
+
options: WorkflowDefinition = WorkflowDefinition.load(
|
|
46
|
+
args.workflow_json,
|
|
47
|
+
build_workflow_objects=True,
|
|
48
|
+
strict_workflow_imports=True,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
for workflow_section in options.workflow_sections:
|
|
52
|
+
workflow_section.value.get_last_ts()
|
|
53
|
+
if hasattr(workflow_section.value, "get_first_ts"):
|
|
54
|
+
workflow_section.value.get_first_ts()
|
|
55
|
+
|
|
56
|
+
options.run(start=args.start, end=args.end)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
if __name__ == "__main__":
|
|
60
|
+
main()
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Public configuration API for d3tools workflows.
|
|
2
|
+
|
|
3
|
+
This package exposes workflow-definition objects, parsing helpers, and the
|
|
4
|
+
configuration pipeline used to resolve environment variables, tags, datasets,
|
|
5
|
+
and section metadata before execution.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .workflow_definition import WorkflowDefinition
|
|
9
|
+
from .options import Options
|
|
10
|
+
from .parsers import dataset_from_config, workflow_from_config
|
|
11
|
+
from .workflow_section import WORKFLOW_SECTION_ALIASES, WorkflowSection
|
|
12
|
+
from .parsing_pipeline import (
|
|
13
|
+
resolve_env,
|
|
14
|
+
resolve_tags,
|
|
15
|
+
build_datasets,
|
|
16
|
+
resolve_dataset_refs,
|
|
17
|
+
collect_workflow_sections,
|
|
18
|
+
parse_options,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
'WORKFLOW_SECTION_ALIASES',
|
|
23
|
+
'WorkflowSection',
|
|
24
|
+
'WorkflowDefinition',
|
|
25
|
+
'Options',
|
|
26
|
+
'dataset_from_config',
|
|
27
|
+
'workflow_from_config',
|
|
28
|
+
'resolve_env',
|
|
29
|
+
'resolve_tags',
|
|
30
|
+
'build_datasets',
|
|
31
|
+
'resolve_dataset_refs',
|
|
32
|
+
'collect_workflow_sections',
|
|
33
|
+
'parse_options',
|
|
34
|
+
]
|