Debian Codegraph @

cylc/flow/cycling/__init__.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 """This module provides base classes for cycling data objects."""
18
19 from abc import ABCMeta, abstractmethod
20
21 from cylc.flow.exceptions import CyclerTypeError
22
23
24 def parse_exclusion(expr: str):
25 count = expr.count('!')
26 if count == 0:
27 return expr, None
28 elif count > 1:
29 raise Exception("'%s': only one set of exclusions per expression "
30 "permitted" % expr)
31 else:
32 remainder, exclusions = expr.split('!')
33 if (
34 ',' in exclusions
35 and (
36 not exclusions.strip().startswith('(')
37 or not exclusions.strip().endswith(')')
38 )
39 ):
40 raise Exception(
41 f"'{exclusions}': a list of exclusions must be enclosed in"
42 " parentheses."
43 )
44
45 exclusions = exclusions.translate(str.maketrans('', '', ' ()'))
46 exclusions = exclusions.split(',')
47 return remainder.strip(), exclusions
48
49
50 class PointBase(metaclass=ABCMeta):
51
52 """The abstract base class for single points in a cycler sequence.
53
54 Points should be based around a string value.
55
56 Subclasses should provide values for TYPE and TYPE_SORT_KEY.
57 They should also provide self._cmp, self.sub, self.add, and
58 self.eq methods which should behave as __cmp__, __sub__,
59 etc standard comparison methods. Note: "_cmp" not "cmp".
60
61 Subclasses may also provide an overridden self.standardise
62 method to reprocess their value into a standard form.
63
64 """
65
66 __slots__ = ('value')
67
68 @property
69 @abstractmethod
70 def TYPE(self) -> str:
71 """Cycling type of this point."""
72
73 @property
74 @abstractmethod
75 def TYPE_SORT_KEY(self) -> int:
76 """Used for comparison operations between different PointBase-derived
77 class instances."""
78
79 def __init__(self, value: str):
80 if not isinstance(value, str):
81 raise TypeError(type(value))
82 self.value = value
83
84 @abstractmethod
85 def add(self, other):
86 """Add other (interval) to self, returning a point."""
87 pass
88
89 @abstractmethod
90 def _cmp(self, other) -> int:
91 """Compare self to other point, returning a 'cmp'-like result."""
92 pass
93
94 def standardise(self, allow_truncated: bool = True) -> 'PointBase':
95 """Format self.value into a standard representation and check it.
96
97 Args:
98 allow_truncated:
99 If True, then truncated points (i.e. any point with context
100 missing off the front) will be tollerated, if False, truncated
101 points will cause an exception to be raised.
102 """
103 raise NotImplementedError
104
105 @abstractmethod
106 def sub(self, other):
107 """Subtract other (interval or point), returning a point or interval.
108
109 If other is a Point, return an Interval.
110 If other is an Interval, return a Point.
111
112 ('Point' here is a PointBase-derived object, and 'Interval' an
113 IntervalBase-derived object)
114
115 """
116 pass
117
118 def __str__(self):
119 # Stringify.
120 return self.value
121
122 __repr__ = __str__
123
124 def __cmp__(self, other: 'PointBase') -> int:
125 # Compare to other point.
126 # TODO: refactor as __cmp__ not used in python3
127 if other is None:
128 return -1
129 if not isinstance(other, PointBase):
130 return NotImplemented
131 # Note: apparently we can compare different subclasses of PointBase:
132 if self.TYPE != other.TYPE:
133 return cmp(self.TYPE_SORT_KEY, other.TYPE_SORT_KEY)
134 if self.value == other.value:
135 return 0
136 return self._cmp(other)
137
138 def __eq__(self, other: object) -> bool:
139 if isinstance(other, self.__class__):
140 return self.__cmp__(other) == 0
141 return NotImplemented
142
143 def __lt__(self, other: 'PointBase') -> bool:
144 return self.__cmp__(other) == -1
145
146 def __le__(self, other: 'PointBase') -> bool:
147 return self.__cmp__(other) <= 0
148
149 def __gt__(self, other: 'PointBase') -> bool:
150 return self.__cmp__(other) == 1
151
152 def __ge__(self, other: 'PointBase') -> bool:
153 return self.__cmp__(other) >= 0
154
155 def __hash__(self) -> int:
156 return hash(self.value)
157
158 def __sub__(self, other):
159 # Subtract other (point or interval) from self.
160 if self.TYPE != other.TYPE:
161 raise CyclerTypeError(self.TYPE, self, other.TYPE, other)
162 return self.sub(other)
163
164 def __add__(self, other):
165 # Add other (point or interval) from self.
166 if self.TYPE != other.TYPE:
167 raise CyclerTypeError(self.TYPE, self, other.TYPE, other)
168 return self.add(other)
169
170
171 class IntervalBase(metaclass=ABCMeta):
172
173 """An interval separating points in a cycler sequence.
174
175 Intervals should be based around a string value.
176
177 Subclasses should provide values for TYPE and TYPE_SORT_KEY.
178 They should also provide self._cmp, self.sub, self.add,
179 self.__mul__, self.__abs__ methods which should
180 behave as __cmp__, __sub__, etc standard comparison methods.
181
182 They can also just override the provided comparison methods (such
183 as __cmp__) instead.
184
185 Note: "_cmp" not "cmp", etc. They should also provide:
186 * self.get_null, which is a method to extract the null interval of
187 this type.
188 * self.get_null_offset, which is a method to extract a null offset
189 relative to a PointBase object.
190
191 Subclasses may also provide an overridden self.standardise
192 method to reprocess their value into a standard form.
193
194 """
195
196 __slots__ = ('value')
197
198 @property
199 @abstractmethod
200 def TYPE(self) -> str:
201 """Cycling type of this interval."""
202
203 @property
204 @abstractmethod
205 def TYPE_SORT_KEY(self) -> int:
206 """Used for comparison operations between different
207 IntervalBase-derived class instances."""
208
209 @classmethod
210 @abstractmethod
211 def get_null(cls):
212 """Return a null interval."""
213 pass
214
215 @abstractmethod
216 def __abs__(self):
217 # Return an interval with absolute values for all properties.
218 pass
219
220 @abstractmethod
221 def __mul__(self, factor):
222 # Return an interval with all properties multiplied by factor.
223 pass
224
225 def __init__(self, value):
226 if not isinstance(value, str):
227 raise TypeError(type(value))
228 self.value = value
229
230 @abstractmethod
231 def add(self, other):
232 """Add other to self, returning a Point or Interval.
233
234 If other is a Point, return a Point.
235 If other is an Interval, return an Interval..
236
237 ('Point' here is a PointBase-derived object, and 'Interval' an
238 IntervalBase-derived object)
239
240 """
241 pass
242
243 @abstractmethod
244 def _cmp(self, other):
245 """Compare self to other (interval), returning a 'cmp'-like result."""
246 pass
247
248 def standardise(self):
249 """Format self.value into a standard representation."""
250 return self
251
252 @abstractmethod
253 def sub(self, other):
254 """Subtract other (interval) from self; return an interval."""
255 pass
256
257 def __str__(self) -> str:
258 # Stringify.
259 return self.value
260
261 def __repr__(self) -> str:
262 return f"<{type(self).__name__} {self}>"
263
264 def __add__(self, other):
265 # Add other (point or interval) to self.
266 if self.TYPE != other.TYPE:
267 raise CyclerTypeError(self.TYPE, self, other.TYPE, other)
268 return self.add(other)
269
270 def __cmp__(self, other: 'IntervalBase') -> int:
271 # Compare self to other (interval).
272 # TODO: refactor as __cmp__ not used in python3
273 if other is None:
274 return -1
275 if not isinstance(other, IntervalBase):
276 return NotImplemented
277 # Note: apparently we can compare different subclasses of IntervalBase:
278 if self.TYPE != other.TYPE:
279 return cmp(self.TYPE_SORT_KEY, other.TYPE_SORT_KEY)
280 if self.value == other.value:
281 return 0
282 return self._cmp(other)
283
284 def __eq__(self, other: object) -> bool:
285 if isinstance(other, self.__class__):
286 return self.__cmp__(other) == 0
287 return NotImplemented
288
289 def __lt__(self, other: 'IntervalBase') -> bool:
290 return self.__cmp__(other) == -1
291
292 def __le__(self, other: 'IntervalBase') -> bool:
293 return self.__cmp__(other) <= 0
294
295 def __gt__(self, other: 'IntervalBase') -> bool:
296 return self.__cmp__(other) == 1
297
298 def __ge__(self, other: 'IntervalBase') -> bool:
299 return self.__cmp__(other) >= 0
300
301 def __hash__(self) -> int:
302 return hash(self.value)
303
304 def __sub__(self, other):
305 # Subtract other (interval or point) from self.
306 if self.TYPE != other.TYPE:
307 raise CyclerTypeError(self.TYPE, self, other.TYPE, other)
308 return self.sub(other)
309
310 def __neg__(self):
311 # Return an interval with all properties multiplied by -1.
312 return self * -1
313
314
315 class SequenceBase(metaclass=ABCMeta):
316
317 """The abstract base class for cycler sequences.
318
319 Subclasses should accept a sequence-specific string, a
320 start context string, and a stop context string as
321 constructor arguments.
322
323 Subclasses should provide values for TYPE and TYPE_SORT_KEY.
324 They should also provide get_async_expr, get_interval,
325 get_offset & set_offset (deprecated), is_on_sequence,
326 get_nearest_prev_point, get_next_point,
327 get_next_point_on_sequence, get_first_point
328 get_start_point, and get_stop_point.
329
330 They should also provide a self.__eq__ implementation
331 which should return whether a SequenceBase-derived object
332 is equal to another (represents the same set of points).
333
334 """
335
336 __slots__ = ()
337
338 @property
339 @abstractmethod
340 def TYPE(self) -> str:
341 """Cycling type of this sequence."""
342
343 @property
344 @abstractmethod
345 def TYPE_SORT_KEY(self) -> int:
346 """Used for comparison operations between different
347 SequenceBase-derived class instances."""
348
349 @classmethod
350 @abstractmethod # Note: stacked decorator not strictly enforced in Py2.x
351 def get_async_expr(cls, start_point=0):
352 """Express a one-off sequence at the initial cycle point."""
353 pass
354
355 @abstractmethod
356 def __init__(self, sequence_string, context_start, context_stop=None):
357 """Parse sequence string according to context point strings."""
358 pass
359
360 @abstractmethod
361 def get_interval(self):
362 """Return the cycling interval of this sequence."""
363 pass
364
365 @abstractmethod
366 def get_offset(self):
367 """Deprecated: return the offset used for this sequence."""
368 pass
369
370 @abstractmethod
371 def set_offset(self, i_offset):
372 """Deprecated: alter state to offset the entire sequence."""
373 pass
374
375 # NOTE: not using @abstractmethod because we need to
376 # patch this method for caching purposes
377 def is_on_sequence(self, point):
378 """Is point on-sequence, disregarding bounds?"""
379 raise NotImplementedError
380
381 @abstractmethod
382 def is_valid(self, point):
383 """Is point on-sequence and in-bounds?"""
384 pass
385
386 @abstractmethod
387 def get_prev_point(self, point):
388 """Return the previous point < point, or None if out of bounds."""
389 pass
390
391 @abstractmethod
392 def get_nearest_prev_point(self, point):
393 """Return the largest point < some arbitrary point."""
394 pass
395
396 @abstractmethod
397 def get_next_point(self, point):
398 """Return the next point > point, or None if out of bounds."""
399 pass
400
401 @abstractmethod
402 def get_next_point_on_sequence(self, point):
403 """Return the next point > point assuming that point is on-sequence,
404 or None if out of bounds."""
405 pass
406
407 @abstractmethod
408 def get_first_point(self, point):
409 """Return the first point >= to point, or None if out of bounds."""
410 pass
411
412 @abstractmethod
413 def get_start_point(self):
414 """Return the first point of this sequence."""
415 pass
416
417 @abstractmethod
418 def get_stop_point(self):
419 """Return the last point of this sequence, or None if unbounded."""
420 pass
421
422 @abstractmethod
423 def __eq__(self, other) -> bool:
424 # Return True if other (sequence) is equal to self.
425 pass
426
427 @abstractmethod
428 def __hash__(self) -> int:
429 pass
430
431
432 class ExclusionBase(metaclass=ABCMeta):
433 """A collection of points or sequences that are treated in an
434 exclusionary manner"""
435 __slots__ = ('exclusion_sequences', 'exclusion_points',
436 'exclusion_start_point', 'exclusion_end_point')
437
438 def __init__(self, start_point, end_point=None):
439 """creates an exclusions object that can contain integer points
440 or integer sequences to be used as excluded points."""
441 self.exclusion_sequences = []
442 self.exclusion_points = []
443 self.exclusion_start_point = start_point
444 self.exclusion_end_point = end_point
445
446 @abstractmethod
447 def build_exclusions(self, excl_points):
448 """Constructs the set of exclusion sequences or points"""
449 pass
450
451 def __contains__(self, point):
452 """Return True if the provided point is in this exclusion.
453
454 Args:
455 point (PointBase): The cycle point to check.
456
457 """
458 if point in self.exclusion_points:
459 return True
460 if any(seq.is_valid(point) for seq in self.exclusion_sequences):
461 return True
462 return False
463
464 def __getitem__(self, key):
465 """Allows indexing of the exclusion object"""
466 return self.exclusion_sequences[key]
467
468 def __str__(self):
469 returns = []
470 for point in sorted(self.exclusion_points):
471 returns.append(str(point))
472 for sequence in self.exclusion_sequences:
473 returns.append(str(sequence))
474 ret = ','.join(returns)
475 if ',' in ret:
476 ret = '(' + ret + ')'
477 return ret
478
479
480 def cmp(self, other):
481 """Temporary replacement for the Python2 cmp function."""
482 if self == other:
483 return 0
484 if self < other:
485 return -1
486 return 1