Coverage for tests/test_timespan.py: 9%
153 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-04 02:55 -0700
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-04 02:55 -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
42from lsst.daf.butler import Timespan
43from lsst.daf.butler.time_utils import TimeConverter
46class TimespanTestCase(unittest.TestCase):
47 """Tests for the `Timespan` class.
49 Test coverage for the `TimespanDatabaseRepresentation` classes is handled
50 by the tests for `Database` and its subclasses.
51 """
53 def setUp(self):
54 start = astropy.time.Time("2020-01-01T00:00:00", format="isot", scale="tai")
55 offset = astropy.time.TimeDelta(60, format="sec")
56 self.timestamps = [start + offset * n for n in range(3)]
57 self.timespans = [Timespan(begin=None, end=None)]
58 self.timespans.extend(Timespan(begin=None, end=t) for t in self.timestamps)
59 self.timespans.extend(Timespan(begin=t, end=None) for t in self.timestamps)
60 self.timespans.extend(Timespan(begin=t, end=t) for t in self.timestamps)
61 self.timespans.extend(Timespan(begin=a, end=b) for a, b in itertools.combinations(self.timestamps, 2))
63 def testEmpty(self):
64 """Test various ways to construct an empty timespan, and that
65 operations on empty timespans yield the expected behavior.
66 """
67 self.assertEqual(
68 Timespan.makeEmpty(),
69 Timespan(Timespan.EMPTY, Timespan.EMPTY),
70 )
71 self.assertEqual(
72 Timespan.makeEmpty(),
73 Timespan(self.timestamps[1], self.timestamps[0]),
74 )
75 self.assertEqual(
76 Timespan.makeEmpty(),
77 Timespan(Timespan.EMPTY, self.timestamps[0]),
78 )
79 self.assertEqual(
80 Timespan.makeEmpty(),
81 Timespan(self.timestamps[0], Timespan.EMPTY),
82 )
83 self.assertEqual(
84 Timespan.makeEmpty(), Timespan(self.timestamps[0], self.timestamps[0], padInstantaneous=False)
85 )
86 empty = Timespan.makeEmpty()
87 for t in self.timestamps:
88 with self.subTest(t=str(t)):
89 self.assertFalse(empty < t)
90 self.assertFalse(empty > t)
91 self.assertFalse(t < empty)
92 self.assertFalse(t > empty)
93 self.assertFalse(empty.contains(t))
94 for t in self.timespans:
95 with self.subTest(t=str(t)):
96 self.assertTrue(t.contains(empty))
97 self.assertFalse(t.overlaps(empty))
98 self.assertFalse(empty.overlaps(t))
99 self.assertEqual(empty.contains(t), t.isEmpty())
100 self.assertFalse(empty < t)
101 self.assertFalse(t < empty)
102 self.assertFalse(empty > t)
103 self.assertFalse(t > empty)
105 def testFromInstant(self):
106 """Test construction of instantaneous timespans."""
107 self.assertEqual(
108 Timespan.fromInstant(self.timestamps[0]), Timespan(self.timestamps[0], self.timestamps[0])
109 )
111 def testInvalid(self):
112 """Test that we reject timespans that should not exist."""
113 with self.assertRaises(ValueError):
114 Timespan(TimeConverter().max_time, None)
115 with self.assertRaises(ValueError):
116 Timespan(TimeConverter().max_time, TimeConverter().max_time)
117 with self.assertRaises(ValueError):
118 Timespan(None, TimeConverter().epoch)
119 with self.assertRaises(ValueError):
120 Timespan(TimeConverter().epoch, TimeConverter().epoch)
121 t = TimeConverter().nsec_to_astropy(TimeConverter().max_nsec - 1)
122 with self.assertRaises(ValueError):
123 Timespan(t, t)
124 with self.assertRaises(ValueError):
125 Timespan.fromInstant(t)
127 def testStrings(self):
128 """Test __str__ against expected values and __repr__ with eval
129 round-tripping.
130 """
131 for ts in self.timespans:
132 # Uncomment the next line and run this test directly for the most
133 # important test: human inspection.
134 # print(str(ts), repr(ts))
135 if ts.isEmpty():
136 self.assertEqual("(empty)", str(ts))
137 else:
138 self.assertIn(", ", str(ts))
139 if ts.begin is None:
140 self.assertTrue(str(ts).startswith("(-∞, "))
141 else:
142 self.assertTrue(str(ts).startswith(f"[2020-01-01T00:{ts.begin.tai.strftime('%M')}:00, "))
143 if ts.end is None:
144 self.assertTrue(str(ts).endswith(", ∞)"))
145 else:
146 self.assertTrue(str(ts).endswith(f", 2020-01-01T00:{ts.end.tai.strftime('%M')}:00)"))
147 self.assertEqual(eval(repr(ts)), ts)
149 def testOperationConsistency(self):
150 """Test that overlaps, contains, intersection, and difference are
151 consistent.
152 """
153 for a, b in itertools.combinations_with_replacement(self.timespans, 2):
154 with self.subTest(a=str(a), b=str(b)):
155 c1 = a.intersection(b)
156 c2 = b.intersection(a)
157 diffs1 = tuple(a.difference(b))
158 diffs2 = tuple(b.difference(a))
159 if a == b:
160 self.assertFalse(diffs1)
161 self.assertFalse(diffs2)
162 self.assertTrue(a.contains(b))
163 self.assertTrue(b.contains(a))
164 if a.contains(b):
165 self.assertTrue(a.overlaps(b) or b.isEmpty())
166 self.assertFalse(diffs2)
167 if b.contains(a):
168 self.assertTrue(b.overlaps(a) or a.isEmpty())
169 self.assertFalse(diffs1)
170 if diffs1 is not None:
171 for t in diffs1:
172 self.assertTrue(a.overlaps(t))
173 self.assertFalse(b.overlaps(t))
174 if diffs2 is not None:
175 for t in diffs2:
176 self.assertTrue(b.overlaps(t))
177 self.assertFalse(a.overlaps(t))
178 self.assertEqual(c1, c2)
179 if a.overlaps(b):
180 self.assertTrue(b.overlaps(a))
181 self.assertFalse(c1.isEmpty())
182 else:
183 self.assertTrue(a < b or a > b or a.isEmpty() or b.isEmpty())
184 self.assertFalse(b.overlaps(a))
185 self.assertTrue(c1.isEmpty())
186 if diffs1 is not None:
187 self.assertEqual(diffs1, (a,))
188 if diffs2 is not None:
189 self.assertEqual(diffs2, (b,))
191 def testPrecision(self):
192 """Test that we only use nanosecond precision for equality."""
193 ts1 = self.timespans[-1]
194 ts2 = Timespan(begin=ts1.begin + astropy.time.TimeDelta(1e-10, format="sec"), end=ts1.end)
195 self.assertEqual(ts1, ts2)
197 self.assertEqual(Timespan(begin=None, end=None), Timespan(begin=None, end=None))
198 self.assertEqual(Timespan(begin=None, end=ts1.end), Timespan(begin=None, end=ts1.end))
200 ts2 = Timespan(begin=ts1.begin + astropy.time.TimeDelta(1e-8, format="sec"), end=ts1.end)
201 self.assertNotEqual(ts1, ts2)
203 ts2 = Timespan(begin=None, end=ts1.end)
204 self.assertNotEqual(ts1, ts2)
206 t1 = Timespan(
207 begin=astropy.time.Time(2456461.0, val2=0.06580758101851847, format="jd", scale="tai"),
208 end=astropy.time.Time(2456461.0, val2=0.06617994212962963, format="jd", scale="tai"),
209 )
210 t2 = Timespan(
211 begin=astropy.time.Time(2456461.0, val2=0.06580758101851858, format="jd", scale="tai"),
212 end=astropy.time.Time(2456461.0, val2=0.06617994212962963, format="jd", scale="tai"),
213 )
214 self.assertEqual(t1, t2)
216 # Ensure that == and != work properly
217 self.assertTrue(t1 == t2, f"Equality of {t1} and {t2}")
218 self.assertFalse(t1 != t2, f"Check != is false for {t1} and {t2}")
220 def testTimescales(self):
221 """Test time scale conversion occurs on comparison."""
222 ts1 = Timespan(
223 begin=astropy.time.Time("2013-06-17 13:34:45.775000", scale="tai", format="iso"),
224 end=astropy.time.Time("2013-06-17 13:35:17.947000", scale="tai", format="iso"),
225 )
226 ts2 = Timespan(
227 begin=astropy.time.Time("2013-06-17T13:34:10.775", scale="utc", format="isot"),
228 end=astropy.time.Time("2013-06-17T13:34:42.947", scale="utc", format="isot"),
229 )
230 self.assertEqual(ts1, ts2, f"Compare {ts1} with {ts2}")
232 def testFuture(self):
233 """Check that we do not get warnings from future dates."""
234 # Astropy will give "dubious year" for UTC five years in the future
235 # so hide these expected warnings from the test output
236 with warnings.catch_warnings():
237 warnings.simplefilter("ignore", category=astropy.utils.exceptions.AstropyWarning)
238 if erfa is not None:
239 warnings.simplefilter("ignore", category=erfa.ErfaWarning)
240 ts1 = Timespan(
241 begin=astropy.time.Time(self.timestamps[0], scale="utc", format="iso"),
242 end=astropy.time.Time("2099-06-17 13:35:17.947000", scale="utc", format="iso"),
243 )
244 ts2 = Timespan(
245 begin=astropy.time.Time(self.timestamps[0], scale="utc", format="iso"),
246 end=astropy.time.Time("2099-06-17 13:35:17.947000", scale="utc", format="iso"),
247 )
249 # unittest can't test for no warnings so we run the test and
250 # trigger our own warning and count all the warnings
251 with self.assertWarns(Warning) as cm:
252 self.assertEqual(ts1, ts2)
253 warnings.warn("deliberate", stacklevel=1)
254 self.assertEqual(str(cm.warning), "deliberate")
256 def testJson(self):
257 ts1 = Timespan(
258 begin=astropy.time.Time("2013-06-17 13:34:45.775000", scale="tai", format="iso"),
259 end=astropy.time.Time("2013-06-17 13:35:17.947000", scale="tai", format="iso"),
260 )
261 json_str = ts1.to_json()
262 ts_json = Timespan.from_json(json_str)
263 self.assertEqual(ts_json, ts1)
265 def test_day_obs(self):
266 data = (
267 ((20240201, 0), ("2024-02-01T00:00:00.0", "2024-02-02T00:00:00.0")),
268 ((19801011, 3600), ("1980-10-11T01:00:00.0", "1980-10-12T01:00:00.0")),
269 ((20481231, -7200), ("2048-12-30T22:00:00.0", "2048-12-31T22:00:00.0")),
270 ((20481231, 7200), ("2048-12-31T02:00:00.0", "2049-01-01T02:00:00.0")),
271 )
272 for input, output in data:
273 ts1 = Timespan.from_day_obs(input[0], input[1])
274 ts2 = Timespan(
275 begin=astropy.time.Time(output[0], scale="tai", format="isot"),
276 end=astropy.time.Time(output[1], scale="tai", format="isot"),
277 )
278 self.assertEqual(ts1, ts2)
280 with self.assertRaises(ValueError):
281 Timespan.from_day_obs(19690101)
284if __name__ == "__main__":
285 unittest.main()