Coverage for tests/test_timespan.py: 9%
163 statements
« prev ^ index » next coverage.py v7.5.1, created at 2024-05-07 02:46 -0700
« prev ^ index » next coverage.py v7.5.1, created at 2024-05-07 02:46 -0700
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
28import itertools
29import unittest
30import warnings
32import astropy.time
33import astropy.utils.exceptions
35# As of astropy 4.2, the erfa interface is shipped independently and
36# ErfaWarning is no longer an AstropyWarning
37try:
38 import erfa
39except ImportError:
40 erfa = None
42import pydantic
43from lsst.daf.butler import Timespan
44from lsst.daf.butler.time_utils import TimeConverter
47class TimespanTestCase(unittest.TestCase):
48 """Tests for the `Timespan` class.
50 Test coverage for the `TimespanDatabaseRepresentation` classes is handled
51 by the tests for `Database` and its subclasses.
52 """
54 def setUp(self):
55 start = astropy.time.Time("2020-01-01T00:00:00", format="isot", scale="tai")
56 offset = astropy.time.TimeDelta(60, format="sec")
57 self.timestamps = [start + offset * n for n in range(3)]
58 self.timespans = [Timespan(begin=None, end=None)]
59 self.timespans.extend(Timespan(begin=None, end=t) for t in self.timestamps)
60 self.timespans.extend(Timespan(begin=t, end=None) for t in self.timestamps)
61 self.timespans.extend(Timespan(begin=t, end=t) for t in self.timestamps)
62 self.timespans.extend(Timespan(begin=a, end=b) for a, b in itertools.combinations(self.timestamps, 2))
64 def testEmpty(self):
65 """Test various ways to construct an empty timespan, and that
66 operations on empty timespans yield the expected behavior.
67 """
68 self.assertEqual(
69 Timespan.makeEmpty(),
70 Timespan(Timespan.EMPTY, Timespan.EMPTY),
71 )
72 self.assertEqual(
73 Timespan.makeEmpty(),
74 Timespan(self.timestamps[1], self.timestamps[0]),
75 )
76 self.assertEqual(
77 Timespan.makeEmpty(),
78 Timespan(Timespan.EMPTY, self.timestamps[0]),
79 )
80 self.assertEqual(
81 Timespan.makeEmpty(),
82 Timespan(self.timestamps[0], Timespan.EMPTY),
83 )
84 self.assertEqual(
85 Timespan.makeEmpty(), Timespan(self.timestamps[0], self.timestamps[0], padInstantaneous=False)
86 )
87 empty = Timespan.makeEmpty()
88 for t in self.timestamps:
89 with self.subTest(t=str(t)):
90 self.assertFalse(empty < t)
91 self.assertFalse(empty > t)
92 self.assertFalse(t < empty)
93 self.assertFalse(t > empty)
94 self.assertFalse(empty.contains(t))
95 for t in self.timespans:
96 with self.subTest(t=str(t)):
97 self.assertTrue(t.contains(empty))
98 self.assertFalse(t.overlaps(empty))
99 self.assertFalse(empty.overlaps(t))
100 self.assertEqual(empty.contains(t), t.isEmpty())
101 self.assertFalse(empty < t)
102 self.assertFalse(t < empty)
103 self.assertFalse(empty > t)
104 self.assertFalse(t > empty)
106 def testFromInstant(self):
107 """Test construction of instantaneous timespans."""
108 self.assertEqual(
109 Timespan.fromInstant(self.timestamps[0]), Timespan(self.timestamps[0], self.timestamps[0])
110 )
112 def testInvalid(self):
113 """Test that we reject timespans that should not exist."""
114 with self.assertRaises(ValueError):
115 Timespan(TimeConverter().max_time, None)
116 with self.assertRaises(ValueError):
117 Timespan(TimeConverter().max_time, TimeConverter().max_time)
118 with self.assertRaises(ValueError):
119 Timespan(None, TimeConverter().epoch)
120 with self.assertRaises(ValueError):
121 Timespan(TimeConverter().epoch, TimeConverter().epoch)
122 t = TimeConverter().nsec_to_astropy(TimeConverter().max_nsec - 1)
123 with self.assertRaises(ValueError):
124 Timespan(t, t)
125 with self.assertRaises(ValueError):
126 Timespan.fromInstant(t)
128 def testStrings(self):
129 """Test __str__ against expected values and __repr__ with eval
130 round-tripping.
131 """
132 for ts in self.timespans:
133 # Uncomment the next line and run this test directly for the most
134 # important test: human inspection.
135 # print(str(ts), repr(ts))
136 if ts.isEmpty():
137 self.assertEqual("(empty)", str(ts))
138 else:
139 self.assertIn(", ", str(ts))
140 if ts.begin is None:
141 self.assertTrue(str(ts).startswith("(-∞, "))
142 else:
143 self.assertTrue(str(ts).startswith(f"[2020-01-01T00:{ts.begin.tai.strftime('%M')}:00, "))
144 if ts.end is None:
145 self.assertTrue(str(ts).endswith(", ∞)"))
146 else:
147 self.assertTrue(str(ts).endswith(f", 2020-01-01T00:{ts.end.tai.strftime('%M')}:00)"))
148 self.assertEqual(eval(repr(ts)), ts)
150 def testOperationConsistency(self):
151 """Test that overlaps, contains, intersection, and difference are
152 consistent.
153 """
154 for a, b in itertools.combinations_with_replacement(self.timespans, 2):
155 with self.subTest(a=str(a), b=str(b)):
156 c1 = a.intersection(b)
157 c2 = b.intersection(a)
158 diffs1 = tuple(a.difference(b))
159 diffs2 = tuple(b.difference(a))
160 if a == b:
161 self.assertFalse(diffs1)
162 self.assertFalse(diffs2)
163 self.assertTrue(a.contains(b))
164 self.assertTrue(b.contains(a))
165 if a.contains(b):
166 self.assertTrue(a.overlaps(b) or b.isEmpty())
167 self.assertFalse(diffs2)
168 if b.contains(a):
169 self.assertTrue(b.overlaps(a) or a.isEmpty())
170 self.assertFalse(diffs1)
171 if diffs1 is not None:
172 for t in diffs1:
173 self.assertTrue(a.overlaps(t))
174 self.assertFalse(b.overlaps(t))
175 if diffs2 is not None:
176 for t in diffs2:
177 self.assertTrue(b.overlaps(t))
178 self.assertFalse(a.overlaps(t))
179 self.assertEqual(c1, c2)
180 if a.overlaps(b):
181 self.assertTrue(b.overlaps(a))
182 self.assertFalse(c1.isEmpty())
183 else:
184 self.assertTrue(a < b or a > b or a.isEmpty() or b.isEmpty())
185 self.assertFalse(b.overlaps(a))
186 self.assertTrue(c1.isEmpty())
187 if diffs1 is not None:
188 self.assertEqual(diffs1, (a,))
189 if diffs2 is not None:
190 self.assertEqual(diffs2, (b,))
192 def testPrecision(self):
193 """Test that we only use nanosecond precision for equality."""
194 ts1 = self.timespans[-1]
195 ts2 = Timespan(begin=ts1.begin + astropy.time.TimeDelta(1e-10, format="sec"), end=ts1.end)
196 self.assertEqual(ts1, ts2)
198 self.assertEqual(Timespan(begin=None, end=None), Timespan(begin=None, end=None))
199 self.assertEqual(Timespan(begin=None, end=ts1.end), Timespan(begin=None, end=ts1.end))
201 ts2 = Timespan(begin=ts1.begin + astropy.time.TimeDelta(1e-8, format="sec"), end=ts1.end)
202 self.assertNotEqual(ts1, ts2)
204 ts2 = Timespan(begin=None, end=ts1.end)
205 self.assertNotEqual(ts1, ts2)
207 t1 = Timespan(
208 begin=astropy.time.Time(2456461.0, val2=0.06580758101851847, format="jd", scale="tai"),
209 end=astropy.time.Time(2456461.0, val2=0.06617994212962963, format="jd", scale="tai"),
210 )
211 t2 = Timespan(
212 begin=astropy.time.Time(2456461.0, val2=0.06580758101851858, format="jd", scale="tai"),
213 end=astropy.time.Time(2456461.0, val2=0.06617994212962963, format="jd", scale="tai"),
214 )
215 self.assertEqual(t1, t2)
217 # Ensure that == and != work properly
218 self.assertTrue(t1 == t2, f"Equality of {t1} and {t2}")
219 self.assertFalse(t1 != t2, f"Check != is false for {t1} and {t2}")
221 def testTimescales(self):
222 """Test time scale conversion occurs on comparison."""
223 ts1 = Timespan(
224 begin=astropy.time.Time("2013-06-17 13:34:45.775000", scale="tai", format="iso"),
225 end=astropy.time.Time("2013-06-17 13:35:17.947000", scale="tai", format="iso"),
226 )
227 ts2 = Timespan(
228 begin=astropy.time.Time("2013-06-17T13:34:10.775", scale="utc", format="isot"),
229 end=astropy.time.Time("2013-06-17T13:34:42.947", scale="utc", format="isot"),
230 )
231 self.assertEqual(ts1, ts2, f"Compare {ts1} with {ts2}")
233 def testFuture(self):
234 """Check that we do not get warnings from future dates."""
235 # Astropy will give "dubious year" for UTC five years in the future
236 # so hide these expected warnings from the test output
237 with warnings.catch_warnings():
238 warnings.simplefilter("ignore", category=astropy.utils.exceptions.AstropyWarning)
239 if erfa is not None:
240 warnings.simplefilter("ignore", category=erfa.ErfaWarning)
241 ts1 = Timespan(
242 begin=astropy.time.Time(self.timestamps[0], scale="utc", format="iso"),
243 end=astropy.time.Time("2099-06-17 13:35:17.947000", scale="utc", format="iso"),
244 )
245 ts2 = Timespan(
246 begin=astropy.time.Time(self.timestamps[0], scale="utc", format="iso"),
247 end=astropy.time.Time("2099-06-17 13:35:17.947000", scale="utc", format="iso"),
248 )
250 # unittest can't test for no warnings so we run the test and
251 # trigger our own warning and count all the warnings
252 with self.assertWarns(Warning) as cm:
253 self.assertEqual(ts1, ts2)
254 warnings.warn("deliberate", stacklevel=1)
255 self.assertEqual(str(cm.warning), "deliberate")
257 def test_serialization(self):
258 ts = Timespan(
259 begin=astropy.time.Time("2013-06-17 13:34:45.775000", scale="tai", format="iso"),
260 end=astropy.time.Time("2013-06-17 13:35:17.947000", scale="tai", format="iso"),
261 )
262 adapter = pydantic.TypeAdapter(Timespan)
263 self.assertIn("TAI", adapter.json_schema()["description"])
264 json_roundtripped = adapter.validate_json(adapter.dump_json(ts))
265 self.assertIsInstance(json_roundtripped, Timespan)
266 self.assertEqual(json_roundtripped, ts)
267 python_roundtripped = adapter.validate_python(adapter.dump_python(ts))
268 self.assertIsInstance(json_roundtripped, Timespan)
269 self.assertEqual(python_roundtripped, ts)
270 with self.assertRaises(ValueError):
271 adapter.validate_python(12)
272 with self.assertRaises(ValueError):
273 adapter.validate_json({})
275 def test_day_obs(self):
276 data = (
277 ((20240201, 0), ("2024-02-01T00:00:00.0", "2024-02-02T00:00:00.0")),
278 ((19801011, 3600), ("1980-10-11T01:00:00.0", "1980-10-12T01:00:00.0")),
279 ((20481231, -7200), ("2048-12-30T22:00:00.0", "2048-12-31T22:00:00.0")),
280 ((20481231, 7200), ("2048-12-31T02:00:00.0", "2049-01-01T02:00:00.0")),
281 )
282 for input, output in data:
283 ts1 = Timespan.from_day_obs(input[0], input[1])
284 ts2 = Timespan(
285 begin=astropy.time.Time(output[0], scale="tai", format="isot"),
286 end=astropy.time.Time(output[1], scale="tai", format="isot"),
287 )
288 self.assertEqual(ts1, ts2)
290 with self.assertRaises(ValueError):
291 Timespan.from_day_obs(19690101)
294if __name__ == "__main__":
295 unittest.main()