Skip to content

Commit

Permalink
Add fuzzy equality to Timespan
Browse files Browse the repository at this point in the history
Now reports that a timespan is equal if the delta is less than
1ns
  • Loading branch information
timj committed Aug 26, 2020
1 parent 5463da9 commit 45b411f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
18 changes: 18 additions & 0 deletions python/lsst/daf/butler/core/timespan.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,24 @@ def __repr__(self) -> str:
end = tmpl.format(t=self.end) if self.end is not None else None
return f"Timespan(begin={begin}, end={end})"

def __eq__(self, other: Any) -> bool:
# Include some fuzziness in equality because round tripping
# can introduce some drift at the picosecond level
# Butler is okay wih nanosecond precision
if not isinstance(other, type(self)):
return False

def compare_time(t1: Optional[astropy.time.Time], t2: Optional[astropy.time.Time]) -> bool:
if t1 is None and t2 is None:
return True
if t1 is None or t2 is None:
return False

return times_equal(t1, t2)

result = compare_time(self.begin, other.begin) and compare_time(self.end, other.end)
return result

def overlaps(self, other: Timespan) -> Any:
"""Test whether this timespan overlaps another.
Expand Down
21 changes: 21 additions & 0 deletions tests/test_timespan.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,27 @@ def testOperationConsistency(self):
self.assertEqual(diffs1, (a,))
self.assertEqual(diffs2, (b,))

def testPrecision(self):
"""Test that we only use nanosecond precision for equality."""
ts1 = self.timespans[-1]
ts2 = Timespan(begin=ts1.begin + astropy.time.TimeDelta(1e-10, format="sec"), end=ts1.end)
self.assertEqual(ts1, ts2)

self.assertEqual(Timespan(begin=None, end=None), Timespan(begin=None, end=None))
self.assertEqual(Timespan(begin=None, end=ts1.end), Timespan(begin=None, end=ts1.end))

ts2 = Timespan(begin=ts1.begin + astropy.time.TimeDelta(1e-8, format="sec"), end=ts1.end)
self.assertNotEqual(ts1, ts2)

ts2 = Timespan(begin=None, end=ts1.end)
self.assertNotEqual(ts1, ts2)

t1 = Timespan(begin=astropy.time.Time(2456461.0, val2=0.06580758101851847, format="jd", scale="tai"),
end=astropy.time.Time(2456461.0, val2=0.06617994212962963, format="jd", scale="tai"))
t2 = Timespan(begin=astropy.time.Time(2456461.0, val2=0.06580758101851858, format="jd", scale="tai"),
end=astropy.time.Time(2456461.0, val2=0.06617994212962963, format="jd", scale="tai"))
self.assertEqual(t1, t2)

def testTimescales(self):
"""Test time scale conversion occurs on comparison."""
ts1 = Timespan(begin=astropy.time.Time('2013-06-17 13:34:45.775000', scale='tai', format='iso'),
Expand Down

0 comments on commit 45b411f

Please sign in to comment.