Coverage for python/lum/clu/processors/interval.py: 54%

28 statements  

« prev     ^ index     » next       coverage.py v7.6.7, created at 2024-11-17 18:41 +0000

1from __future__ import annotations 

2from pydantic import BaseModel, Field 

3import typing 

4 

5__all__ = ["Interval"] 

6 

7class Interval(BaseModel): 

8 """Defines a token or character span""" 

9 start: int = Field(description="The token or character index where the interval begins.") 

10 end: int = Field(description="1 + the index of the last token/character in the span.") 

11 

12 """ 

13 Methods 

14 ------- 

15 contains(that) 

16 Test whether `that` (int or Interval) overlaps with span of this Interval. 

17 

18 overlaps(that) 

19 Test whether this Interval contains another. Equivalent Intervals will overlap. 

20 """ 

21 

22 # def __init__(self, start, end): 

23 # NLPDatum.__init__(self) 

24 # assert (start < end), "Interval start must precede end." 

25 # self.start = start 

26 # self.end = end 

27 

28 # def to_JSON_dict(self): 

29 # return {"start":self.start, "end":self.end} 

30 

31 @property 

32 def size(self) -> int: 

33 """The size of an Interval""" 

34 return self.end - self.start 

35 

36 @property 

37 def __len__(self) -> int: 

38 """The size of an Interval""" 

39 return self.size 

40 

41 def contains(self, other: typing.Union[int, Interval]) -> bool: 

42 """Test whether `other` (int or Interval) overlaps with span of this Interval.""" 

43 if isinstance(other, int): 

44 return self.start <= other <= self.end 

45 # self.__class__ 

46 elif isinstance(other, Interval): 

47 return self.start <= other.start and self.end >= other.end 

48 return False 

49 

50 def __contains__(self, other: typing.Union[int, Interval]): 

51 return self.contains(other) 

52 

53 def overlaps(self, other: typing.Union[int, Interval]) -> bool: 

54 """Test whether this Interval contains another. Equivalent Intervals will overlap.""" 

55 if isinstance(other, int): 

56 return self.start <= other < self.end 

57 # self.__class__ 

58 elif isinstance(other, Interval): 

59 return ((other.start <= self.start < other.end) or (self.start <= other.start < self.end)) 

60 return False