Debian Codegraph @

cylc/flow/param_expand.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 """Parameter expansion for runtime namespace names and graph strings.
17
18 Uses recursion to achieve nested looping over any number of parameters. In its
19 simplest form (without allowing for parameter offsets and specific values, and
20 with input already expressed as a string template) the method looks like this:
21
22 #------------------------------------------------------------------------------
23 def expand(template, params, results, values=None):
24 '''Recursive parameter expansion.
25
26 template: e.g. "foo_m(m)s=>bar_m%(m)s_n%(n)s".
27 results: output list of expanded strings.
28 params: list of parameter (name, max-value) tuples.
29 '''
30 if values is None:
31 values = {}
32 if not params:
33 results.add(template % values)
34 else:
35 param = params[0]
36 for value in range(param[1]):
37 values[param[0]] = value
38 expand(template, params[1:], results, values)
39 #------------------------------------------------------------------------------
40 if __name__ == "__main__":
41 results = []
42 expand(
43 "foo_m%(m)s=>bar_m%(m)s_n%(n)s",
44 results,
45 [('m', 2), ('n', 3)]
46 )
47 for result in results:
48 print result
49
50 foo_m0=>bar_m0_n0
51 foo_m0=>bar_m0_n1
52 foo_m0=>bar_m0_n2
53 foo_m1=>bar_m1_n0
54 foo_m1=>bar_m1_n1
55 foo_m1=>bar_m1_n2
56 #------------------------------------------------------------------------------
57 """
58
59 from contextlib import suppress
60 import re
61 from typing import List, Tuple
62
63 from cylc.flow.exceptions import ParamExpandError
64 from cylc.flow.task_id import TaskID
65
66 # To split runtime heading name lists.
67 REC_NAMES = re.compile(r'(?:[^,<]|<[^>]*>)+')
68 # To extract (e.g.) 'name', 'the, quick, brown', and 'other' from
69 # 'name<the, quick, brown>other' (other is used for clock-offsets).
70 REC_P_ALL = re.compile(r"(%s)?(?:<(.*?)>)?(.+)?" % TaskID.NAME_RE)
71 # To extract all parameter lists e.g. 'm,n,o' (from '<m,n,o>').
72 REC_P_GROUP = re.compile(r"<(.*?)>")
73 # To extract parameter name and optional offset or value e.g. 'm-1'.
74 REC_P_OFFS = re.compile(
75 r'(\w+)\s*([\-+]\s*\d+|=\s*%s)?' % TaskID.NAME_SUFFIX_RE)
76
77
78 def item_in_iterable(item, itt):
79 """Return True if item is in itt, by string or int comparison.
80
81 Items may be general strings, or strings of zero-padded integers.
82 """
83 if item in itt:
84 return True
85 try:
86 int(item)
87 except ValueError:
88 return False
89 return int(item) in (int(i) for i in itt)
90
91
92 class NameExpander:
93 """Handle parameter expansion in runtime namespace headings."""
94
95 def __init__(self, parameters):
96 """Initialize the parameterized task name expander.
97
98 parameters is:
99 ({param_name: [param_values], # list of strings
100 {param_name: param_template}) # e.g. "_m%(m)s"
101 """
102 self.param_cfg, self.param_tmpl_cfg = parameters
103
104 def expand(self, runtime_heading):
105 """Expand runtime namespace names for a subset of workflow parameters.
106
107 Input runtime_heading is a string that may contain comma-separated
108 parameterized namespace names, e.g. for "foo<m,n>, bar<m,n>".
109
110 Unlike GraphExpander this does not support offsets like "foo<m-1,n>",
111 but it does support specific parameter values like "foo<m=0,n>".
112
113 Returns a list of tuples, each with an expanded name and its parameter
114 values (to be passed to the corresponding tasks), e.g.:
115 [('foo_i0_j0', {i:'0', j:'0'}),
116 ('foo_i0_j1', {i:'0', j:'1'}),
117 ('foo_i1_j0', {i:'1', j:'0'}),
118 ('foo_i1_j1', {i:'1', j:'1'})]
119 """
120 # Create a string template and values to pass to the expansion method.
121 results = []
122 for name in REC_NAMES.findall(runtime_heading):
123 tmpl = ''
124 spec_vals = {}
125 used_params = []
126 while name:
127 head, p_list_str, tail = REC_P_ALL.match(name.strip()).groups()
128 if not p_list_str:
129 break
130 if head:
131 tmpl += head
132 # Get the subset of parameters used in this case.
133 for item in (i.strip() for i in p_list_str.split(',')):
134 pname, sval = REC_P_OFFS.match(item.strip()).groups()
135 if not self.param_cfg.get(pname, None):
136 raise ParamExpandError(
137 "parameter %s is not defined in %s" % (
138 pname, runtime_heading))
139 if sval:
140 if sval.startswith('+') or sval.startswith('-'):
141 raise ParamExpandError(
142 "parameter index offsets are not"
143 " supported in name expansion: %s%s" % (
144 pname, sval))
145 elif sval.startswith('='):
146 # Check that specific parameter values exist.
147 val = sval[1:].strip()
148 # Pad integer values here.
149 try:
150 nval = int(val)
151 except ValueError:
152 nval = val
153 if not item_in_iterable(
154 nval, self.param_cfg[pname]):
155 raise ParamExpandError(
156 "parameter %s out of range: %s" % (
157 pname, p_list_str))
158 spec_vals[pname] = nval
159 else:
160 used_params.append((pname, self.param_cfg[pname]))
161 tmpl += self.param_tmpl_cfg[pname]
162 if tail:
163 name = tail
164 else:
165 name = ''
166 if tmpl:
167 tmpl += name
168 self._expand_name(results, tmpl, used_params, spec_vals)
169 else:
170 results.append((name.strip(), {}))
171 return results
172
173 def _expand_name(self, results, tmpl, params, spec_vals=None):
174 """Recursively expand tmpl for any number of parameters.
175
176 tmpl is a string template, e.g. 'foo_m%(m)s_n%(n)s' for two
177 parameters m and n.
178 params is a list of tuples (name, max-val) for each parameter
179 to be looped over.
180 spec_vals is a map of values for parameters that are not to be looped
181 over because they've been assigned a specific value.
182
183 E.g. for "foo<m=0,n>" tmpl is "foo_m%(m)s_n%(n)s", params is
184 [('n', 2)], and spec_values {'m': 0}.
185
186 results contains the expanded names and corresponding parameter values,
187 as described above in the calling method.
188 """
189 if spec_vals is None:
190 spec_vals = {}
191 if not params:
192 # Inner loop.
193 current_values = dict(spec_vals)
194 try:
195 results.append((tmpl % current_values, current_values))
196 except KeyError as exc:
197 raise ParamExpandError(
198 'parameter %s is not defined.' % str(exc.args[0])
199 ) from None
200 else:
201 for param_val in params[0][1]:
202 spec_vals[params[0][0]] = param_val
203 self._expand_name(results, tmpl, params[1:], spec_vals)
204
205 @staticmethod
206 def _parse_task_name_string(task_str: str) -> Tuple[List[str], str]:
207 """Takes a parent string and returns a list of parameters and a
208 template string.
209
210 Examples:
211 >>> this = NameExpander._parse_task_name_string
212
213 # Parent doesn't contain a parameter:
214 >>> this('foo')
215 ([], 'foo')
216
217 # Parent contains a simple single parameter:
218 >>> this('<foo>')
219 (['foo'], '{foo}')
220
221 # Parent contains 2 parameters in 1 <>:
222 >>> this('something<foo, bar>other')
223 (['foo', 'bar'], 'something{foo}{bar}other')
224
225 # Parent contains 2 parameters in 2 <>:
226 >>> this('something<foo>middlebit<bar>other')
227 (['foo', 'bar'], 'something{foo}middlebit{bar}other')
228
229 # Parent contains 2 parameters, once with an = sign in it.
230 >>> this('something<foo=42>middlebit<bar>other')
231 (['foo=42', 'bar'], 'something{foo}middlebit{bar}other')
232
233 # Parent contains 2 parameters in 2 <>:
234 >>> this('something<foo,bar=99>other')
235 (['foo', 'bar=99'], 'something{foo}{bar}other')
236
237 # Parent contains spaces around = sign:
238 >>> this('FAM<i = cat ,j=3>')
239 (['i = cat', 'j=3'], 'FAM{i}{j}')
240 """
241 param_list = []
242
243 for match in REC_P_GROUP.finditer(task_str):
244 param = match.group(1)
245 if ',' in param:
246 # parameter syntax `<foo, bar>`
247 replacement = ''
248 for sub_param in param.split(','):
249 sub_param = sub_param.strip()
250 param_list.append(sub_param)
251 if '=' in sub_param:
252 sub_param = sub_param.split('=')[0].strip()
253 replacement += '{' + sub_param + '}'
254 else:
255 # parameter syntax: `<foo><bar>`
256 param_list.append(param)
257 if '=' in param:
258 replacement = '{' + param.split('=')[0] + '}'
259 else:
260 replacement = '{' + param + '}'
261
262 task_str = task_str.replace(match.group(0), replacement, 1)
263
264 return param_list, task_str
265
266 def expand_parent_params(self, parent, param_values, origin):
267 """Replace parameters with specific values in inherited parent names.
268
269 If a value is NOT specified, e.g.:
270 inherit = parent<m>
271 then it must be given in param_values (as defined by expansion of the
272 enclosing namespace name).
273
274 If a value IS specified, e.g.:
275 inherit = parent<m=3>
276 then it must be a legal value for that parameter.
277
278 """
279 p_list, tmpl = self._parse_task_name_string(parent)
280
281 if not p_list:
282 return (None, parent)
283
284 used = {}
285 for item in p_list:
286 if '-' in item or '+' in item:
287 raise ParamExpandError(
288 "parameter offsets illegal here: '%s'" % origin)
289 elif '=' in item:
290 # Specific value given.
291 pname, pval = [val.strip() for val in item.split('=', 1)]
292 with suppress(ValueError):
293 pval = int(pval)
294 if pname not in self.param_cfg:
295 raise ParamExpandError(
296 "parameter '%s' undefined in '%s'" % (
297 pname, origin))
298 elif pval not in self.param_cfg[pname]:
299 raise ParamExpandError(
300 "illegal value '%s=%s' in '%s'" % (
301 pname, pval, origin))
302 used[pname] = pval
303 else:
304 # Non-specific; value must be supplied in param_values.
305 try:
306 used[item] = param_values[item]
307 except KeyError:
308 raise ParamExpandError(
309 "parameter '%s' undefined in '%s'" % (item, origin)
310 ) from None
311
312 # For each parameter substitute the param_tmpl_cfg.
313 tmpl = tmpl.format(**self.param_tmpl_cfg)
314 # Insert parameter values into template.
315 return (used, tmpl % used)
316
317
318 class GraphExpander:
319 """Handle parameter expansion of graph string lines."""
320
321 _REMOVE = -32768
322
323 def __init__(self, parameters):
324 """Initialize the parameterized task name expander.
325
326 parameters is:
327 ({param_name: [param_values], # list of strings
328 {param_name: param_template}) # e.g. "_m%(m)s"
329 """
330 try:
331 self.param_cfg, self.param_tmpl_cfg = parameters
332 except (TypeError, ValueError):
333 self.param_cfg, self.param_tmpl_cfg = ({}, {})
334
335 def expand(self, line):
336 """Expand a graph line for subset of workflow parameters.
337
338 Input line is a string that may contain multiple parameterized node
339 names, e.g. "pre=>init<m>=>sim<m,n>=>post<m,n>=>done".
340
341 Unlike NameExpander this supports offsets like "foo<m-1,n>", which
342 means (because the parameter substitutions have to be computed on the
343 fly) we have shift creation of the expansion string template into the
344 inner loop of the recursive expansion function.
345
346 Returns a set containing lines expanded for all used parameters, e.g.
347 for "foo=>bar<m,n>" with m=2 and n=2 the result would be:
348 set([foo=>bar_m0_n0,
349 foo=>bar_m0_n1,
350 foo=>bar_m1_n0,
351 foo=>bar_m1_n1])
352
353 Specific parameter values can be singled out like this:
354 "sim<m=0,n>=>sim<m,n>"
355 Offset (negative only) values can be specified like this:
356 "sim<m-1,n>=>sim<m,n>"
357 (Here the offset node must be the first in a line, and if m-1 evaluates
358 to less than 0 the node will be removed to leave just "sim<m,n>").
359 """
360 line_set = set()
361 used_pnames = []
362 for p_group in set(REC_P_GROUP.findall(line)):
363 for item in p_group.split(','):
364 pname, offs = REC_P_OFFS.match(item).groups()
365 if not self.param_cfg.get(pname, None):
366 raise ParamExpandError(
367 "parameter %s is not defined in <%s>: %s" % (
368 pname, p_group, line))
369 if offs and offs.startswith('='):
370 # Check that specific parameter values exist.
371 val = offs[1:]
372 try:
373 nval = int(val)
374 except ValueError:
375 nval = val
376 if not item_in_iterable(nval, self.param_cfg[pname]):
377 raise ParamExpandError(
378 "parameter %s out of range: %s" % (
379 pname, p_group))
380 if pname not in used_pnames:
381 used_pnames.append(pname)
382 used_params = [(p, self.param_cfg[p]) for p in used_pnames]
383 self._expand_graph(line, dict(used_params), used_params, line_set)
384 return line_set
385
386 def _expand_graph(self, line, all_params,
387 param_list, line_set, values=None):
388 """Expand line into line_set for any number of parameters.
389
390 line is a graph string line as described above in the calling method.
391 param_list is a list of tuples (name, max-val) for each parameter.
392 results is a set to hold each expanded line.
393 """
394 if values is None:
395 values = {}
396 if not param_list:
397 # Inner loop.
398 for p_group in set(REC_P_GROUP.findall(line)):
399 # Parameters must be expanded in the order found.
400 param_values = {}
401 for item in p_group.split(','):
402 pname, offs = REC_P_OFFS.match(item).groups()
403 if offs is None:
404 param_values[pname] = values[pname]
405 elif offs[0] == '=':
406 # Specific value.
407 try:
408 # Template may require an integer
409 param_values[pname] = int(offs[1:])
410 except ValueError:
411 param_values[pname] = offs[1:]
412 else:
413 # Index offset.
414 plist = all_params[pname]
415 cur_idx = plist.index(values[pname])
416 off_idx = cur_idx + int(offs)
417 if 0 <= off_idx < len(plist):
418 offval = plist[off_idx]
419 else:
420 offval = self._REMOVE
421 param_values[pname] = offval
422 tmpl = ''.join(
423 self.param_tmpl_cfg[pname]
424 for pname in param_values
425 )
426 try:
427 repl = tmpl % param_values
428 except KeyError as exc:
429 raise ParamExpandError(
430 'parameter %s is not defined.' % str(exc.args[0])
431 ) from None
432 line = line.replace('<' + p_group + '>', repl)
433 if line:
434 line_set.add(line)
435 else:
436 # Recurse through index ranges.
437 for param_val in param_list[0][1]:
438 values[param_list[0][0]] = param_val
439 self._expand_graph(line, all_params,
440 param_list[1:], line_set, values)