Debian Codegraph @

asdf_astropy/converters/time/tests/test_time.py

raw
1 import unittest.mock as mk
2 from datetime import datetime
3
4 import asdf
5 import numpy as np
6 import pytest
7 from asdf.testing.helpers import yaml_to_asdf
8 from astropy import units as u
9 from astropy.coordinates import EarthLocation
10 from astropy.time import Time
11
12 from asdf_astropy.testing.helpers import assert_time_equal
13
14
15 def create_times():
16 return [
17 Time(1950.0, format="byear"),
18 Time("B1950.0", format="byear_str"),
19 Time(
20 [1, 2],
21 location=EarthLocation(x=[1, 2] * u.m, y=[3, 4] * u.m, z=[5, 6] * u.m),
22 format="cxcsec",
23 ),
24 Time(datetime(2000, 1, 2, 12, 0, 0), format="datetime"),
25 Time(2000.45, format="decimalyear"),
26 Time("2000-01-01T00:00:00.000", format="fits"),
27 Time(630720013.0, format="gps"),
28 Time("2000-01-01 00:00:00.000", format="iso"),
29 Time("2000-01-01T00:00:00.000", format="isot"),
30 Time(2451544.5, format="jd"),
31 Time(2000.0, format="jyear"),
32 Time(
33 "J2000.000",
34 location=EarthLocation(x=6378100 * u.m, y=0 * u.m, z=0 * u.m),
35 format="jyear_str",
36 ),
37 Time(51544.0, format="mjd"),
38 Time(Time("2000-01-01T00:00:00.000").plot_date, format="plot_date"), # astropy/astropy#14080
39 Time(np.arange(100), format="unix"),
40 Time(946684800.0, format="unix_tai"),
41 Time("2000:001:00:00:00.000", format="yday"),
42 Time("2000-01-01T00:00:00.000"),
43 Time({"year": 2010, "month": 3, "day": 1}, format="ymdhms"),
44 Time(np.datetime64("2000-01-01T01:01:01"), format="datetime64"),
45 Time(["2001-01-02T12:34:56", "2001-02-03T00:01:02"]),
46 ]
47
48
49 @pytest.mark.parametrize("time", create_times())
50 @pytest.mark.parametrize("version", asdf.versioning.supported_versions)
51 def test_serialization(time, version, tmp_path):
52 file_path = tmp_path / "test.asdf"
53 with asdf.AsdfFile(version=version) as af:
54 af["time"] = time
55 af.write_to(file_path)
56
57 with asdf.open(file_path) as af:
58 assert_time_equal(af["time"], time)
59
60
61 def create_examples():
62 return [
63 {"example": '!time/time-1.1.0 "2000-12-31T13:05:27.737"', "truth": Time("2000-12-31T13:05:27.737")},
64 {"example": '!time/time-1.1.0 "2001:003:04:05:06.789"', "truth": Time("2001:003:04:05:06.789")},
65 {"example": "!time/time-1.1.0 B2000.0", "truth": Time("B2000.0")},
66 {
67 "example": """!time/time-1.1.0
68 value: 2000.0
69 format: byear""",
70 "truth": Time(2000.0, format="byear"),
71 },
72 {
73 "example": """!time/time-1.1.0
74 ["2000-12-31T13:05:27.737", "2000-12-31T13:06:38.444"]""",
75 "truth": Time(["2000-12-31T13:05:27.737", "2000-12-31T13:06:38.444"]),
76 },
77 {
78 "example": """!time/time-1.1.0
79 value: !core/ndarray-1.0.0
80 data: [2000, 2001]
81 datatype: float64
82 format: jyear""",
83 "truth": Time([2000, 2001], format="jyear"),
84 },
85 {
86 "example": """!time/time-1.1.0
87 value: !core/ndarray-1.0.0
88 value: 2000.0
89 format: jyear
90 scale: tdb
91 location:
92 x: !unit/quantity-1.1.0
93 value: 6378100
94 unit: !unit/unit-1.0.0 m
95 y: !unit/quantity-1.1.0
96 value: 0
97 unit: !unit/unit-1.0.0 m
98 z: !unit/quantity-1.1.0
99 value: 0
100 unit: !unit/unit-1.0.0 m
101 format: jyear""",
102 "truth": Time(
103 2000.0,
104 location=EarthLocation(x=6378100 * u.m, y=0 * u.m, z=0 * u.m),
105 scale="tdb",
106 format="jyear",
107 ),
108 },
109 ]
110
111
112 @pytest.mark.parametrize("example", create_examples())
113 def test_read_examples(example):
114 buff = yaml_to_asdf(f"example: {example['example'].strip()}", version="1.5.0")
115 with asdf.open(buff) as af:
116 assert np.all(af["example"] == example["truth"])
117
118
119 def test_error():
120 from asdf_astropy.converters.time.time import TimeConverter
121
122 with mk.patch("asdf_astropy.converters.time.time._ASTROPY_FORMAT_TO_ASDF_FORMAT") as mock_time:
123 mock_time.get.return_value = "Bad time"
124
125 example = "2000-01-01 00:00:00.000"
126 with pytest.raises(ValueError, match=f"ASDF time '{example}' is not one of the recognized implicit formats"):
127 TimeConverter().from_yaml_tree(example, mk.MagicMock(), mk.MagicMock())
128
129
130 def create_formats():
131 from astropy.time.formats import TIME_FORMATS
132
133 formats = []
134 for format_ in TIME_FORMATS:
135 if format_ == "stardate":
136 # stardate is not a documented format for astropy
137 # https://docs.astropy.org/en/latest/time/index.html#time-format
138 continue
139 if format_ == "galexsec":
140 # galexsec is unsupported until the time schema can be updated
141 # https://github.com/astropy/asdf-astropy/issues/292
142 continue
143 new = Time("B2000.0")
144 new.format = format_
145 formats.append(new)
146
147 return formats
148
149
150 @pytest.mark.parametrize("time", create_formats())
151 def test_formats(time, tmp_path):
152 atol = 1 * u.day if "jyear" in time.format else 1e-08 * u.day
153
154 file_path = tmp_path / "test.asdf"
155 with asdf.AsdfFile() as af:
156 af["time"] = time
157 af.write_to(file_path)
158
159 with asdf.open(file_path) as af:
160 assert af["time"].isclose(time, atol=atol)
161 assert af["time"].format == time.format
162
163
164 def create_str_formats():
165 return [
166 Time("2000-01-01 00:00:00.000", format="iso"),
167 Time("B2000.0", scale="utc", format="byear_str"),
168 Time("J2000.000", scale="utc", format="jyear_str"),
169 Time("2000:001:00:00:00.000", format="yday"),
170 ]
171
172
173 @pytest.mark.parametrize("time", create_str_formats())
174 def test_str_format(time, tmp_path):
175 """Test times that should serialize as strings"""
176
177 file_path = tmp_path / "test.asdf"
178
179 with asdf.AsdfFile() as af:
180 af["time"] = time
181 af.write_to(file_path)
182
183 with asdf.open(file_path, _force_raw_types=True) as af:
184 assert isinstance(af["time"], str)
185 assert str(af["time"]) == time.value
186
187 atol = 1 * u.day if "jyear" in time.format or "byear" in time.format else 1e-08 * u.day
188
189 with asdf.open(file_path) as af:
190 assert af["time"].isclose(time, atol=atol)
191 assert af["time"].format == time.format