Debian Codegraph @

cylc/flow/time_parser.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 """This module is for parsing date/time representations.
17
18 Expressions can be formatted in either the full ISO 8601:2004 date/time
19 representations (also including the ISO 8601:2000 truncated syntax), or
20 in the Cylc-specific abbreviations thereof.
21
22 Where abbreviations or truncations are used, the missing information
23 needs to be filled in by some date/time context - this means that "T06"
24 needs to be applied to a context time such as "20201205T0000Z" in order
25 to get a full date/time (in this example, "20201205T0600Z"). This
26 context is the initial cycle point or final cycle point for the task
27 cycling dependency graph section specification, and is the task cycle
28 time for inter-cycle task references such as "foo[-P6Y] => foo".
29
30 """
31
32 import re
33 from typing import TYPE_CHECKING, List, Optional, Pattern, Tuple, Union, cast
34
35 from metomi.isodatetime.data import Duration, TimeRecurrence
36 from metomi.isodatetime.exceptions import IsodatetimeError
37 from metomi.isodatetime.parsers import (
38 DurationParser, TimePointParser, TimeRecurrenceParser
39 )
40
41 from cylc.flow import LOG
42 from cylc.flow.cycling import parse_exclusion
43 from cylc.flow.exceptions import (
44 CylcMissingContextPointError,
45 CylcMissingFinalCyclePointError,
46 CylcTimeSyntaxError,
47 )
48 import cylc.flow.flags
49
50 if TYPE_CHECKING:
51 from metomi.isodatetime.data import TimePoint
52 from cylc.flow.cycling.iso8601 import ISO8601Point
53
54
55 UTC_UTC_OFFSET_HOURS_MINUTES = (0, 0)
56
57
58 class CylcTimeParser:
59
60 """Parser for Cylc abbreviated/full ISO 8601 syntax.
61
62 Arguments:
63 context_start_point describes the beginning date/time used for
64 extrapolating incomplete date/time syntax (usually initial
65 cycle point). It is either a date/time string in full ISO 8601
66 syntax or a metomi.isodatetime.data.TimePoint object.
67 context_end_point is the same as context_start_point, but describes
68 a final time - e.g. the final cycle point.
69
70 """
71
72 POINT_INVALID_FOR_CYLC_REGEXES = [
73 (re.compile(r"^\d\d$"),
74 ("2 digit centuries not allowed. Did you mean T-digit-digit e.g. "
75 "'T00'?"))
76 ]
77
78 RECURRENCE_FORMAT_REGEXES: List[Tuple[Pattern, int]] = [
79 (re.compile(r"^(?P<start>[^PR/][^/]*)$"), 3),
80 (re.compile(r"^R(?P<reps>\d+)?/(?P<start>[^PR/][^/]*)/(?P<end>[^PR/]"
81 "[^/]*)$"), 1),
82 (re.compile(r"^(?P<start>[^PR/][^/]*)/(?P<intv>P[^/]*)/?$"), 3),
83 (re.compile(r"^(?P<intv>P[^/]*)$"), 3),
84 (re.compile(r"^(?P<intv>P[^/]*)/(?P<end>[^PR/][^/]*)$"), 4),
85 (re.compile(r"^R(?P<reps>\d+)?/(?P<start>[^PR/][^/]*)/?$"), 3),
86 (re.compile(r"^R(?P<reps>\d+)?/(?P<start>[^PR/][^/]*)/(?P<intv>P[^/]"
87 "*)$"), 3),
88 (re.compile(r"^R(?P<reps>\d+)?/(?P<start>)/(?P<intv>P[^/]*)$"), 3),
89 (re.compile(r"^R(?P<reps>\d+)?/(?P<intv>P[^/]*)/(?P<end>[^PR/][^/]*)"
90 "$"), 4),
91 (re.compile(r"^R(?P<reps>\d+)?/(?P<intv>P[^/]*)/?$"), 4),
92 (re.compile(r"^R(?P<reps>\d+)?//(?P<end>[^PR/][^/]*)$"), 4),
93 (re.compile(r"^R(?P<reps>1)/?(?P<start>$)"), 3),
94 (re.compile(r"^R(?P<reps>1)//(?P<end>[^PR/][^/]*)$"), 4)
95 ]
96
97 CHAIN_REGEX = re.compile(r'((?:[+-P]|[\dT])[\d\w]*)')
98
99 MIN_REGEX = re.compile(r'min\(([^)]+)\)')
100
101 OFFSET_REGEX = re.compile(r"(?P<sign>[+-])(?P<intv>P.+)$")
102
103 TRUNCATED_REC_MAP = {
104 "---": [re.compile(r"^\d\dT")],
105 "--": [re.compile(r"^\d\d\d\dT")],
106 "-": [
107 re.compile(r"^\d\d\dT"),
108 re.compile(r"\dW\d\dT"),
109 re.compile(r"W\d\d\d?T"),
110 re.compile(r"W-\dT"),
111 re.compile(r"W-\d")
112 ]
113 }
114
115 __slots__ = ('timepoint_parser', 'duration_parser', 'recurrence_parser',
116 'context_start_point', 'context_end_point')
117
118 def __init__(
119 self,
120 context_start_point: Union['ISO8601Point', 'TimePoint', str, None],
121 context_end_point: Union['ISO8601Point', 'TimePoint', str, None],
122 parsers: Tuple[TimePointParser, DurationParser, TimeRecurrenceParser]
123 ):
124 if context_start_point is not None:
125 context_start_point = str(context_start_point)
126 if context_end_point is not None:
127 context_end_point = str(context_end_point)
128 self.timepoint_parser, self.duration_parser, self.recurrence_parser = (
129 parsers
130 )
131
132 if isinstance(context_start_point, str):
133 context_start_point, _ = self._get_point_from_expression(
134 context_start_point, None)
135 self.context_start_point: Optional['TimePoint'] = context_start_point
136 if isinstance(context_end_point, str):
137 context_end_point, _ = self._get_point_from_expression(
138 context_end_point, None)
139 self.context_end_point: Optional['TimePoint'] = context_end_point
140
141 @staticmethod
142 def initiate_parsers(num_expanded_year_digits=0, dump_format=None,
143 assumed_time_zone=None):
144 """Initiate datetime parsers required to initiate this class.
145
146 Returns:
147 tuple: (timepoint_parser, duration_parser, time_recurrence_parser)
148 - timepoint_parser - metomi.isodatetime.parsers.TimePointParser
149 obj.
150 - duration_parser - metomi.isodatetime.parsers.DurationParser
151 obj.
152 - time_recurrence_parser -
153 metomi.isodatetime.parsers.TimeRecurrenceParser obj
154 """
155
156 if dump_format is None:
157 if num_expanded_year_digits:
158 dump_format = "+XCCYYMMDDThhmmZ"
159 else:
160 dump_format = "CCYYMMDDThhmmZ"
161
162 timepoint_parser = TimePointParser(
163 allow_only_basic=False,
164 allow_truncated=True,
165 num_expanded_year_digits=num_expanded_year_digits,
166 dump_format=dump_format,
167 assumed_time_zone=assumed_time_zone
168 )
169
170 return (timepoint_parser, DurationParser(), TimeRecurrenceParser())
171
172 def parse_interval(self, expr: str) -> Duration:
173 """Parse an interval (duration) in full ISO date/time format."""
174 return self.duration_parser.parse(expr)
175
176 def parse_timepoint(
177 self, expr: str, context_point: Optional['TimePoint'] = None
178 ) -> 'TimePoint':
179 """Parse an expression in abbrev. or full ISO date/time format.
180
181 Args:
182 expr: a string such as 20010205T00Z, or a truncated/abbreviated
183 format string such as T06 or -P2Y.
184 context_point: supplies the missing information for truncated
185 expressions. E.g. for inter-cycle dependency expressions,
186 it should be the task cycle point.
187 If None, self.context_start_point is used.
188
189 """
190 if context_point is None:
191 context_point = self.context_start_point
192 point, offsets = self._get_point_from_expression(
193 expr, context_point, allow_truncated=True
194 )
195 if point is not None:
196 if point.truncated:
197 point += context_point # type: ignore[operator]
198 for offset in offsets:
199 point += offset
200 return point
201 raise CylcTimeSyntaxError(
202 ("'%s': not a valid cylc-shorthand or full " % expr) +
203 "ISO 8601 date representation")
204
205 def parse_recurrence(
206 self,
207 expression: str,
208 context_start_point: Optional['TimePoint'] = None,
209 context_end_point: Optional['TimePoint'] = None,
210 zero_duration_warning: bool = True,
211 ) -> Tuple[TimeRecurrence, list]:
212 """Parse an expression in abbrev. or full ISO recurrence format.
213
214 Args:
215 expression:
216 The recurrence expression to parse.
217 context_start_point:
218 Sequence start point from the global context.
219 context_end_point:
220 Sequence end point from the global context.
221 zero_duration_warning:
222 If `False`, then zero-duration recurrence warnings will be
223 turned off. This is set for exclusion parsing.
224
225 """
226 expression, exclusions = parse_exclusion(str(expression))
227
228 if context_start_point is None:
229 context_start_point = self.context_start_point
230 if context_end_point is None:
231 context_end_point = self.context_end_point
232 for rec_object, format_num in self.RECURRENCE_FORMAT_REGEXES:
233 result = rec_object.search(expression)
234 if not result:
235 continue
236
237 repetitions = result.groupdict().get("reps")
238 if repetitions is not None:
239 repetitions = int(repetitions)
240 start: Optional[str] = result.groupdict().get("start")
241 end: Optional[str] = result.groupdict().get("end")
242 start_required = (format_num in {1, 3})
243 end_required = (format_num in {1, 4})
244 start_point, start_offsets = self._get_point_from_expression(
245 start, context_start_point,
246 is_required=start_required,
247 allow_truncated=True
248 )
249 try:
250 end_point, end_offsets = self._get_point_from_expression(
251 end, context_end_point,
252 is_required=end_required,
253 allow_truncated=True
254 )
255 except CylcMissingContextPointError:
256 raise CylcMissingFinalCyclePointError(
257 "This workflow requires a final cycle point."
258 ) from None
259
260 exclusion_points = []
261 # Convert the exclusion strings to ISO8601 points
262 if exclusions is not None:
263 for exclusion in exclusions:
264 try:
265 # Attempt to convert to TimePoint
266 exclusion_point, excl_offsets = (
267 self._get_point_from_expression(exclusion, None)
268 )
269 for offset in excl_offsets:
270 exclusion_point += offset # type: ignore[operator]
271 exclusion_points.append(exclusion_point)
272 except (CylcTimeSyntaxError, IndexError):
273 # Not a point, parse it as recurrence later
274 exclusion_points.append(exclusion)
275
276 intv = result.groupdict().get("intv")
277 intv_context_truncated_point = None
278 if start_point is not None and start_point.truncated:
279 intv_context_truncated_point = start_point
280 if end_point is not None and end_point.truncated:
281 intv_context_truncated_point = end_point
282 interval = self._get_interval_from_expression(
283 intv, context=intv_context_truncated_point)
284 if format_num == 1:
285 interval = None
286 elif repetitions == 1:
287 interval = Duration(0)
288 if start_point is not None:
289 if start_point.truncated:
290 start_point += ( # type: ignore[operator]
291 context_start_point
292 )
293 for offset in start_offsets:
294 start_point += offset
295 if end_point is not None:
296 if end_point.truncated:
297 end_point += context_end_point # type: ignore[operator]
298 for offset in end_offsets:
299 end_point += offset
300
301 if (
302 interval and
303 start_point is None and repetitions is None and
304 context_start_point is not None
305 ):
306 # isodatetime only reverses bounded end-point recurrences.
307 # This is unbounded, and will come back in reverse order.
308 # We need to reverse it.
309 start_point = cast( # (end pt can't be None if start is None)
310 'TimePoint', end_point
311 )
312 repetitions = 1
313 while start_point > context_start_point:
314 start_point -= interval
315 repetitions += 1
316 end_point = None
317
318 if (
319 zero_duration_warning
320 and not interval
321 and repetitions != 1
322 and (format_num != 1 or start_point == end_point)
323 ):
324 LOG.warning(
325 "Cannot have more than 1 repetition for zero-duration "
326 f"recurrence {expression}."
327 )
328
329 if cylc.flow.flags.cylc7_back_compat and format_num == 1:
330 LOG.warning(
331 f"The recurrence '{expression}' is unlikely to behave "
332 "the same way as in Cylc 7 as that implementation was "
333 "incorrect (see https://cylc.github.io/cylc-doc/stable/"
334 "html/user-guide/writing-workflows/scheduling.html"
335 "#format-1-r-limit-datetime-datetime)"
336 )
337
338 return TimeRecurrence(
339 repetitions=repetitions,
340 start_point=start_point,
341 duration=interval,
342 end_point=end_point
343 ), exclusion_points
344
345 raise CylcTimeSyntaxError("Could not parse %s" % expression)
346
347 def _get_interval_from_expression(
348 self, expr: Optional[str], context: Optional['TimePoint'] = None
349 ) -> Optional[Duration]:
350 if expr is None:
351 if context is None or not context.truncated:
352 return None
353 prop_name = context.get_largest_truncated_property_name()
354 kwargs = {}
355 if prop_name == "year_of_century":
356 kwargs = {"years": 100}
357 if prop_name == "year_of_decade":
358 kwargs = {"years": 10}
359 if prop_name in ["month_of_year", "week_of_year", "day_of_year"]:
360 kwargs = {"years": 1}
361 if prop_name == "day_of_month":
362 kwargs = {"months": 1}
363 if prop_name == "day_of_week":
364 kwargs = {"days": 7}
365 if prop_name == "hour_of_day":
366 kwargs = {"days": 1}
367 if prop_name == "minute_of_hour":
368 kwargs = {"hours": 1}
369 if prop_name == "second_of_minute":
370 kwargs = {"minutes": 1}
371 if not kwargs:
372 return None
373 return Duration(**kwargs)
374 return self.duration_parser.parse(expr)
375
376 def _get_min_from_expression(
377 self,
378 expr: str,
379 context: Optional['TimePoint']
380 ) -> str:
381 points: List[str] = [
382 x.strip() for x in re.findall(self.MIN_REGEX, expr)[0].split(",")
383 ]
384 ptslist: List['TimePoint'] = []
385 min_entry = ""
386 for point in points:
387 cpoint, offsets = self._get_point_from_expression(
388 point, context, allow_truncated=True
389 )
390 if cpoint is not None:
391 if cpoint.truncated:
392 cpoint += context # type: ignore[operator]
393 for offset in offsets:
394 cpoint += offset
395 ptslist.append(cpoint)
396 if cpoint == min(ptslist):
397 min_entry = point
398 return min_entry
399
400 def _get_point_from_expression(
401 self,
402 expr: Optional[str],
403 context: Optional['TimePoint'],
404 is_required: bool = False,
405 allow_truncated: bool = False
406 ) -> Tuple[Optional['TimePoint'], List[Duration]]:
407 """Gets a TimePoint from an expression"""
408 if expr is None:
409 if is_required and allow_truncated:
410 if context is None:
411 raise CylcMissingContextPointError(
412 "Missing context cycle point."
413 )
414 return context, []
415 return None, []
416
417 if expr.startswith("min("):
418 expr = self._get_min_from_expression(expr, context)
419
420 expr_offsets: List[Duration] = []
421 if self.OFFSET_REGEX.search(expr):
422 expr, expr_offsets = self.parse_chain_expression(expr)
423 if not expr and allow_truncated:
424 return context, expr_offsets
425
426 for invalid_rec, msg in self.POINT_INVALID_FOR_CYLC_REGEXES:
427 if invalid_rec.search(expr):
428 raise CylcTimeSyntaxError(f"'{expr}': {msg}")
429
430 expr_to_parse = expr
431 if expr.endswith("T"):
432 expr_to_parse += "00"
433 try:
434 expr_point: 'TimePoint' = self.timepoint_parser.parse(
435 expr_to_parse
436 )
437 except ValueError: # not IsodatetimeError as too specific
438 pass
439 else:
440 return expr_point, expr_offsets
441
442 if allow_truncated:
443 for truncation_string, recs in self.TRUNCATED_REC_MAP.items():
444 for rec in recs:
445 if rec.search(expr):
446 try:
447 expr_point = self.timepoint_parser.parse(
448 truncation_string + expr_to_parse)
449 except IsodatetimeError:
450 continue
451 return expr_point, expr_offsets
452
453 raise CylcTimeSyntaxError(
454 f"'{expr}': not a valid cylc-shorthand or full "
455 "ISO 8601 date representation"
456 )
457
458 def parse_chain_expression(self, expr: str) -> Tuple[str, List[Duration]]:
459 """Parse an expression such as '+P1M+P1D'.
460
461 Returns:
462 Expression: The expression with any offsets removed.
463 Offsets: List of offsets from the expression. Note: by keeping
464 offsets separate (rather than combine into 1 Duration),
465 we preserve order of operations.
466
467 Examples:
468 >>> ctp = CylcTimeParser(
469 ... None, None, (TimePointParser(), DurationParser(), None)
470 ... )
471 >>> expr, offsets = ctp.parse_chain_expression('2022+P1M-P1D')
472 >>> expr
473 '2022'
474 >>> [str(i) for i in offsets]
475 ['P1M', '-P1D']
476 """
477 expr_offsets: List[Duration] = []
478 chain_expr: List[str] = self.CHAIN_REGEX.findall(expr)
479 expr = ""
480 for item in chain_expr:
481 if "P" not in item:
482 expr += item
483 continue
484 split_expr = self.OFFSET_REGEX.split(item)
485 expr += split_expr.pop(0)
486 expr_offset_item = self.duration_parser.parse(item[1:])
487 if item[0] == "-":
488 expr_offset_item *= -1
489 expr_offsets.append(expr_offset_item)
490 return expr, expr_offsets