Debian Codegraph @

asdf_astropy/converters/transform/tests/test_transform.py

raw
1 import itertools
2 import unittest.mock as mk
3 import warnings
4
5 import asdf
6 import astropy
7 import astropy.modeling
8 import numpy as np
9 import pytest
10 from asdf.testing.helpers import yaml_to_asdf
11 from astropy import units as u
12 from astropy.modeling import bind_bounding_box
13 from astropy.modeling import models as astropy_models
14 from astropy.modeling.bounding_box import CompoundBoundingBox, ModelBoundingBox
15 from astropy.utils import minversion
16
17 from asdf_astropy import integration
18 from asdf_astropy.testing import helpers
19
20
21 def assert_bounding_box_roundtrip(bounding_box, tmp_path, version=None):
22 message = (
23 "asdf_astropy.converters.transforms.tests.test_transform.assert_bounding_box_round_trip is deprecated."
24 "Use asdf_astropy.testing.helpers.assert_bounding_box_roundtrip instead."
25 )
26 warnings.warn(message, DeprecationWarning, stacklevel=2)
27
28 return helpers.assert_bounding_box_roundtrip(bounding_box, tmp_path, version=version)
29
30
31 def assert_model_roundtrip(model, tmp_path, version=None):
32 message = (
33 "asdf_astropy.converters.transforms.tests.test_transform.assert_model_round_trip is deprecated."
34 "Use asdf_astropy.testing.helpers.assert_model_roundtrip instead."
35 )
36 warnings.warn(message, DeprecationWarning, stacklevel=2)
37
38 return helpers.assert_model_roundtrip(model, tmp_path, version=version)
39
40
41 def test_deprecations(tmp_path):
42 # Test assert_bounding_box_roundtrip deprecation
43 bbox = ModelBoundingBox((0, 1), astropy_models.Polynomial1D(1))
44 with pytest.warns(DeprecationWarning, match=".*assert_bounding_box_roundtrip.*"):
45 assert_bounding_box_roundtrip(bbox, tmp_path)
46
47 # Test assert_model_roundtrip deprecation
48 model = astropy_models.Gaussian2D()
49 with pytest.warns(DeprecationWarning, match=".*assert_model_roundtrip.*"):
50 assert_model_roundtrip(model, tmp_path)
51
52
53 def create_bounding_boxes():
54 model_bounding_box = [
55 ModelBoundingBox((0, 1), astropy_models.Polynomial1D(1)),
56 ModelBoundingBox(((2, 3), (3, 4)), astropy_models.Polynomial2D(1)),
57 ModelBoundingBox(((5, 6), (7, 8)), astropy_models.Polynomial2D(1), order="F"),
58 ]
59
60 model_bounding_box.extend(
61 [
62 ModelBoundingBox((9, 10), astropy_models.Polynomial2D(1), ignored=["x"]),
63 ModelBoundingBox((11, 12), astropy_models.Polynomial2D(1), ignored=["y"]),
64 ],
65 )
66
67 compound_bounding_box = [
68 CompoundBoundingBox({(1,): (0, 1), (2,): (2, 3)}, astropy_models.Polynomial2D(1), [("x", True)]),
69 CompoundBoundingBox(
70 {(1,): ((0, 1), (-1, 0)), (2,): ((2, 3), (-3, -2))},
71 astropy_models.Polynomial2D(1),
72 [("x", False)],
73 ),
74 CompoundBoundingBox(
75 {(1,): (0, 1), (2,): (2, 3)},
76 astropy_models.Polynomial2D(1),
77 [("x", False)],
78 ignored=["x"],
79 ),
80 CompoundBoundingBox(
81 {(1,): (0, 1), (2,): (2, 3)},
82 astropy_models.Polynomial2D(1),
83 [("x", False)],
84 ignored=["y"],
85 ),
86 ]
87
88 return model_bounding_box + compound_bounding_box
89
90
91 @pytest.mark.parametrize("bbox", create_bounding_boxes())
92 def test_round_trip_bounding_box(bbox, tmp_path):
93 helpers.assert_bounding_box_roundtrip(bbox, tmp_path)
94
95
96 def create_single_models(): # noqa: PLR0915
97 model_with_bounding_box = astropy_models.Shift(10)
98 model_with_bounding_box.bounding_box = ((1, 7),)
99
100 model_with_user_inverse = astropy_models.Shift(10)
101 model_with_user_inverse.inverse = astropy_models.Shift(-7)
102
103 model_with_constraints = astropy_models.Legendre2D(
104 x_degree=1,
105 y_degree=1,
106 c0_0=1,
107 c0_1=2,
108 c1_0=3,
109 fixed={"c1_0": True, "c0_1": True},
110 bounds={"c0_0": (-10, 10)},
111 )
112
113 model_with_custom_inputs_outputs = astropy_models.Gaussian2D()
114 model_with_custom_inputs_outputs.inputs = ("a", "b")
115 model_with_custom_inputs_outputs.outputs = ("c",)
116
117 result = [
118 # Generic model features
119 astropy_models.Shift(10, name="some model name"),
120 model_with_bounding_box,
121 model_with_user_inverse,
122 model_with_constraints,
123 model_with_custom_inputs_outputs,
124 # astropy.modeling.functional_models
125 astropy_models.AiryDisk2D(amplitude=10.0, x_0=0.5, y_0=1.5),
126 astropy_models.Box1D(amplitude=10.0, x_0=0.5, width=5.0),
127 astropy_models.Box2D(amplitude=10.0, x_0=0.5, x_width=5.0, y_0=1.5, y_width=7.0),
128 astropy_models.Const1D(amplitude=5.0),
129 astropy_models.Const2D(amplitude=5.0),
130 astropy_models.Disk2D(amplitude=10.0, x_0=0.5, y_0=1.5, R_0=5.0),
131 astropy_models.Ellipse2D(amplitude=10.0, x_0=0.5, y_0=1.5, a=2.0, b=4.0, theta=0.1),
132 astropy_models.Exponential1D(amplitude=10.0, tau=3.5),
133 astropy_models.Gaussian1D(amplitude=10.0, mean=5.0, stddev=3.0),
134 astropy_models.Gaussian2D(amplitude=10.0, x_mean=5.0, y_mean=5.0, x_stddev=3.0, y_stddev=3.0),
135 astropy_models.KingProjectedAnalytic1D(amplitude=10.0, r_core=5.0, r_tide=2.0),
136 astropy_models.Linear1D(slope=2.0, intercept=1.5),
137 astropy_models.Logarithmic1D(amplitude=10.0, tau=3.5),
138 astropy_models.Lorentz1D(amplitude=10.0, x_0=0.5, fwhm=2.5),
139 astropy_models.Moffat1D(amplitude=10.0, x_0=0.5, gamma=1.2, alpha=2.5),
140 astropy_models.Moffat2D(amplitude=10.0, x_0=0.5, y_0=1.5, gamma=1.2, alpha=2.5),
141 astropy_models.Multiply(3),
142 astropy_models.Multiply(10 * u.m),
143 astropy_models.Planar2D(slope_x=0.5, slope_y=1.2, intercept=2.5),
144 astropy_models.RedshiftScaleFactor(z=2.5),
145 astropy_models.RickerWavelet1D(amplitude=10.0, x_0=0.5, sigma=1.2),
146 astropy_models.RickerWavelet2D(amplitude=10.0, x_0=0.5, y_0=1.5, sigma=1.2),
147 astropy_models.Ring2D(amplitude=10.0, x_0=0.5, y_0=1.5, r_in=5.0, width=10.0),
148 astropy_models.Scale(3.4),
149 astropy_models.Sersic1D(amplitude=10.0, r_eff=1.0, n=4.0),
150 astropy_models.Sersic2D(amplitude=10.0, r_eff=1.0, n=4.0, x_0=0.5, y_0=1.5, ellip=0.0, theta=0.0),
151 astropy_models.Shift(2.0),
152 astropy_models.Shift(2.0 * u.deg),
153 astropy_models.Scale(3.4 * u.deg),
154 astropy_models.Sine1D(amplitude=10.0, frequency=0.5, phase=1.0),
155 astropy_models.Cosine1D(amplitude=10.0, frequency=0.5, phase=1.0),
156 astropy_models.Tangent1D(amplitude=10.0, frequency=0.5, phase=1.0),
157 astropy_models.ArcSine1D(amplitude=10.0, frequency=0.5, phase=1.0),
158 astropy_models.ArcCosine1D(amplitude=10.0, frequency=0.5, phase=1.0),
159 astropy_models.ArcTangent1D(amplitude=10.0, frequency=0.5, phase=1.0),
160 astropy_models.Trapezoid1D(amplitude=10.0, x_0=0.5, width=5.0, slope=1.0),
161 astropy_models.TrapezoidDisk2D(amplitude=10.0, x_0=0.5, y_0=1.5, R_0=5.0, slope=1.0),
162 astropy_models.Voigt1D(x_0=0.55, amplitude_L=10.0, fwhm_L=0.5, fwhm_G=0.9),
163 # astropy.modeling.mappings
164 astropy_models.Identity(2),
165 astropy_models.Mapping((0, 1), n_inputs=3),
166 # astropy.modeling.math_functions
167 astropy.modeling.math_functions.AbsoluteUfunc(),
168 astropy.modeling.math_functions.AddUfunc(),
169 astropy.modeling.math_functions.ArccosUfunc(),
170 astropy.modeling.math_functions.ArccoshUfunc(),
171 astropy.modeling.math_functions.ArcsinUfunc(),
172 astropy.modeling.math_functions.ArcsinhUfunc(),
173 astropy.modeling.math_functions.Arctan2Ufunc(),
174 astropy.modeling.math_functions.ArctanUfunc(),
175 astropy.modeling.math_functions.ArctanhUfunc(),
176 astropy.modeling.math_functions.CbrtUfunc(),
177 astropy.modeling.math_functions.CosUfunc(),
178 astropy.modeling.math_functions.CoshUfunc(),
179 astropy.modeling.math_functions.Deg2radUfunc(),
180 astropy.modeling.math_functions.DivideUfunc(),
181 astropy.modeling.math_functions.DivmodUfunc(),
182 astropy.modeling.math_functions.Exp2Ufunc(),
183 astropy.modeling.math_functions.ExpUfunc(),
184 astropy.modeling.math_functions.Expm1Ufunc(),
185 astropy.modeling.math_functions.FabsUfunc(),
186 astropy.modeling.math_functions.Floor_divideUfunc(),
187 astropy.modeling.math_functions.FmodUfunc(),
188 astropy.modeling.math_functions.HypotUfunc(),
189 astropy.modeling.math_functions.Log10Ufunc(),
190 astropy.modeling.math_functions.Log1pUfunc(),
191 astropy.modeling.math_functions.Log2Ufunc(),
192 astropy.modeling.math_functions.LogUfunc(),
193 astropy.modeling.math_functions.Logaddexp2Ufunc(),
194 astropy.modeling.math_functions.LogaddexpUfunc(),
195 astropy.modeling.math_functions.ModUfunc(),
196 astropy.modeling.math_functions.MultiplyUfunc(),
197 astropy.modeling.math_functions.NegativeUfunc(),
198 astropy.modeling.math_functions.PositiveUfunc(),
199 astropy.modeling.math_functions.PowerUfunc(),
200 astropy.modeling.math_functions.Rad2degUfunc(),
201 astropy.modeling.math_functions.ReciprocalUfunc(),
202 astropy.modeling.math_functions.RemainderUfunc(),
203 astropy.modeling.math_functions.RintUfunc(),
204 astropy.modeling.math_functions.SinUfunc(),
205 astropy.modeling.math_functions.SinhUfunc(),
206 astropy.modeling.math_functions.SqrtUfunc(),
207 astropy.modeling.math_functions.SquareUfunc(),
208 astropy.modeling.math_functions.SubtractUfunc(),
209 astropy.modeling.math_functions.TanUfunc(),
210 astropy.modeling.math_functions.TanhUfunc(),
211 astropy.modeling.math_functions.True_divideUfunc(),
212 # astropy.modeling.physical_models
213 astropy_models.BlackBody(scale=10.0, temperature=6000.0 * u.K),
214 astropy_models.Drude1D(amplitude=10.0, x_0=0.5, fwhm=2.5),
215 # TODO: NFW
216 # astropy.modeling.polynomial
217 astropy_models.Chebyshev1D(2, c0=2, c1=3, c2=0.5),
218 astropy_models.Chebyshev1D(2, c0=2, c1=3, c2=0.5, domain=(0.0, 1.0), window=(1.5, 2.5)),
219 astropy_models.Chebyshev2D(1, 1, c0_0=1, c0_1=2, c1_0=3),
220 astropy_models.Chebyshev2D(
221 1,
222 1,
223 c0_0=1,
224 c0_1=2,
225 c1_0=3,
226 x_domain=(1.0, 2.0),
227 y_domain=(3.0, 4.0),
228 x_window=(5.0, 6.0),
229 y_window=(7.0, 8.0),
230 ),
231 astropy_models.Hermite1D(2, c0=2, c1=3, c2=0.5),
232 astropy_models.Hermite2D(1, 1, c0_0=1, c0_1=2, c1_0=3),
233 astropy_models.Legendre1D(2, c0=2, c1=3, c2=0.5),
234 astropy_models.Legendre2D(1, 1, c0_0=1, c0_1=2, c1_0=3),
235 astropy_models.Polynomial1D(2, c0=1, c1=2, c2=3),
236 astropy_models.Polynomial2D(1, c0_0=1, c0_1=2, c1_0=3),
237 # astropy.modeling.spline
238 astropy_models.Spline1D(
239 np.array([-3.0, -3.0, -3.0, -3.0, -1.0, 0.0, 1.0, 3.0, 3.0, 3.0, 3.0]),
240 np.array(
241 [
242 0.10412331,
243 0.07013616,
244 -0.18799552,
245 1.35953147,
246 -0.15282581,
247 0.03923,
248 -0.04297299,
249 0.0,
250 0.0,
251 0.0,
252 0.0,
253 ],
254 ),
255 3,
256 ),
257 # astropy.modeling.powerlaws
258 astropy_models.BrokenPowerLaw1D(amplitude=10, x_break=0.5, alpha_1=2.0, alpha_2=3.5),
259 astropy_models.ExponentialCutoffPowerLaw1D(10, 0.5, 2.0, 7.0),
260 astropy_models.LogParabola1D(
261 amplitude=10,
262 x_0=0.5,
263 alpha=2.0,
264 beta=3.0,
265 ),
266 astropy_models.PowerLaw1D(amplitude=10.0, x_0=0.5, alpha=2.0),
267 astropy_models.SmoothlyBrokenPowerLaw1D(amplitude=10.0, x_break=5.0, alpha_1=2.0, alpha_2=3.0, delta=0.5),
268 # astropy.modeling.projections
269 astropy_models.AffineTransformation2D(
270 matrix=np.array([[1.0, 2.0], [3.0, 4.0]]),
271 translation=np.array([5.0, 6.0]),
272 ),
273 astropy_models.Pix2Sky_Airy(theta_b=75.8),
274 astropy_models.Sky2Pix_Airy(theta_b=75.8),
275 astropy_models.Pix2Sky_BonneEqualArea(theta1=44.3),
276 astropy_models.Sky2Pix_BonneEqualArea(theta1=44.3),
277 astropy_models.Pix2Sky_COBEQuadSphericalCube(),
278 astropy_models.Sky2Pix_COBEQuadSphericalCube(),
279 astropy_models.Pix2Sky_ConicEqualArea(sigma=89.5, delta=0.5),
280 astropy_models.Sky2Pix_ConicEqualArea(sigma=89.5, delta=0.5),
281 astropy_models.Pix2Sky_ConicEquidistant(sigma=89.5, delta=0.5),
282 astropy_models.Sky2Pix_ConicEquidistant(sigma=89.5, delta=0.5),
283 astropy_models.Pix2Sky_ConicOrthomorphic(sigma=88.0, delta=1.0),
284 astropy_models.Sky2Pix_ConicOrthomorphic(sigma=88.0, delta=1.0),
285 astropy_models.Pix2Sky_ConicPerspective(sigma=89.5, delta=0.5),
286 astropy_models.Sky2Pix_ConicPerspective(sigma=89.5, delta=0.5),
287 astropy_models.Pix2Sky_CylindricalEqualArea(lam=0.5),
288 astropy_models.Sky2Pix_CylindricalEqualArea(lam=0.5),
289 astropy_models.Pix2Sky_CylindricalPerspective(mu=1.5, lam=2.4),
290 astropy_models.Sky2Pix_CylindricalPerspective(mu=1.5, lam=2.4),
291 astropy_models.Pix2Sky_Gnomonic(),
292 astropy_models.Sky2Pix_Gnomonic(),
293 astropy_models.Pix2Sky_HEALPixPolar(),
294 astropy_models.Sky2Pix_HEALPixPolar(),
295 astropy_models.Pix2Sky_HEALPix(H=12.0, X=17.0),
296 astropy_models.Sky2Pix_HEALPix(H=12.0, X=17.0),
297 astropy_models.Pix2Sky_HammerAitoff(),
298 astropy_models.Sky2Pix_HammerAitoff(),
299 astropy_models.Pix2Sky_Mercator(),
300 astropy_models.Sky2Pix_Mercator(),
301 astropy_models.Pix2Sky_Molleweide(),
302 astropy_models.Sky2Pix_Molleweide(),
303 astropy_models.Pix2Sky_Parabolic(),
304 astropy_models.Sky2Pix_Parabolic(),
305 astropy_models.Pix2Sky_PlateCarree(),
306 astropy_models.Sky2Pix_PlateCarree(),
307 astropy_models.Pix2Sky_Polyconic(),
308 astropy_models.Sky2Pix_Polyconic(),
309 astropy_models.Pix2Sky_QuadSphericalCube(),
310 astropy_models.Sky2Pix_QuadSphericalCube(),
311 astropy_models.Pix2Sky_SansonFlamsteed(),
312 astropy_models.Sky2Pix_SansonFlamsteed(),
313 astropy_models.Pix2Sky_SlantOrthographic(xi=0.1, eta=0.2),
314 astropy_models.Sky2Pix_SlantOrthographic(xi=0.1, eta=0.2),
315 astropy_models.Pix2Sky_SlantZenithalPerspective(mu=1.5, phi0=15.0, theta0=80.0),
316 astropy_models.Sky2Pix_SlantZenithalPerspective(mu=1.5, phi0=15.0, theta0=80.0),
317 astropy_models.Pix2Sky_Stereographic(),
318 astropy_models.Sky2Pix_Stereographic(),
319 astropy_models.Pix2Sky_TangentialSphericalCube(),
320 astropy_models.Sky2Pix_TangentialSphericalCube(),
321 astropy_models.Pix2Sky_ZenithalEqualArea(),
322 astropy_models.Sky2Pix_ZenithalEqualArea(),
323 astropy_models.Pix2Sky_ZenithalEquidistant(),
324 astropy_models.Sky2Pix_ZenithalEquidistant(),
325 astropy_models.Pix2Sky_ZenithalPerspective(mu=1.5, gamma=15.0),
326 astropy_models.Sky2Pix_ZenithalPerspective(mu=1.5, gamma=15.0),
327 # astropy.modeling.rotations
328 astropy_models.EulerAngleRotation(23, 14, 2.3, axes_order="xzx"),
329 astropy_models.RotateCelestial2Native(5.63, -72.5, 180),
330 astropy_models.RotateCelestial2Native(5.63 * u.deg, -72.5 * u.deg, 180 * u.deg),
331 astropy_models.RotateNative2Celestial(5.63, -72.5, 180),
332 astropy_models.RotateNative2Celestial(5.63 * u.deg, -72.5 * u.deg, 180 * u.deg),
333 astropy_models.Rotation2D(angle=1.51),
334 astropy_models.RotationSequence3D([1.2, 2.3, 3.4, 0.3], "xyzx"),
335 astropy_models.SphericalRotationSequence([1.2, 2.3, 3.4, 0.3], "xyzy"),
336 # astropy.modeling.tabular
337 astropy_models.Tabular1D(points=np.arange(0, 5), lookup_table=[1.0, 10, 2, 45, -3]),
338 astropy_models.Tabular1D(points=np.arange(0, 5) * u.pix, lookup_table=[1.0, 10, 2, 45, -3] * u.nm),
339 astropy_models.Tabular2D(
340 points=([1, 2, 3], [1, 2, 3]),
341 lookup_table=np.arange(0, 9).reshape(3, 3),
342 bounds_error=False,
343 fill_value=None,
344 method="nearest",
345 ),
346 astropy_models.Tabular2D(
347 points=([1, 2, 3], [1, 2, 3]) * u.pix,
348 lookup_table=np.arange(0, 9).reshape(3, 3) * u.nm,
349 bounds_error=False,
350 fill_value=None,
351 method="nearest",
352 ),
353 ]
354
355 # Test case for model with a metaclass generated abstract bounding_box
356 # where a custom bounding box is stored
357 gaussian_1d = astropy_models.Gaussian1D(10, 1.5, 0.25)
358 gaussian_1d.bounding_box = [7, 8]
359 result.append(gaussian_1d)
360
361 # compound model with bounding box
362 model = astropy_models.Shift(1) & astropy_models.Shift(2)
363 model.bounding_box = ((1, 2), (3, 4))
364 result.append(model)
365
366 # compound model with bounding box
367 model = astropy_models.Shift(1) & astropy_models.Shift(2) & astropy_models.Shift(3)
368 model.bounding_box = ((1, 2), (3, 4), (5, 6))
369 result.append(model)
370
371 # model with compound bounding box
372 model = astropy_models.Shift(1) & astropy_models.Scale(2) & astropy_models.Identity(1)
373 model.inputs = ("x", "y", "slit_id")
374 bounding_boxes = {
375 (0,): ((-0.5, 1047.5), (-0.5, 2047.5)),
376 (1,): ((-0.5, 3047.5), (-0.5, 4047.5)),
377 }
378 bounding_box = CompoundBoundingBox.validate(model, bounding_boxes, selector_args=[("slit_id", True)], order="F")
379 model.bounding_box = bounding_box
380 result.append(model)
381
382 model = astropy_models.Shift(1) & astropy_models.Shift(2) & astropy_models.Shift(3)
383 model.inputs = ("x", "y", "z")
384 bounding_boxes = {
385 (0,): (1.0, 2.0),
386 (1,): (3.0, 4.0),
387 }
388
389 bounding_box = CompoundBoundingBox.validate(
390 model,
391 bounding_boxes,
392 selector_args=[("x", True)],
393 ignored=["y"],
394 )
395 model.bounding_box = bounding_box
396 result.append(model)
397
398 result.append(astropy_models.Plummer1D(mass=10.0, r_plum=5.0))
399
400 # models with input_units_equivalencies
401 # 1D model
402 m1 = astropy_models.Shift(1 * u.kg)
403 m1.input_units_equivalencies = {"x": u.mass_energy()}
404
405 # 2D model
406 m2 = astropy_models.Const2D(10 * u.Hz)
407 m2.input_units_equivalencies = {"x": u.dimensionless_angles(), "y": u.dimensionless_angles()}
408
409 # 2D model with only one input equivalencies
410 m3 = astropy_models.Const2D(10 * u.Hz)
411 m3.input_units_equivalencies = {"x": u.dimensionless_angles()}
412
413 # model using equivalency that has args using units
414 m4 = astropy_models.PowerLaw1D(amplitude=1 * u.m, x_0=10 * u.pix, alpha=7)
415 m4.input_units_equivalencies = {"x": u.equivalencies.pixel_scale(0.5 * u.arcsec / u.pix)}
416
417 result.extend([m1, m2, m3, m4])
418
419 # compound models with input_units_equivalencies
420 m1 = astropy_models.Gaussian1D(10 * u.K, 11 * u.arcsec, 12 * u.arcsec)
421 m1.input_units_equivalencies = {"x": u.parallax()}
422 m2 = astropy_models.Gaussian1D(5 * u.s, 2 * u.K, 3 * u.K)
423 m2.input_units_equivalencies = {"x": u.temperature()}
424
425 result.extend([m1 | m2, m1 & m2, m1 + m2])
426
427 # fix_inputs models with input_units_equivalencies
428 m1 = astropy_models.Pix2Sky_TAN()
429 m1.input_units_equivalencies = {"x": u.dimensionless_angles(), "y": u.dimensionless_angles()}
430 m2 = astropy_models.Rotation2D()
431 m = m1 | m2
432
433 result.extend([astropy_models.fix_inputs(m, {"x": 45}), astropy_models.fix_inputs(m, {0: 45})])
434
435 result.append(astropy_models.Schechter1D(phi_star=1.0, m_star=2.0, alpha=3.0))
436
437 return result
438
439
440 UNSUPPORTED_MODELS = [
441 # FITS-specific and deemed unworthy of ASDF serialization:
442 astropy.modeling.polynomial.InverseSIP,
443 astropy.modeling.polynomial.SIP,
444 # Base classes which should not be directly supported:
445 astropy.modeling.core.Model,
446 astropy.modeling.math_functions._NPUfuncModel,
447 astropy.modeling.polynomial.OrthoPolynomialBase,
448 astropy.modeling.polynomial.PolynomialModel,
449 astropy.modeling.projections.Conic,
450 astropy.modeling.projections.Cylindrical,
451 astropy.modeling.projections.HEALPix,
452 astropy.modeling.projections.Pix2SkyProjection,
453 astropy.modeling.projections.Projection,
454 astropy.modeling.projections.PseudoConic,
455 astropy.modeling.projections.PseudoCylindrical,
456 astropy.modeling.projections.QuadCube,
457 astropy.modeling.projections.Sky2PixProjection,
458 astropy.modeling.projections.Zenithal,
459 # https://github.com/astropy/asdf-astropy/issues/6
460 astropy.modeling.physical_models.NFW,
461 ]
462
463 if minversion("astropy", "6.0.dev"):
464 UNSUPPORTED_MODELS.append(astropy.modeling.functional_models.GeneralSersic2D)
465
466 if minversion("astropy", "7.0.dev"):
467 UNSUPPORTED_MODELS.append(astropy.modeling.functional_models.Lorentz2D)
468
469
470 @pytest.mark.parametrize("model", create_single_models())
471 def test_single_model(tmp_path, model):
472 helpers.assert_model_roundtrip(model, tmp_path)
473
474
475 def get_all_models():
476 def _iterate_model_classes():
477 for _key, value in itertools.chain(
478 astropy_models.__dict__.items(),
479 astropy.modeling.math_functions.__dict__.items(),
480 ):
481 if (
482 isinstance(value, type)
483 and issubclass(value, astropy.modeling.core.Model)
484 and value not in UNSUPPORTED_MODELS
485 ):
486 yield value
487
488 return list(_iterate_model_classes())
489
490
491 @pytest.mark.parametrize("model", get_all_models())
492 def test_all_models_supported(model):
493 """
494 Test that all model classes in astropy have serialization
495 support implemented in this package. If this test fails,
496 file an issue on GitHub for each missing model and add
497 the model to the UNSUPPORTED_MODELS list above with
498 a link to the issue in a comment.
499 """
500
501 extensions = integration.get_extensions()
502 extension_manager = asdf.extension.ExtensionManager(extensions)
503
504 message = f"Missing support for model: {model.__module__}.{model.__qualname__}"
505 assert extension_manager.handles_type(model), message
506
507
508 def test_legacy_const(tmp_path):
509 with asdf.config_context() as config:
510 config.remove_extension("asdf://asdf-format.org/transform/extensions/transform-1.6.0")
511 config.remove_extension("asdf://asdf-format.org/transform/extensions/transform-1.5.0")
512
513 model = astropy_models.Const1D(amplitude=5.0)
514 helpers.assert_model_roundtrip(model, tmp_path, version="1.3.0")
515
516 model = astropy_models.Const2D(amplitude=5.0)
517 with pytest.raises(TypeError, match=r".* does not support models with > 1 dimension"):
518 helpers.assert_model_roundtrip(model, tmp_path, version="1.3.0")
519
520
521 COMPOUND_OPERATORS = [
522 "__add__",
523 "__sub__",
524 "__mul__",
525 "__truediv__",
526 "__pow__",
527 "__or__",
528 "__and__",
529 ]
530
531
532 @pytest.mark.parametrize("operator", COMPOUND_OPERATORS)
533 def test_compound_model(tmp_path, operator):
534 left_model = astropy_models.Shift(5)
535 right_model = astropy_models.Shift(-1)
536 model = getattr(left_model, operator)(right_model)
537 result = helpers.assert_model_roundtrip(model, tmp_path)
538 helpers.assert_model_equal(result.left, left_model)
539 helpers.assert_model_equal(result.right, right_model)
540 assert result.op == model.op
541
542
543 def test_fix_inputs(tmp_path):
544 model = astropy_models.Gaussian2D(1, 2, 3, 4, 5)
545 fixed_model = astropy_models.fix_inputs(model, {"x": 2.5})
546 result = helpers.assert_model_roundtrip(fixed_model, tmp_path)
547 helpers.assert_model_equal(result.left, model)
548 assert result.right == fixed_model.right
549 assert result.op == fixed_model.op
550
551
552 def test_units_mapping(tmp_path):
553 # Basic mapping between units:
554 model = astropy_models.UnitsMapping(((u.m, u.dimensionless_unscaled),))
555 model.name = "foo"
556 result = helpers.assert_model_roundtrip(model, tmp_path)
557 assert result.mapping == model.mapping
558
559 # Remove units:
560 model = astropy_models.UnitsMapping(((u.m, None),))
561 result = helpers.assert_model_roundtrip(model, tmp_path)
562 assert result.mapping == model.mapping
563
564 # Change a model to accept any units:
565 model = astropy_models.UnitsMapping(((None, u.m),))
566 result = helpers.assert_model_roundtrip(model, tmp_path)
567 assert result.mapping == model.mapping
568
569 # With equivalencies:
570 model = astropy_models.UnitsMapping(
571 ((u.m, u.dimensionless_unscaled),),
572 input_units_equivalencies={"x": u.equivalencies.spectral()},
573 )
574 result = helpers.assert_model_roundtrip(model, tmp_path)
575 assert result.mapping == model.mapping
576
577 # Allow dimensionless on all inputs:
578 model = astropy_models.UnitsMapping(
579 ((u.m, u.dimensionless_unscaled), (u.s, u.Hz)),
580 input_units_allow_dimensionless=True,
581 )
582 result = helpers.assert_model_roundtrip(model, tmp_path)
583 assert result.mapping == model.mapping
584
585 # Allow dimensionless selectively:
586 model = astropy_models.UnitsMapping(
587 ((u.m, u.dimensionless_unscaled), (u.s, u.Hz)),
588 input_units_allow_dimensionless={"x0": True, "x1": False},
589 )
590 result = helpers.assert_model_roundtrip(model, tmp_path)
591 assert result.mapping == model.mapping
592
593
594 @pytest.mark.parametrize("standard_version", [v for v in asdf.versioning.supported_versions if v >= "1.4.0"])
595 @pytest.mark.parametrize(
596 "model",
597 [
598 astropy_models.Polynomial1D(1, c0=5, c1=17),
599 astropy_models.Polynomial1D(1, c0=5, c1=17, domain=[-5, 4], window=[-2, 3]),
600 astropy_models.Chebyshev1D(2, c0=2, c1=3, c2=0.5, domain=[-2, 2]),
601 astropy_models.Chebyshev1D(2, c0=2, c1=3, c2=0.5, domain=[-2, 2], window=[-0.5, 0.5]),
602 ],
603 )
604 def test_1d_polynomial_with_asdf_standard_version(tmp_path, standard_version, model):
605 result = helpers.assert_model_roundtrip(model, tmp_path, version=standard_version)
606 assert result.domain == model.domain
607 assert result.window == model.window
608
609
610 @pytest.mark.parametrize("standard_version", [v for v in asdf.versioning.supported_versions if v >= "1.4.0"])
611 @pytest.mark.parametrize(
612 "model",
613 [
614 astropy_models.Polynomial2D(2, c0_0=3, c1_0=5, c0_1=7),
615 astropy_models.Polynomial2D(
616 2,
617 c0_0=3,
618 c1_0=5,
619 c0_1=7,
620 x_domain=[-2, 2],
621 y_domain=[-4, 4],
622 x_window=[-6, 6],
623 y_window=[-8, 8],
624 ),
625 astropy_models.Chebyshev2D(1, 1, c0_0=1, c0_1=2, c1_0=3, x_domain=[-2, 2], y_domain=[-2, 2]),
626 astropy_models.Chebyshev2D(
627 1,
628 1,
629 c0_0=1,
630 c0_1=2,
631 c1_0=3,
632 x_domain=[-2, 2],
633 y_domain=[-2, 2],
634 x_window=[-0.5, 0.5],
635 y_window=[-0.1, 0.5],
636 ),
637 ],
638 )
639 def test_2d_polynomial_with_asdf_standard_version(tmp_path, standard_version, model):
640 result = helpers.assert_model_roundtrip(model, tmp_path, version=standard_version)
641 assert result.x_domain == model.x_domain
642 assert result.y_domain == model.y_domain
643 assert result.x_window == model.x_window
644 assert result.y_window == model.y_window
645
646
647 def test_deserialize_compound_user_inverse(tmp_path):
648 """
649 Confirm that we are able to correctly reconstruct a
650 compound model with a user inverse set on one of its
651 component models.
652
653 Due to code in TransformConverter that facilitates circular
654 inverses, the user inverse of the component model is
655 not available at the time that the CompoundModel is
656 constructed.
657 """
658
659 yaml = """
660 model: !transform/concatenate-1.2.0
661 forward:
662 - !transform/shift-1.2.0
663 inverse: !transform/shift-1.2.0 {offset: 5.0}
664 offset: -10.0
665 - !transform/shift-1.2.0 {offset: -20.0}
666 """
667 buff = yaml_to_asdf(yaml)
668 with asdf.open(buff) as af:
669 model = af["model"]
670 assert model.has_inverse()
671 assert model.inverse(-5, -20) == (0, 0)
672
673
674 def test_rotation_errors():
675 from asdf_astropy.converters.transform.rotations import RotationSequenceConverter
676
677 converter = RotationSequenceConverter()
678
679 # to yaml error
680 mdl = astropy_models.Const1D(5)
681 mdl.angles = mk.MagicMock()
682 mdl.axes_order = mk.MagicMock()
683 with pytest.raises(TypeError, match=r"Cannot serialize model of type *"):
684 converter.to_yaml_tree_transform(mdl, mk.MagicMock(), mk.MagicMock())
685
686 # from yaml error
687 node = {"angles": mk.MagicMock(), "axes_order": mk.MagicMock(), "rotation_type": mk.MagicMock()}
688 with pytest.raises(ValueError, match=r"Unrecognized rotation_type: *"):
689 converter.from_yaml_tree_transform(node, mk.MagicMock(), mk.MagicMock())
690
691
692 def test_projection_errors():
693 from asdf_astropy.converters.transform.projections import ProjectionConverter
694
695 converter = ProjectionConverter(mk.MagicMock(), mk.MagicMock(), mk.MagicMock())
696 converter._sky2pix_type = astropy_models.Pix2Sky_Airy
697 converter._pix2sky_type = astropy_models.Sky2Pix_Airy
698
699 # to yaml error
700 mdl = astropy_models.Const1D(5)
701 with pytest.raises(TypeError, match=r"Unrecognized projection model type: *"):
702 converter.to_yaml_tree_transform(mdl, mk.MagicMock(), mk.MagicMock())
703
704 # from yaml error
705 node = {"direction": mk.MagicMock()}
706 with pytest.raises(ValueError, match=r"Unrecognized projection direction: *"):
707 converter.from_yaml_tree_transform(node, mk.MagicMock(), mk.MagicMock())
708
709
710 def test_polynomial_errors():
711 from asdf_astropy.converters.transform.polynomial import PolynomialConverter
712
713 converter = PolynomialConverter()
714
715 # from yaml error
716 node = {"coefficients": np.zeros((2, 3))}
717 with pytest.raises(TypeError, match=r"Coefficients must be an .* matrix"):
718 converter.from_yaml_tree_transform(node, mk.MagicMock(), mk.MagicMock())
719
720
721 def test_compound_errors():
722 from asdf_astropy.converters.transform.compound import CompoundConverter
723
724 converter = CompoundConverter()
725
726 # Left not a model
727 tag = "!transform/add-1.2.0"
728 node = {"forward": [mk.MagicMock(), mk.MagicMock()]}
729 with pytest.raises(TypeError, match=r"Unknown left model type '.*'"):
730 converter.from_yaml_tree_transform(node, tag, mk.MagicMock())
731
732 # Right not a model (not fix_inputs)
733 node = {"forward": [astropy_models.Const1D(17), mk.MagicMock()]}
734 with pytest.raises(TypeError, match=r"Unknown right model type '.*'"):
735 converter.from_yaml_tree_transform(node, tag, mk.MagicMock())
736
737 # Right not a model (fix_inputs)
738 tag = "!transform/fix_inputs-1.2.0"
739 mdl = mk.MagicMock()
740 mdl.__class__ = astropy_models.Const1D
741 node = {"forward": [astropy_models.Const1D(17), mdl]}
742 with pytest.raises(TypeError, match=r"Unknown right model type '.*'"):
743 converter.from_yaml_tree_transform(node, tag, mk.MagicMock())
744
745
746 def test_bounding_box_missing_attributes():
747 yaml = """
748 model: !transform/constant-1.4.0
749 value: 1
750 dimensions: 1
751 bounding_box: !transform/property/bounding_box-1.0.0
752 intervals:
753 x: [1.0, 2.0]
754 """
755 buff = yaml_to_asdf(yaml)
756 with asdf.open(buff) as af:
757 model = af["model"]
758 assert model.bounding_box.ignored == []
759 assert model.bounding_box.order == "C"
760
761 yaml = """
762 model: !transform/constant-1.4.0
763 value: 1
764 dimensions: 2
765 bounding_box: !transform/property/compound_bounding_box-1.0.0
766 selector_args:
767 - argument: x
768 ignore: true
769 cbbox:
770 - key: [0] # value of input x is 0 to select this box
771 bbox: !transform/property/bounding_box-1.0.0
772 intervals:
773 y: [1.0, 2.0]
774 - key: [3] # value of input x is 3 to select this box
775 bbox: !transform/property/bounding_box-1.0.0
776 intervals:
777 y: [4.0, 5.0]
778 """
779 buff = yaml_to_asdf(yaml)
780 with asdf.open(buff) as af:
781 model = af["model"]
782 assert model.bounding_box.order == "C"
783
784
785 @pytest.mark.filterwarnings("ignore:Unable to locate schema file for.*")
786 @pytest.mark.filterwarnings("ignore:.* not recognized, converting to raw Python data structure")
787 def test_compound_bbox_ignored_error():
788 yaml = """
789 model: !transform/concatenate-1.2.0
790 forward:
791 - !transform/concatenate-1.2.0
792 forward:
793 - !transform/shift-1.2.0
794 offset: 1.0
795 - !transform/shift-1.2.0
796 offset: 2.0
797 - !transform/shift-1.2.0
798 offset: 3.0
799 bounding_box: !transform/property/compound_bounding_box-1.0.0
800 selector_args:
801 - argument: x
802 ignore: true
803 cbbox:
804 - key: [0] # both value of input x is 0
805 bbox: !transform/property/bounding_box-1.0.0
806 intervals:
807 x0: [2.0, 3.0]
808 - key: [1] # both value of input x is 1
809 bbox: !transform/property/bounding_box-1.0.0
810 intervals:
811 x0: [6.0, 7.0]
812 ignore: [x1]
813 """
814 buff = yaml_to_asdf(yaml)
815 asdf.open(buff)
816
817
818 def test_serialize_bbox(tmp_path):
819 mdl = astropy_models.Const2D(3)
820 bind_bounding_box(mdl, (1, 2), ignored="y")
821 helpers.assert_model_roundtrip(mdl, tmp_path)
822
823
824 def test_serialize_cbbox(tmp_path):
825 mdl = astropy_models.Shift(1) & astropy_models.Scale(2) & astropy_models.Identity(1)
826 mdl.inputs = ("x", "y", "slit_id")
827 bounding_boxes = {
828 (0,): ((-0.5, 1047.5), (-0.5, 2047.5)),
829 (1,): ((-0.5, 3047.5), (-0.5, 4047.5)),
830 }
831 bounding_box = CompoundBoundingBox.validate(mdl, bounding_boxes, selector_args=[("slit_id", True)], order="F")
832 mdl.bounding_box = bounding_box
833
834 helpers.assert_model_roundtrip(mdl, tmp_path)