Debian Codegraph @

cylc/flow/cycling/iso8601.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
17 """Date-time cycling by point, interval, and sequence classes."""
18
19 import contextlib
20 from functools import lru_cache
21 import re
22 from typing import List, Optional, TYPE_CHECKING, Tuple
23
24 from metomi.isodatetime.data import Calendar, CALENDAR, Duration
25 from metomi.isodatetime.dumpers import TimePointDumper
26 from metomi.isodatetime.timezone import (
27 get_local_time_zone, get_local_time_zone_format, TimeZoneFormatMode)
28 from metomi.isodatetime.exceptions import IsodatetimeError
29 from metomi.isodatetime.parsers import ISO8601SyntaxError
30 from cylc.flow.time_parser import CylcTimeParser
31 from cylc.flow.cycling import (
32 PointBase, IntervalBase, SequenceBase, ExclusionBase, cmp
33 )
34 from cylc.flow.exceptions import (
35 CylcConfigError,
36 IntervalParsingError,
37 PointParsingError,
38 SequenceDegenerateError,
39 WorkflowConfigError
40 )
41 from cylc.flow.wallclock import get_current_time_string
42 from cylc.flow.parsec.validate import IllegalValueError
43
44 if TYPE_CHECKING:
45 from metomi.isodatetime.data import TimePoint
46 from metomi.isodatetime.parsers import (
47 DurationParser, TimePointParser, TimeRecurrenceParser)
48
49 CYCLER_TYPE_ISO8601 = "iso8601"
50 CYCLER_TYPE_SORT_KEY_ISO8601 = 1
51
52 DATE_TIME_FORMAT = "CCYYMMDDThhmm"
53 EXPANDED_DATE_TIME_FORMAT = "+XCCYYMMDDThhmm"
54 NEW_DATE_TIME_REC = re.compile("T")
55
56 WARNING_PARSE_EXPANDED_YEAR_DIGITS = (
57 "(incompatible with [cylc]cycle point num expanded year digits = %s ?)")
58
59
60 class WorkflowSpecifics:
61
62 """Store workflow-setup-specific constants and utilities here."""
63 ASSUMED_TIME_ZONE: Tuple[int, int]
64 DUMP_FORMAT: str
65 abbrev_util: CylcTimeParser
66 interval_parser: 'DurationParser'
67 point_parser: 'TimePointParser'
68 recurrence_parser: 'TimeRecurrenceParser'
69 iso8601_parsers: Tuple[
70 'TimePointParser', 'DurationParser', 'TimeRecurrenceParser'
71 ]
72 NUM_EXPANDED_YEAR_DIGITS: int = 0
73
74
75 class ISO8601Point(PointBase):
76
77 """A single point in an ISO8601 date time sequence."""
78
79 TYPE = CYCLER_TYPE_ISO8601
80 TYPE_SORT_KEY = CYCLER_TYPE_SORT_KEY_ISO8601
81
82 __slots__ = ('value')
83
84 @classmethod
85 def from_nonstandard_string(cls, point_string):
86 """Standardise a date-time string."""
87 return ISO8601Point(str(point_parse(point_string))).standardise()
88
89 def add(self, other):
90 """Add an Interval to self."""
91 return ISO8601Point(self._iso_point_add(
92 self.value, other.value, CALENDAR.mode
93 ))
94
95 def standardise(self, allow_truncated=True):
96 """Reformat self.value into a standard representation."""
97 try:
98 point = point_parse(self.value)
99 if not allow_truncated and point.truncated:
100 raise PointParsingError(
101 type(self),
102 self.value,
103 'Truncated ISO8601 dates are not permitted',
104 )
105 self.value = str(point_parse(self.value))
106 except IsodatetimeError as exc:
107 if self.value.startswith("+") or self.value.startswith("-"):
108 message = WARNING_PARSE_EXPANDED_YEAR_DIGITS % (
109 WorkflowSpecifics.NUM_EXPANDED_YEAR_DIGITS)
110 else:
111 message = str(exc)
112 raise PointParsingError(type(self), self.value, message) from None
113 return self
114
115 def sub(self, other):
116 """Subtract a Point or Interval from self."""
117 if isinstance(other, ISO8601Point):
118 return ISO8601Interval(self._iso_point_sub_point(
119 self.value, other.value, CALENDAR.mode
120 ))
121 return ISO8601Point(self._iso_point_sub_interval(
122 self.value, other.value, CALENDAR.mode
123 ))
124
125 @staticmethod
126 @lru_cache(10000)
127 def _iso_point_add(point_string, interval_string, _calendar_mode):
128 """Add the parsed point_string to the parsed interval_string."""
129 point = point_parse(point_string)
130 interval = interval_parse(interval_string)
131 return str(point + interval)
132
133 def _cmp(self, other: 'ISO8601Point') -> int:
134 return self._iso_point_cmp(self.value, other.value, CALENDAR.mode)
135
136 @staticmethod
137 @lru_cache(10000)
138 def _iso_point_cmp(point_string, other_point_string, _calendar_mode):
139 """Compare the parsed point_string to the other one."""
140 point = point_parse(point_string)
141 other_point = point_parse(other_point_string)
142 return cmp(point, other_point)
143
144 @staticmethod
145 @lru_cache(10000)
146 def _iso_point_sub_interval(point_string, interval_string, _calendar_mode):
147 """Return the parsed point_string minus the parsed interval_string."""
148 point = point_parse(point_string)
149 interval = interval_parse(interval_string)
150 return str(point - interval)
151
152 @staticmethod
153 @lru_cache(10000)
154 def _iso_point_sub_point(point_string, other_point_string, _calendar_mode):
155 """Return the difference between the two parsed point strings."""
156 point = point_parse(point_string)
157 other_point = point_parse(other_point_string)
158 return str(point - other_point)
159
160
161 class ISO8601Interval(IntervalBase):
162
163 """The interval between points in an ISO8601 date time sequence."""
164
165 NULL_INTERVAL_STRING = "P0Y"
166 TYPE = CYCLER_TYPE_ISO8601
167 TYPE_SORT_KEY = CYCLER_TYPE_SORT_KEY_ISO8601
168
169 __slots__ = ('value')
170
171 @classmethod
172 def get_null(cls):
173 """Return a null interval."""
174 return ISO8601Interval("P0Y")
175
176 @classmethod
177 def get_null_offset(cls):
178 """Return a null offset."""
179 return ISO8601Interval("+P0Y")
180
181 def standardise(self):
182 """Format self.value into a standard representation."""
183 try:
184 self.value = str(interval_parse(self.value))
185 except IsodatetimeError:
186 raise IntervalParsingError(type(self), self.value) from None
187 return self
188
189 def add(self, other):
190 """Add other to self (point or interval) c.f. ISO 8601."""
191 if isinstance(other, ISO8601Interval):
192 return ISO8601Interval(
193 self._iso_interval_add(self.value, other.value))
194 return other + self
195
196 def _cmp(self, other: 'IntervalBase') -> int:
197 """Compare another interval with this one."""
198 return self._iso_interval_cmp(self.value, other.value)
199
200 def sub(self, other):
201 """Subtract another interval from this one."""
202 return ISO8601Interval(
203 self._iso_interval_sub(self.value, other.value))
204
205 def __abs__(self):
206 """Return an interval with absolute values of this one's values."""
207 return ISO8601Interval(
208 self._iso_interval_abs(self.value, self.NULL_INTERVAL_STRING))
209
210 def __mul__(self, factor):
211 """Return an interval with v * factor for v in this one's values."""
212 return ISO8601Interval(self._iso_interval_mul(self.value, factor))
213
214 def __bool__(self):
215 """Return whether this interval has any non-null values."""
216 return self._iso_interval_nonzero(self.value)
217
218 @staticmethod
219 @lru_cache(10000)
220 def _iso_interval_abs(interval_string, other_interval_string):
221 """Return the absolute (non-negative) value of an interval_string."""
222 interval = interval_parse(interval_string)
223 other = interval_parse(other_interval_string)
224 if interval < other:
225 return str(interval * -1)
226 return interval_string
227
228 @staticmethod
229 @lru_cache(10000)
230 def _iso_interval_add(interval_string, other_interval_string):
231 """Return one parsed interval_string plus the other one."""
232 interval = interval_parse(interval_string)
233 other = interval_parse(other_interval_string)
234 return str(interval + other)
235
236 @staticmethod
237 @lru_cache(10000)
238 def _iso_interval_cmp(interval_string, other_interval_string):
239 """Compare one parsed interval_string with the other one."""
240 interval = interval_parse(interval_string)
241 other = interval_parse(other_interval_string)
242 return cmp(interval, other)
243
244 @staticmethod
245 @lru_cache(10000)
246 def _iso_interval_sub(interval_string, other_interval_string):
247 """Subtract one parsed interval_string from the other one."""
248 interval = interval_parse(interval_string)
249 other = interval_parse(other_interval_string)
250 return str(interval - other)
251
252 @staticmethod
253 @lru_cache(10000)
254 def _iso_interval_mul(interval_string, factor):
255 """Multiply one parsed interval_string's values by factor."""
256 interval = interval_parse(interval_string)
257 return str(interval * factor)
258
259 @staticmethod
260 @lru_cache(10000)
261 def _iso_interval_nonzero(interval_string):
262 """Return whether the parsed interval_string is a null interval."""
263 interval = interval_parse(interval_string)
264 return bool(interval)
265
266
267 class ISO8601Exclusions(ExclusionBase):
268 """A collection of ISO8601Sequences that represent excluded sequences.
269
270 The object is able to determine if points are within any of its
271 grouped exclusion sequences. The Python ``in`` and ``not in`` operators
272 may be used on this object to determine if a point is in the collection
273 of exclusion sequences."""
274
275 def __init__(self, excl_points, start_point, end_point=None):
276 super(ISO8601Exclusions, self).__init__(start_point, end_point)
277 self.build_exclusions(excl_points)
278
279 def build_exclusions(self, excl_points):
280 for point in excl_points:
281 try:
282 # Try making an ISO8601Sequence
283 exclusion = ISO8601Sequence(
284 point,
285 self.exclusion_start_point,
286 self.exclusion_end_point,
287 # disable warnings which are logged when exclusion is a
288 # time point
289 zero_duration_warning=False,
290 )
291 self.exclusion_sequences.append(exclusion)
292 except (AttributeError, TypeError, ValueError):
293 # Try making an ISO8601Point
294 exclusion_point = ISO8601Point.from_nonstandard_string(
295 str(point)) if point else None
296 if exclusion_point not in self.exclusion_points:
297 self.exclusion_points.append(exclusion_point)
298
299
300 class ISO8601Sequence(SequenceBase):
301
302 """A sequence of ISO8601 date time points separated by an interval.
303 Note that an ISO8601Sequence object (may) contain
304 ISO8601ExclusionSequences
305
306 Args:
307 dep_section:
308 The full sequence expression.
309 context_start_point:
310 Sequence start point from the global context.
311 context_end_point:
312 Sequence end point from the global context.
313 zero_duration_warning:
314 If `False`, then zero-duration recurrence warnings will be turned
315 off. This is set for exclusion parsing.
316
317 """
318
319 TYPE = CYCLER_TYPE_ISO8601
320 TYPE_SORT_KEY = CYCLER_TYPE_SORT_KEY_ISO8601
321 _MAX_CACHED_POINTS = 100
322
323 __slots__ = ('dep_section', 'context_start_point', 'context_end_point',
324 'offset', '_cached_first_point_values',
325 '_cached_next_point_values', '_cached_valid_point_booleans',
326 '_cached_recent_valid_points', 'spec', 'abbrev_util',
327 'recurrence', 'exclusions', 'step', 'value', 'is_on_sequence')
328
329 @classmethod
330 def get_async_expr(cls, start_point=None):
331 """Express a one-off sequence at the initial cycle point."""
332 if start_point is None:
333 return "R1"
334 return "R1/" + str(start_point)
335
336 def __init__(
337 self,
338 dep_section,
339 context_start_point=None,
340 context_end_point=None,
341 zero_duration_warning=True,
342 ):
343 SequenceBase.__init__(
344 self, dep_section, context_start_point, context_end_point)
345 self.dep_section = dep_section
346
347 # cache is_on_sequence
348 # see B019 - https://github.com/PyCQA/flake8-bugbear#list-of-warnings
349 self.is_on_sequence = lru_cache(maxsize=100)(self._is_on_sequence)
350
351 if (
352 context_start_point is None
353 or isinstance(context_start_point, ISO8601Point)
354 ):
355 self.context_start_point = context_start_point
356 else:
357 self.context_start_point = ISO8601Point.from_nonstandard_string(
358 context_start_point)
359
360 if context_end_point is None:
361 self.context_end_point = None
362 elif isinstance(context_end_point, ISO8601Point):
363 self.context_end_point = context_end_point
364 else:
365 self.context_end_point = ISO8601Point.from_nonstandard_string(
366 context_end_point)
367
368 self.offset = ISO8601Interval.get_null()
369
370 self._cached_first_point_values = {}
371 self._cached_next_point_values = {}
372 self._cached_valid_point_booleans = {}
373 self._cached_recent_valid_points = []
374
375 self.spec = dep_section
376 self.abbrev_util = CylcTimeParser(self.context_start_point,
377 self.context_end_point,
378 WorkflowSpecifics.iso8601_parsers)
379 # Parse_recurrence returns an isodatetime TimeRecurrence object
380 # and a list of exclusion strings.
381 self.recurrence, excl_points = self.abbrev_util.parse_recurrence(
382 dep_section,
383 zero_duration_warning=zero_duration_warning,
384 )
385
386 # Determine the exclusion start point and end point
387 try:
388 exclusion_start_point = ISO8601Point.from_nonstandard_string(
389 str(self.recurrence.start_point))
390 except IsodatetimeError:
391 exclusion_start_point = self.context_start_point
392
393 try:
394 exclusion_end_point = ISO8601Point.from_nonstandard_string(
395 str(self.recurrence.end_point))
396 except IsodatetimeError:
397 exclusion_end_point = self.context_end_point
398
399 self.exclusions = []
400
401 # Creating an exclusions object instead
402 if excl_points:
403 with contextlib.suppress(AttributeError):
404 self.exclusions = ISO8601Exclusions(
405 excl_points,
406 exclusion_start_point,
407 exclusion_end_point)
408
409 self.step = (
410 ISO8601Interval(str(self.recurrence.duration))
411 if self.recurrence.duration
412 else ISO8601Interval.get_null()
413 )
414 self.value = str(self.recurrence)
415 # Concatenate the strings in exclusion list
416 if self.exclusions:
417 self.value += '!' + str(self.exclusions)
418
419 def get_interval(self):
420 """Return the interval between points in this sequence."""
421 return self.step
422
423 def get_offset(self):
424 """Deprecated: return the offset used for this sequence."""
425 return self.offset
426
427 def set_offset(self, i_offset):
428 """Deprecated: alter state to i_offset the entire sequence."""
429 self.recurrence += interval_parse(str(i_offset))
430 self._cached_first_point_values = {}
431 self._cached_next_point_values = {}
432 self._cached_valid_point_booleans = {}
433 self._cached_recent_valid_points = []
434 self.value = str(self.recurrence) + '!' + str(self.exclusions)
435 if self.exclusions:
436 self.value += '!' + str(self.exclusions)
437
438 # lru_cache'd see __init__()
439 def _is_on_sequence(self, point):
440 """Return True if point is on-sequence."""
441 # Iterate starting at recent valid points, for speed.
442 if self.exclusions and point in self.exclusions:
443 return False
444
445 for valid_point in reversed(self._cached_recent_valid_points):
446 if valid_point == point:
447 return True
448 if valid_point > point:
449 continue
450 next_point = valid_point
451 while next_point is not None and next_point < point:
452 next_point = self.get_next_point_on_sequence(next_point)
453 if next_point is None:
454 continue
455 if next_point == point:
456 return True
457 return self.recurrence.get_is_valid(point_parse(point.value))
458
459 def is_valid(self, point):
460 """Return True if point is on-sequence and in-bounds."""
461 try:
462 return self._cached_valid_point_booleans[point.value]
463 except KeyError:
464 is_valid = self.is_on_sequence(point)
465 if (len(self._cached_valid_point_booleans) >
466 self._MAX_CACHED_POINTS):
467 self._cached_valid_point_booleans.popitem()
468 self._cached_valid_point_booleans[point.value] = is_valid
469 return is_valid
470
471 def get_prev_point(self, point):
472 """Return the previous point < point, or None if out of bounds."""
473 # may be None if out of the recurrence bounds
474 res = None
475 prev_point = self.recurrence.get_prev(point_parse(point.value))
476 if prev_point:
477 res = ISO8601Point(str(prev_point))
478 if res == point:
479 raise SequenceDegenerateError(self.recurrence,
480 WorkflowSpecifics.DUMP_FORMAT,
481 res, point)
482 # Check if res point is in the list of exclusions
483 # If so, check the previous point by recursion.
484 # Once you have found a point that is *not* in the exclusion
485 # list, you can return it.
486 if self.exclusions and res in self.exclusions:
487 return self.get_prev_point(res)
488 return res
489
490 def get_nearest_prev_point(self, point):
491 """Return the largest point < some arbitrary point."""
492 if self.is_on_sequence(point):
493 return self.get_prev_point(point)
494 p_iso_point = point_parse(point.value)
495 prev_cycle_point = None
496
497 for recurrence_iso_point in self.recurrence:
498
499 # Is recurrence point greater than arbitrary point?
500 if recurrence_iso_point > p_iso_point:
501 break
502 recurrence_cycle_point = ISO8601Point(str(recurrence_iso_point))
503 if self.exclusions and recurrence_cycle_point in self.exclusions:
504 continue
505 prev_cycle_point = recurrence_cycle_point
506
507 if prev_cycle_point is None:
508 return None
509 if prev_cycle_point == point:
510 raise SequenceDegenerateError(
511 self.recurrence, WorkflowSpecifics.DUMP_FORMAT,
512 prev_cycle_point, point
513 )
514 return prev_cycle_point
515
516 def get_next_point(self, point):
517 """Return the next point > p, or None if out of bounds."""
518 with contextlib.suppress(KeyError):
519 return ISO8601Point(self._cached_next_point_values[point.value])
520 # Iterate starting at recent valid points, for speed.
521 for valid_point in reversed(self._cached_recent_valid_points):
522 if valid_point >= point:
523 continue
524 next_point = valid_point
525 excluded = False
526 while next_point is not None and (next_point <= point or excluded):
527 excluded = False
528 next_point = self.get_next_point_on_sequence(next_point)
529 if next_point and next_point in self.exclusions:
530 excluded = True
531 if next_point is not None:
532 self._check_and_cache_next_point(point, next_point)
533 return next_point
534 # Iterate starting at the beginning.
535 p_iso_point = point_parse(point.value)
536 for recurrence_iso_point in self.recurrence:
537 if recurrence_iso_point > p_iso_point:
538 next_point = ISO8601Point(str(recurrence_iso_point))
539 if next_point and next_point in self.exclusions:
540 continue
541 self._check_and_cache_next_point(point, next_point)
542 return next_point
543 return None
544
545 def _check_and_cache_next_point(self, point, next_point):
546 """Verify and cache the get_next_point return info."""
547 # Verify next_point != point.
548 if next_point == point:
549 raise SequenceDegenerateError(
550 self.recurrence, WorkflowSpecifics.DUMP_FORMAT,
551 next_point, point
552 )
553
554 # Cache the answer for point -> next_point.
555 if (len(self._cached_next_point_values) >
556 self._MAX_CACHED_POINTS):
557 self._cached_next_point_values.popitem()
558 self._cached_next_point_values[point.value] = next_point.value
559
560 # Cache next_point as a valid starting point for this recurrence.
561 if (len(self._cached_next_point_values) >
562 self._MAX_CACHED_POINTS):
563 self._cached_recent_valid_points.pop(0)
564 self._cached_recent_valid_points.append(next_point)
565
566 def get_next_point_on_sequence(
567 self, point: ISO8601Point
568 ) -> Optional[ISO8601Point]:
569 """Return the on-sequence point > point assuming that point is
570 on-sequence, or None if out of bounds."""
571 result = None
572 next_point = self.recurrence.get_next(point_parse(point.value))
573 if next_point:
574 result = ISO8601Point(str(next_point))
575 if result == point:
576 raise SequenceDegenerateError(
577 self.recurrence, WorkflowSpecifics.DUMP_FORMAT,
578 point, result
579 )
580 # Check it is in the exclusions list now
581 if result and result in self.exclusions:
582 return self.get_next_point_on_sequence(result)
583 return result
584
585 def get_first_point(
586 self,
587 point: ISO8601Point
588 ) -> Optional[ISO8601Point]:
589 """Return the first point >= to point, or None if out of bounds."""
590 with contextlib.suppress(KeyError):
591 return ISO8601Point(self._cached_first_point_values[point.value])
592 p_iso_point = point_parse(point.value)
593 for recurrence_iso_point in self.recurrence:
594 if recurrence_iso_point >= p_iso_point:
595 first_point_value = str(recurrence_iso_point)
596 ret = ISO8601Point(first_point_value)
597 # Check multiple exclusions
598 if ret and ret in self.exclusions:
599 return self.get_next_point_on_sequence(ret)
600 if (len(self._cached_first_point_values) >
601 self._MAX_CACHED_POINTS):
602 self._cached_first_point_values.popitem()
603 self._cached_first_point_values[point.value] = (
604 first_point_value)
605 return ret
606 return None
607
608 def get_start_point(self):
609 """Return the first point in this sequence, or None."""
610 for recurrence_iso_point in self.recurrence:
611 point = ISO8601Point(str(recurrence_iso_point))
612 # Check for multiple exclusions
613 if not self.exclusions or point not in self.exclusions:
614 return point
615 return None
616
617 def get_stop_point(self):
618 """Return the last point in this sequence, or None if unbounded."""
619 if (self.recurrence.repetitions is not None or (
620 (self.recurrence.start_point is not None or
621 self.recurrence.min_point is not None) and
622 (self.recurrence.end_point is not None or
623 self.recurrence.max_point is not None))):
624 curr = None
625 prev = None
626 for recurrence_iso_point in self.recurrence:
627 prev = curr
628 curr = recurrence_iso_point
629 ret = ISO8601Point(str(curr))
630 if self.exclusions and ret in self.exclusions:
631 return ISO8601Point(str(prev))
632 return ret
633 return None
634
635 def __eq__(self, other):
636 # Return True if other (sequence) is equal to self.
637 if self.TYPE != other.TYPE:
638 return False
639 if self.value == other.value:
640 return True
641 return False
642
643 def __lt__(self, other):
644 return self.value < other.value
645
646 def __str__(self):
647 return self.value
648
649 def __repr__(self) -> str:
650 return f"<{type(self).__name__} {self.value}>"
651
652 def __hash__(self) -> int:
653 return hash(self.value)
654
655
656 def _get_old_anchor_step_recurrence(anchor, step, start_point):
657 """Return a string representing an old-format recurrence translation."""
658 anchor_point = ISO8601Point.from_nonstandard_string(anchor)
659 # We may need to adjust the anchor downwards if it is ahead of the start.
660 if start_point is not None:
661 while anchor_point >= start_point + step:
662 anchor_point -= step
663 return str(anchor_point) + "/" + str(step)
664
665
666 def ingest_time(value: str, now: Optional[str] = None) -> str:
667 """Handle relative, truncated and prev/next cycle points.
668
669 Args:
670 value: The string containing the previous()/next() stuff.
671 now: A time point to use as the context for resolving the value.
672 """
673 # remove extraneous whitespace from cycle point
674 value = value.replace(" ", "")
675 parser = WorkflowSpecifics.point_parser
676
677 # integer point or old-style date-time cycle point format
678 is_integer = bool(re.match(r"\d+$", value))
679 # iso8601 expanded year
680 is_expanded = (
681 (value.startswith("-") or value.startswith("+"))
682 and "P" not in value
683 )
684 # previous() or next()
685 is_prev_next = "next" in value or "previous" in value
686 # offset from now (±P...)
687 is_offset = value.startswith("P") or value.startswith("-P")
688
689 if (
690 is_integer
691 or is_expanded
692 ):
693 # we don't need to do any fancy processing
694 return value
695
696 # parse the timepoint if needed
697 if is_prev_next or is_offset:
698 # `value` isn't necessarily valid ISO8601
699 timepoint = None
700 is_truncated = None
701 else:
702 timepoint = parser.parse(value)
703 # missing date-time components off the front (e.g. 01T00)
704 is_truncated = timepoint.truncated
705
706 if not (is_prev_next or is_offset or is_truncated):
707 return value
708
709 if now is None:
710 now = get_current_time_string()
711 now_point = parser.parse(now)
712
713 # correct for year in 'now' if year is the only date unit specified -
714 # https://github.com/cylc/cylc-flow/issues/4805#issuecomment-1103928604
715 if re.search(r"\(-\d{2}[);T]", value):
716 now_point += Duration(years=1)
717 # likewise correct for month if year and month are the only date units
718 elif re.search(r"\(-\d{4}[);T]", value):
719 now_point += Duration(months=1)
720
721 # perform whatever transformation is required
722 offset = None
723 if is_prev_next:
724 cycle_point, offset = prev_next(value, now_point, parser)
725 elif is_offset:
726 cycle_point = now_point
727 offset = value
728 else: # is_truncated
729 cycle_point = now_point + timepoint
730
731 if offset is not None:
732 # add/subtract offset duration to/from chosen timepoint
733 duration_parser = WorkflowSpecifics.interval_parser
734 offset = offset.replace('+', '')
735 cycle_point += duration_parser.parse(offset)
736
737 return str(cycle_point)
738
739
740 def prev_next(
741 value: str, now: 'TimePoint', parser: 'TimePointParser'
742 ) -> Tuple['TimePoint', Optional[str]]:
743 """Handle previous() and next() syntax.
744
745 Args:
746 value: The string containing the previous()/next() stuff.
747 now: A time point to use as the context for resolving the value.
748 parser: A time point parser.
749
750 Returns
751 (cycle point, offset)
752 """
753 # are we in gregorian mode (or some other eccentric calendar
754 if CALENDAR.mode != Calendar.MODE_GREGORIAN:
755 raise CylcConfigError(
756 'previous()/next() syntax must be used with integer or gregorian'
757 f' cycling modes ("{value}")'
758 )
759
760 # break down cycle point into constituent parts.
761 direction, tmp = value.split("(")
762 offset: Optional[str]
763 tmp, offset = tmp.split(")")
764
765 offset = offset.strip() or None
766
767 str_points: List[str] = tmp.split(";")
768 timepoints: List['TimePoint'] = []
769
770 # for use with 'previous' below.
771 go_back = {
772 "minute_of_hour": "PT1M",
773 "hour_of_day": "PT1H",
774 "day_of_week": "P1D",
775 "day_of_month": "P1D",
776 "day_of_year": "P1D",
777 "week_of_year": "P1W",
778 "month_of_year": "P1M",
779 "year_of_decade": "P1Y",
780 "decade_of_century": "P10Y",
781 "year_of_century": "P1Y",
782 "century": "P100Y"
783 }
784
785 for my_time in str_points:
786 try:
787 parsed_point = parser.parse(my_time.strip())
788 except ISO8601SyntaxError as exc:
789 raise exc
790 except ValueError:
791 # If list is accidentally comma
792 suggest = my_time.replace(',', ';')
793 raise WorkflowConfigError(
794 f'Invalid offset: {my_time}:'
795 f' Offset lists are semicolon separated, try {suggest}'
796 ) from None
797
798 timepoints.append(parsed_point + now)
799
800 if direction == 'previous':
801 # for 'previous' determine next largest unit,
802 # from go_back dict (defined outside 'for' loop), and
803 # subtract 1 of it from each timepoint
804 duration_parser = WorkflowSpecifics.interval_parser
805 next_unit = parsed_point.get_smallest_missing_property_name()
806
807 timepoints[-1] -= duration_parser.parse(go_back[next_unit])
808
809 my_diff = [abs(my_time - now) for my_time in timepoints]
810
811 cycle_point = timepoints[my_diff.index(min(my_diff))]
812
813 # ensure truncated dates do not have time from 'now' included' -
814 # https://github.com/metomi/isodatetime/issues/212
815 if 'T' not in value.split(')')[0]:
816 # NOTE: Strictly speaking we shouldn't forcefully mutate TimePoints
817 # in this way as they're meant to be immutable since
818 # https://github.com/metomi/isodatetime/pull/165, however it
819 # should be ok as long as the TimePoint is not used as a dict key and
820 # we don't call any of the TimePoint's cached methods until after we've
821 # finished mutating it.
822 cycle_point._hour_of_day = 0
823 cycle_point._minute_of_hour = 0
824 cycle_point._second_of_minute = 0
825 # likewise ensure month and day from 'now' are not included
826 # where they did not appear in the truncated datetime
827 if re.search(r"\(-\d{2}[);T]", value):
828 # case 1 - year only
829 cycle_point._month_of_year = 1
830 cycle_point._day_of_month = 1
831 elif re.search(r"\(-(-\d{2}|\d{4})[;T)]", value):
832 # case 2 - month only or year and month
833 cycle_point._day_of_month = 1
834
835 return cycle_point, offset
836
837
838 def init_from_cfg(cfg):
839 """Initialise global variables (yuk) based on the configuration."""
840 num_expanded_year_digits = cfg['scheduler'][
841 'cycle point num expanded year digits']
842 time_zone = cfg['scheduler']['cycle point time zone']
843 custom_dump_format = cfg['scheduler']['cycle point format']
844 assume_utc = cfg['scheduler']['UTC mode']
845 cycling_mode = cfg['scheduling']['cycling mode']
846
847 init(
848 num_expanded_year_digits=num_expanded_year_digits,
849 custom_dump_format=custom_dump_format,
850 time_zone=time_zone,
851 assume_utc=assume_utc,
852 cycling_mode=cycling_mode
853 )
854
855
856 def init(num_expanded_year_digits=0, custom_dump_format=None, time_zone=None,
857 assume_utc=False, cycling_mode=None):
858 """Initialise workflow-setup-specific information."""
859 if cycling_mode in Calendar.default().MODES:
860 Calendar.default().set_mode(cycling_mode)
861
862 if time_zone is None:
863 if assume_utc:
864 time_zone = "Z"
865 time_zone_hours_minutes = (0, 0)
866 else:
867 time_zone = get_local_time_zone_format(TimeZoneFormatMode.reduced)
868 time_zone_hours_minutes = get_local_time_zone()
869 else:
870 time_zone_hours_minutes = TimePointDumper().get_time_zone(time_zone)
871 WorkflowSpecifics.ASSUMED_TIME_ZONE = time_zone_hours_minutes
872 WorkflowSpecifics.NUM_EXPANDED_YEAR_DIGITS = num_expanded_year_digits
873 if custom_dump_format is None:
874 if num_expanded_year_digits > 0:
875 WorkflowSpecifics.DUMP_FORMAT = (
876 EXPANDED_DATE_TIME_FORMAT + time_zone
877 )
878 else:
879 WorkflowSpecifics.DUMP_FORMAT = DATE_TIME_FORMAT + time_zone
880 else:
881 WorkflowSpecifics.DUMP_FORMAT = custom_dump_format
882 if "+X" not in custom_dump_format and num_expanded_year_digits:
883 raise IllegalValueError(
884 'cycle point format',
885 ('cylc', 'cycle point format'),
886 WorkflowSpecifics.DUMP_FORMAT
887 )
888
889 WorkflowSpecifics.iso8601_parsers = CylcTimeParser.initiate_parsers(
890 dump_format=WorkflowSpecifics.DUMP_FORMAT,
891 num_expanded_year_digits=num_expanded_year_digits,
892 assumed_time_zone=WorkflowSpecifics.ASSUMED_TIME_ZONE
893 )
894
895 (WorkflowSpecifics.point_parser,
896 WorkflowSpecifics.interval_parser,
897 WorkflowSpecifics.recurrence_parser) = WorkflowSpecifics.iso8601_parsers
898
899 WorkflowSpecifics.abbrev_util = CylcTimeParser(
900 None, None, WorkflowSpecifics.iso8601_parsers
901 )
902 return WorkflowSpecifics
903
904
905 def get_dump_format() -> str:
906 """Return cycle point string dump format."""
907 return WorkflowSpecifics.DUMP_FORMAT
908
909
910 def get_point_relative(offset_string, base_point):
911 """Create a point from offset_string applied to base_point."""
912 try:
913 operator = '+'
914 base_point_relative = base_point
915 for part in re.split(r'(\+|-)', offset_string):
916 if part == '+' or part == '-':
917 operator = part
918 elif part != '':
919 interval = interval_parse(part)
920 if operator == '-':
921 interval *= -1
922 base_point_relative += ISO8601Interval(str(interval))
923 return base_point_relative
924 except IsodatetimeError:
925 # It's a truncated time point rather than an interval
926 return ISO8601Point(str(
927 WorkflowSpecifics.abbrev_util.parse_timepoint(
928 offset_string, context_point=point_parse(base_point.value))
929 ))
930
931
932 def interval_parse(interval_string):
933 """Parse an interval_string into a proper Duration class."""
934 try:
935 return _interval_parse(interval_string)
936 except Exception:
937 try:
938 return -1 * _interval_parse(interval_string.replace("-", "", 1))
939 except Exception:
940 return _interval_parse(interval_string.replace("+", "", 1))
941
942
943 def is_offset_absolute(offset_string):
944 """Return True if offset_string is a point rather than an interval."""
945 try:
946 interval_parse(offset_string)
947 except Exception:
948 return True
949 else:
950 return False
951
952
953 @lru_cache(10000)
954 def _interval_parse(interval_string):
955 """Parse an interval_string into a proper Duration object."""
956 return WorkflowSpecifics.interval_parser.parse(interval_string)
957
958
959 def point_parse(point_string: str) -> 'TimePoint':
960 """Parse a point_string into a proper TimePoint object."""
961 return _point_parse(
962 point_string,
963 WorkflowSpecifics.DUMP_FORMAT,
964 WorkflowSpecifics.ASSUMED_TIME_ZONE
965 )
966
967
968 @lru_cache(10000)
969 def _point_parse(point_string: str, _dump_fmt, _tz) -> 'TimePoint':
970 """Parse a point_string into a proper TimePoint object.
971
972 Args:
973 point_string: The string to parse.
974 _dump_fmt: Dump format (only used to avoid invalid cache hits).
975 _tz: Cycle point time zone (only used to avoid invalid cache hits).
976 """
977 if "%" in WorkflowSpecifics.DUMP_FORMAT:
978 # May be a custom not-quite ISO 8601 dump format.
979 with contextlib.suppress(IsodatetimeError):
980 return WorkflowSpecifics.point_parser.strptime(
981 point_string, WorkflowSpecifics.DUMP_FORMAT)
982 # Attempt to parse it in ISO 8601 format.
983 return WorkflowSpecifics.point_parser.parse(point_string)