hash
stringlengths
64
64
content
stringlengths
0
1.51M
5b50c4c3620724027610051d4ad8fe08b538903a322fdb1848d127dc49f6efbc
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest import numpy as np import matplotlib.pyplot as plt from astropy.wcs import WCS from astropy.visualization.wcsaxes import WCSAxes from astropy.visualization.wcsaxes.frame import BaseFrame from astropy.tests.image_tests import IMAGE_REFERENCE_DIR from .test_images import BaseImageTests class HexagonalFrame(BaseFrame): spine_names = 'abcdef' def update_spines(self): xmin, xmax = self.parent_axes.get_xlim() ymin, ymax = self.parent_axes.get_ylim() ymid = 0.5 * (ymin + ymax) xmid1 = (xmin + xmax) / 4. xmid2 = (xmin + xmax) * 3. / 4. self['a'].data = np.array(([xmid1, ymin], [xmid2, ymin])) self['b'].data = np.array(([xmid2, ymin], [xmax, ymid])) self['c'].data = np.array(([xmax, ymid], [xmid2, ymax])) self['d'].data = np.array(([xmid2, ymax], [xmid1, ymax])) self['e'].data = np.array(([xmid1, ymax], [xmin, ymid])) self['f'].data = np.array(([xmin, ymid], [xmid1, ymin])) class TestFrame(BaseImageTests): @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_custom_frame(self): wcs = WCS(self.msx_header) fig = plt.figure(figsize=(4, 4)) ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], wcs=wcs, frame_class=HexagonalFrame) fig.add_axes(ax) ax.coords.grid(color='white') im = ax.imshow(np.ones((149, 149)), vmin=0., vmax=2., origin='lower', cmap=plt.cm.gist_heat) minpad = {} minpad['a'] = minpad['d'] = 1 minpad['b'] = minpad['c'] = minpad['e'] = minpad['f'] = 2.75 ax.coords['glon'].set_axislabel("Longitude", minpad=minpad) ax.coords['glon'].set_axislabel_position('ad') ax.coords['glat'].set_axislabel("Latitude", minpad=minpad) ax.coords['glat'].set_axislabel_position('bcef') ax.coords['glon'].set_ticklabel_position('ad') ax.coords['glat'].set_ticklabel_position('bcef') # Set limits so that no labels overlap ax.set_xlim(5.5, 100.5) ax.set_ylim(5.5, 110.5) # Clip the image to the frame im.set_clip_path(ax.coords.frame.patch) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_update_clip_path_rectangular(self, tmpdir): fig = plt.figure() ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], aspect='equal') fig.add_axes(ax) ax.set_xlim(0., 2.) ax.set_ylim(0., 2.) # Force drawing, which freezes the clip path returned by WCSAxes fig.savefig(tmpdir.join('nothing').strpath) ax.imshow(np.zeros((12, 4))) ax.set_xlim(-0.5, 3.5) ax.set_ylim(-0.5, 11.5) ax.coords[0].set_auto_axislabel(False) ax.coords[1].set_auto_axislabel(False) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_update_clip_path_nonrectangular(self, tmpdir): fig = plt.figure() ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], aspect='equal', frame_class=HexagonalFrame) fig.add_axes(ax) ax.set_xlim(0., 2.) ax.set_ylim(0., 2.) # Force drawing, which freezes the clip path returned by WCSAxes fig.savefig(tmpdir.join('nothing').strpath) ax.imshow(np.zeros((12, 4))) ax.set_xlim(-0.5, 3.5) ax.set_ylim(-0.5, 11.5) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_update_clip_path_change_wcs(self, tmpdir): # When WCS is changed, a new frame is created, so we need to make sure # that the path is carried over to the new frame. fig = plt.figure() ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], aspect='equal') fig.add_axes(ax) ax.set_xlim(0., 2.) ax.set_ylim(0., 2.) # Force drawing, which freezes the clip path returned by WCSAxes fig.savefig(tmpdir.join('nothing').strpath) ax.reset_wcs() ax.imshow(np.zeros((12, 4))) ax.set_xlim(-0.5, 3.5) ax.set_ylim(-0.5, 11.5) ax.coords[0].set_auto_axislabel(False) ax.coords[1].set_auto_axislabel(False) return fig def test_copy_frame_properties_change_wcs(self): # When WCS is changed, a new frame is created, so we need to make sure # that the color and linewidth are transferred over fig = plt.figure() ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8]) fig.add_axes(ax) ax.coords.frame.set_linewidth(5) ax.coords.frame.set_color('purple') ax.reset_wcs() assert ax.coords.frame.get_linewidth() == 5 assert ax.coords.frame.get_color() == 'purple'
2c9312049c8065ee51c68605846bdd76948d16154c2b977a83ca217cd9ae28d5
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest import numpy as np import matplotlib.pyplot as plt from astropy import units as u from astropy.wcs import WCS from astropy.visualization.wcsaxes import WCSAxes from .test_images import BaseImageTests from astropy.visualization.wcsaxes.transforms import CurvedTransform from astropy.tests.image_tests import IMAGE_REFERENCE_DIR # Create fake transforms that roughly mimic a polar projection class DistanceToLonLat(CurvedTransform): has_inverse = True def __init__(self, R=6e3): super().__init__() self.R = R def transform(self, xy): x, y = xy[:, 0], xy[:, 1] lam = np.degrees(np.arctan2(y, x)) phi = 90. - np.degrees(np.hypot(x, y) / self.R) return np.array((lam, phi)).transpose() transform_non_affine = transform def inverted(self): return LonLatToDistance(R=self.R) class LonLatToDistance(CurvedTransform): def __init__(self, R=6e3): super().__init__() self.R = R def transform(self, lamphi): lam, phi = lamphi[:, 0], lamphi[:, 1] r = np.radians(90 - phi) * self.R x = r * np.cos(np.radians(lam)) y = r * np.sin(np.radians(lam)) return np.array((x, y)).transpose() transform_non_affine = transform def inverted(self): return DistanceToLonLat(R=self.R) class TestTransformCoordMeta(BaseImageTests): @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_coords_overlay(self): # Set up a simple WCS that maps pixels to non-projected distances wcs = WCS(naxis=2) wcs.wcs.ctype = ['x', 'y'] wcs.wcs.cunit = ['km', 'km'] wcs.wcs.crpix = [614.5, 856.5] wcs.wcs.cdelt = [6.25, 6.25] wcs.wcs.crval = [0., 0.] fig = plt.figure(figsize=(4, 4)) ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], wcs=wcs) fig.add_axes(ax) s = DistanceToLonLat(R=6378.273) ax.coords['x'].set_ticklabel_position('') ax.coords['y'].set_ticklabel_position('') coord_meta = {} coord_meta['type'] = ('longitude', 'latitude') coord_meta['wrap'] = (360., None) coord_meta['unit'] = (u.deg, u.deg) coord_meta['name'] = 'lon', 'lat' overlay = ax.get_coords_overlay(s, coord_meta=coord_meta) overlay.grid(color='red') overlay['lon'].grid(color='red', linestyle='solid', alpha=0.3) overlay['lat'].grid(color='blue', linestyle='solid', alpha=0.3) overlay['lon'].set_ticklabel(size=7, exclude_overlapping=True) overlay['lat'].set_ticklabel(size=7, exclude_overlapping=True) overlay['lon'].set_ticklabel_position('brtl') overlay['lat'].set_ticklabel_position('brtl') overlay['lon'].set_ticks(spacing=10. * u.deg) overlay['lat'].set_ticks(spacing=10. * u.deg) ax.set_xlim(-0.5, 1215.5) ax.set_ylim(-0.5, 1791.5) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_coords_overlay_auto_coord_meta(self): fig = plt.figure(figsize=(4, 4)) ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], wcs=WCS(self.msx_header)) fig.add_axes(ax) ax.grid(color='red', alpha=0.5, linestyle='solid') overlay = ax.get_coords_overlay('fk5') # automatically sets coord_meta overlay.grid(color='black', alpha=0.5, linestyle='solid') overlay['ra'].set_ticks(color='black') overlay['dec'].set_ticks(color='black') ax.set_xlim(-0.5, 148.5) ax.set_ylim(-0.5, 148.5) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_direct_init(self): s = DistanceToLonLat(R=6378.273) coord_meta = {} coord_meta['type'] = ('longitude', 'latitude') coord_meta['wrap'] = (360., None) coord_meta['unit'] = (u.deg, u.deg) coord_meta['name'] = 'lon', 'lat' fig = plt.figure(figsize=(4, 4)) ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], transform=s, coord_meta=coord_meta) fig.add_axes(ax) ax.coords['lon'].grid(color='red', linestyle='solid', alpha=0.3) ax.coords['lat'].grid(color='blue', linestyle='solid', alpha=0.3) ax.coords['lon'].set_auto_axislabel(False) ax.coords['lat'].set_auto_axislabel(False) ax.coords['lon'].set_ticklabel(size=7, exclude_overlapping=True) ax.coords['lat'].set_ticklabel(size=7, exclude_overlapping=True) ax.coords['lon'].set_ticklabel_position('brtl') ax.coords['lat'].set_ticklabel_position('brtl') ax.coords['lon'].set_ticks(spacing=10. * u.deg) ax.coords['lat'].set_ticks(spacing=10. * u.deg) ax.set_xlim(-400., 500.) ax.set_ylim(-300., 400.) return fig
cab2561e730d1b1d50700bd749cb587b3dbc5679b6099d516d5552fd2d456df5
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest import numpy as np from numpy.testing import assert_almost_equal from matplotlib import rc_context from astropy import units as u from astropy.tests.helper import assert_quantity_allclose from astropy.units import UnitsError from astropy.visualization.wcsaxes.formatter_locator import AngleFormatterLocator, ScalarFormatterLocator class TestAngleFormatterLocator: def test_no_options(self): fl = AngleFormatterLocator() assert fl.values is None assert fl.number == 5 assert fl.spacing is None def test_too_many_options(self): with pytest.raises(ValueError) as exc: AngleFormatterLocator(values=[1., 2.], number=5) assert exc.value.args[0] == "At most one of values/number/spacing can be specified" with pytest.raises(ValueError) as exc: AngleFormatterLocator(values=[1., 2.], spacing=5. * u.deg) assert exc.value.args[0] == "At most one of values/number/spacing can be specified" with pytest.raises(ValueError) as exc: AngleFormatterLocator(number=5, spacing=5. * u.deg) assert exc.value.args[0] == "At most one of values/number/spacing can be specified" with pytest.raises(ValueError) as exc: AngleFormatterLocator(values=[1., 2.], number=5, spacing=5. * u.deg) assert exc.value.args[0] == "At most one of values/number/spacing can be specified" def test_values(self): fl = AngleFormatterLocator(values=[0.1, 1., 14.] * u.degree) assert fl.values.to_value(u.degree).tolist() == [0.1, 1., 14.] assert fl.number is None assert fl.spacing is None values, spacing = fl.locator(34.3, 55.4) assert_almost_equal(values.to_value(u.degree), [0.1, 1., 14.]) def test_number(self): fl = AngleFormatterLocator(number=7) assert fl.values is None assert fl.number == 7 assert fl.spacing is None values, spacing = fl.locator(34.3, 55.4) assert_almost_equal(values.to_value(u.degree), [35., 40., 45., 50., 55.]) values, spacing = fl.locator(34.3, 36.1) assert_almost_equal(values.to_value(u.degree), [34.5, 34.75, 35., 35.25, 35.5, 35.75, 36.]) fl.format = 'dd' values, spacing = fl.locator(34.3, 36.1) assert_almost_equal(values.to_value(u.degree), [35., 36.]) def test_spacing(self): with pytest.raises(TypeError) as exc: AngleFormatterLocator(spacing=3.) assert exc.value.args[0] == "spacing should be an astropy.units.Quantity instance with units of angle" fl = AngleFormatterLocator(spacing=3. * u.degree) assert fl.values is None assert fl.number is None assert fl.spacing == 3. * u.degree values, spacing = fl.locator(34.3, 55.4) assert_almost_equal(values.to_value(u.degree), [36., 39., 42., 45., 48., 51., 54.]) fl.spacing = 30. * u.arcmin values, spacing = fl.locator(34.3, 36.1) assert_almost_equal(values.to_value(u.degree), [34.5, 35., 35.5, 36.]) with pytest.warns(UserWarning, match=r'Spacing is too small'): fl.format = 'dd' values, spacing = fl.locator(34.3, 36.1) assert_almost_equal(values.to_value(u.degree), [35., 36.]) def test_minor_locator(self): fl = AngleFormatterLocator() values, spacing = fl.locator(34.3, 55.4) minor_values = fl.minor_locator(spacing, 5, 34.3, 55.4) assert_almost_equal(minor_values.to_value(u.degree), [36., 37., 38., 39., 41., 42., 43., 44., 46., 47., 48., 49., 51., 52., 53., 54.]) minor_values = fl.minor_locator(spacing, 2, 34.3, 55.4) assert_almost_equal(minor_values.to_value(u.degree), [37.5, 42.5, 47.5, 52.5]) fl.values = [0.1, 1., 14.] * u.degree values, spacing = fl.locator(34.3, 36.1) minor_values = fl.minor_locator(spacing, 2, 34.3, 55.4) assert_almost_equal(minor_values.to_value(u.degree), []) @pytest.mark.parametrize(('format', 'string'), [('dd', '15\xb0'), ('dd:mm', '15\xb024\''), ('dd:mm:ss', '15\xb023\'32"'), ('dd:mm:ss.s', '15\xb023\'32.0"'), ('dd:mm:ss.ssss', '15\xb023\'32.0316"'), ('hh', '1h'), ('hh:mm', '1h02m'), ('hh:mm:ss', '1h01m34s'), ('hh:mm:ss.s', '1h01m34.1s'), ('hh:mm:ss.ssss', '1h01m34.1354s'), ('d', '15\xb0'), ('d.d', '15.4\xb0'), ('d.dd', '15.39\xb0'), ('d.ddd', '15.392\xb0'), ('m', '924\''), ('m.m', '923.5\''), ('m.mm', '923.53\''), ('s', '55412"'), ('s.s', '55412.0"'), ('s.ss', '55412.03"'), ]) def test_format(self, format, string): fl = AngleFormatterLocator(number=5, format=format) assert fl.formatter([15.392231] * u.degree, None, format='ascii')[0] == string @pytest.mark.parametrize(('separator', 'format', 'string'), [(('deg', "'", '"'), 'dd', '15deg'), (('deg', "'", '"'), 'dd:mm', '15deg24\''), (('deg', "'", '"'), 'dd:mm:ss', '15deg23\'32"'), ((':', "-", 's'), 'dd:mm:ss.s', '15:23-32.0s'), (':', 'dd:mm:ss.s', '15:23:32.0'), ((':', ":", 's'), 'hh', '1:'), (('-', "-", 's'), 'hh:mm:ss.ssss', '1-01-34.1354s'), (('d', ":", '"'), 'd', '15\xb0'), (('d', ":", '"'), 'd.d', '15.4\xb0'), ]) def test_separator(self, separator, format, string): fl = AngleFormatterLocator(number=5, format=format) fl.sep = separator assert fl.formatter([15.392231] * u.degree, None)[0] == string def test_latex_format(self): fl = AngleFormatterLocator(number=5, format="dd:mm:ss") assert fl.formatter([15.392231] * u.degree, None)[0] == '15\xb023\'32"' with rc_context(rc={'text.usetex': True}): assert fl.formatter([15.392231] * u.degree, None)[0] == "$15^\\circ23{}^\\prime32{}^{\\prime\\prime}$" @pytest.mark.parametrize(('format'), ['x.xxx', 'dd.ss', 'dd:ss', 'mdd:mm:ss']) def test_invalid_formats(self, format): fl = AngleFormatterLocator(number=5) with pytest.raises(ValueError) as exc: fl.format = format assert exc.value.args[0] == "Invalid format: " + format @pytest.mark.parametrize(('format', 'base_spacing'), [('dd', 1. * u.deg), ('dd:mm', 1. * u.arcmin), ('dd:mm:ss', 1. * u.arcsec), ('dd:mm:ss.ss', 0.01 * u.arcsec), ('hh', 15. * u.deg), ('hh:mm', 15. * u.arcmin), ('hh:mm:ss', 15. * u.arcsec), ('hh:mm:ss.ss', 0.15 * u.arcsec), ('d', 1. * u.deg), ('d.d', 0.1 * u.deg), ('d.dd', 0.01 * u.deg), ('d.ddd', 0.001 * u.deg), ('m', 1. * u.arcmin), ('m.m', 0.1 * u.arcmin), ('m.mm', 0.01 * u.arcmin), ('s', 1. * u.arcsec), ('s.s', 0.1 * u.arcsec), ('s.ss', 0.01 * u.arcsec), ]) def test_base_spacing(self, format, base_spacing): fl = AngleFormatterLocator(number=5, format=format) assert fl.base_spacing == base_spacing def test_incorrect_spacing(self): fl = AngleFormatterLocator() fl.spacing = 0.032 * u.deg with pytest.warns(UserWarning, match=r'Spacing is not a multiple of base spacing'): fl.format = 'dd:mm:ss' assert_almost_equal(fl.spacing.to_value(u.arcsec), 115.) def test_decimal_values(self): # Regression test for a bug that meant that the spacing was not # determined correctly for decimal coordinates fl = AngleFormatterLocator() fl.format = 'd.dddd' assert_quantity_allclose(fl.locator(266.9730, 266.9750)[0], [266.9735, 266.9740, 266.9745, 266.9750] * u.deg) fl = AngleFormatterLocator(decimal=True, format_unit=u.hourangle, number=4) assert_quantity_allclose(fl.locator(266.9730, 266.9750)[0], [17.79825, 17.79830] * u.hourangle) def test_values_unit(self): # Make sure that the intrinsic unit and format unit are correctly # taken into account when using the locator fl = AngleFormatterLocator(unit=u.arcsec, format_unit=u.arcsec, decimal=True) assert_quantity_allclose(fl.locator(850, 2150)[0], [1000., 1200., 1400., 1600., 1800., 2000.] * u.arcsec) fl = AngleFormatterLocator(unit=u.arcsec, format_unit=u.degree, decimal=False) assert_quantity_allclose(fl.locator(850, 2150)[0], [15., 20., 25., 30., 35.] * u.arcmin) fl = AngleFormatterLocator(unit=u.arcsec, format_unit=u.hourangle, decimal=False) assert_quantity_allclose(fl.locator(850, 2150)[0], [60., 75., 90., 105., 120., 135.] * (15 * u.arcsec)) fl = AngleFormatterLocator(unit=u.arcsec) fl.format = 'dd:mm:ss' assert_quantity_allclose(fl.locator(0.9, 1.1)[0], [1] * u.arcsec) fl = AngleFormatterLocator(unit=u.arcsec, spacing=0.2 * u.arcsec) assert_quantity_allclose(fl.locator(0.3, 0.9)[0], [0.4, 0.6, 0.8] * u.arcsec) @pytest.mark.parametrize(('spacing', 'string'), [(2 * u.deg, '15\xb0'), (2 * u.arcmin, '15\xb024\''), (2 * u.arcsec, '15\xb023\'32"'), (0.1 * u.arcsec, '15\xb023\'32.0"')]) def test_formatter_no_format(self, spacing, string): fl = AngleFormatterLocator() assert fl.formatter([15.392231] * u.degree, spacing)[0] == string @pytest.mark.parametrize(('format_unit', 'decimal', 'show_decimal_unit', 'spacing', 'ascii', 'latex'), [(u.degree, False, True, 2 * u.degree, '15\xb0', r'$15^\circ$'), (u.degree, False, True, 2 * u.arcmin, '15\xb024\'', r'$15^\circ24{}^\prime$'), (u.degree, False, True, 2 * u.arcsec, '15\xb023\'32"', r'$15^\circ23{}^\prime32{}^{\prime\prime}$'), (u.degree, False, True, 0.1 * u.arcsec, '15\xb023\'32.0"', r'$15^\circ23{}^\prime32.0{}^{\prime\prime}$'), (u.hourangle, False, True, 15 * u.degree, '1h', r'$1^{\mathrm{h}}$'), (u.hourangle, False, True, 15 * u.arcmin, '1h02m', r'$1^{\mathrm{h}}02^{\mathrm{m}}$'), (u.hourangle, False, True, 15 * u.arcsec, '1h01m34s', r'$1^{\mathrm{h}}01^{\mathrm{m}}34^{\mathrm{s}}$'), (u.hourangle, False, True, 1.5 * u.arcsec, '1h01m34.1s', r'$1^{\mathrm{h}}01^{\mathrm{m}}34.1^{\mathrm{s}}$'), (u.degree, True, True, 15 * u.degree, '15\xb0', r'$15\mathrm{^\circ}$'), (u.degree, True, True, 0.12 * u.degree, '15.39\xb0', r'$15.39\mathrm{^\circ}$'), (u.degree, True, True, 0.0036 * u.arcsec, '15.392231\xb0', r'$15.392231\mathrm{^\circ}$'), (u.arcmin, True, True, 15 * u.degree, '924\'', r'$924\mathrm{^\prime}$'), (u.arcmin, True, True, 0.12 * u.degree, '923.5\'', r'$923.5\mathrm{^\prime}$'), (u.arcmin, True, True, 0.1 * u.arcmin, '923.5\'', r'$923.5\mathrm{^\prime}$'), (u.arcmin, True, True, 0.0002 * u.arcmin, '923.5339\'', r'$923.5339\mathrm{^\prime}$'), (u.arcsec, True, True, 0.01 * u.arcsec, '55412.03"', r'$55412.03\mathrm{^{\prime\prime}}$'), (u.arcsec, True, True, 0.001 * u.arcsec, '55412.032"', r'$55412.032\mathrm{^{\prime\prime}}$'), (u.mas, True, True, 0.001 * u.arcsec, '55412032mas', r'$55412032\mathrm{mas}$'), (u.degree, True, False, 15 * u.degree, '15', '15'), (u.degree, True, False, 0.12 * u.degree, '15.39', '15.39'), (u.degree, True, False, 0.0036 * u.arcsec, '15.392231', '15.392231'), (u.arcmin, True, False, 15 * u.degree, '924', '924'), (u.arcmin, True, False, 0.12 * u.degree, '923.5', '923.5'), (u.arcmin, True, False, 0.1 * u.arcmin, '923.5', '923.5'), (u.arcmin, True, False, 0.0002 * u.arcmin, '923.5339', '923.5339'), (u.arcsec, True, False, 0.01 * u.arcsec, '55412.03', '55412.03'), (u.arcsec, True, False, 0.001 * u.arcsec, '55412.032', '55412.032'), (u.mas, True, False, 0.001 * u.arcsec, '55412032', '55412032'), # Make sure that specifying None defaults to # decimal for non-degree or non-hour angles (u.arcsec, None, True, 0.01 * u.arcsec, '55412.03"', r'$55412.03\mathrm{^{\prime\prime}}$')]) def test_formatter_no_format_with_units(self, format_unit, decimal, show_decimal_unit, spacing, ascii, latex): # Check the formatter works when specifying the default units and # decimal behavior to use. fl = AngleFormatterLocator(unit=u.degree, format_unit=format_unit, decimal=decimal, show_decimal_unit=show_decimal_unit) assert fl.formatter([15.392231] * u.degree, spacing, format='ascii')[0] == ascii assert fl.formatter([15.392231] * u.degree, spacing, format='latex')[0] == latex def test_incompatible_unit_decimal(self): with pytest.raises(UnitsError) as exc: AngleFormatterLocator(unit=u.arcmin, decimal=False) assert exc.value.args[0] == 'Units should be degrees or hours when using non-decimal (sexagesimal) mode' class TestScalarFormatterLocator: def test_no_options(self): fl = ScalarFormatterLocator(unit=u.m) assert fl.values is None assert fl.number == 5 assert fl.spacing is None def test_too_many_options(self): with pytest.raises(ValueError) as exc: ScalarFormatterLocator(values=[1., 2.] * u.m, number=5) assert exc.value.args[0] == "At most one of values/number/spacing can be specified" with pytest.raises(ValueError) as exc: ScalarFormatterLocator(values=[1., 2.] * u.m, spacing=5. * u.m) assert exc.value.args[0] == "At most one of values/number/spacing can be specified" with pytest.raises(ValueError) as exc: ScalarFormatterLocator(number=5, spacing=5. * u.m) assert exc.value.args[0] == "At most one of values/number/spacing can be specified" with pytest.raises(ValueError) as exc: ScalarFormatterLocator(values=[1., 2.] * u.m, number=5, spacing=5. * u.m) assert exc.value.args[0] == "At most one of values/number/spacing can be specified" def test_values(self): fl = ScalarFormatterLocator(values=[0.1, 1., 14.] * u.m, unit=u.m) assert fl.values.value.tolist() == [0.1, 1., 14.] assert fl.number is None assert fl.spacing is None values, spacing = fl.locator(34.3, 55.4) assert_almost_equal(values.value, [0.1, 1., 14.]) def test_number(self): fl = ScalarFormatterLocator(number=7, unit=u.m) assert fl.values is None assert fl.number == 7 assert fl.spacing is None values, spacing = fl.locator(34.3, 55.4) assert_almost_equal(values.value, np.linspace(36., 54., 10)) values, spacing = fl.locator(34.3, 36.1) assert_almost_equal(values.value, np.linspace(34.4, 36, 9)) fl.format = 'x' values, spacing = fl.locator(34.3, 36.1) assert_almost_equal(values.value, [35., 36.]) def test_spacing(self): fl = ScalarFormatterLocator(spacing=3. * u.m) assert fl.values is None assert fl.number is None assert fl.spacing == 3. * u.m values, spacing = fl.locator(34.3, 55.4) assert_almost_equal(values.value, [36., 39., 42., 45., 48., 51., 54.]) fl.spacing = 0.5 * u.m values, spacing = fl.locator(34.3, 36.1) assert_almost_equal(values.value, [34.5, 35., 35.5, 36.]) with pytest.warns(UserWarning, match=r'Spacing is too small'): fl.format = 'x' values, spacing = fl.locator(34.3, 36.1) assert_almost_equal(values.value, [35., 36.]) def test_minor_locator(self): fl = ScalarFormatterLocator(unit=u.m) values, spacing = fl.locator(34.3, 55.4) minor_values = fl.minor_locator(spacing, 5, 34.3, 55.4) assert_almost_equal(minor_values.value, [36., 37., 38., 39., 41., 42., 43., 44., 46., 47., 48., 49., 51., 52., 53., 54.]) minor_values = fl.minor_locator(spacing, 2, 34.3, 55.4) assert_almost_equal(minor_values.value, [37.5, 42.5, 47.5, 52.5]) fl.values = [0.1, 1., 14.] * u.m values, spacing = fl.locator(34.3, 36.1) minor_values = fl.minor_locator(spacing, 2, 34.3, 55.4) assert_almost_equal(minor_values.value, []) @pytest.mark.parametrize(('format', 'string'), [('x', '15'), ('x.x', '15.4'), ('x.xx', '15.39'), ('x.xxx', '15.392'), ('%g', '15.3922'), ('%f', '15.392231'), ('%.2f', '15.39'), ('%.3f', '15.392')]) def test_format(self, format, string): fl = ScalarFormatterLocator(number=5, format=format, unit=u.m) assert fl.formatter([15.392231] * u.m, None)[0] == string @pytest.mark.parametrize(('format', 'string'), [('x', '1539'), ('x.x', '1539.2'), ('x.xx', '1539.22'), ('x.xxx', '1539.223')]) def test_format_unit(self, format, string): fl = ScalarFormatterLocator(number=5, format=format, unit=u.m) fl.format_unit = u.cm assert fl.formatter([15.392231] * u.m, None)[0] == string @pytest.mark.parametrize(('format'), ['dd', 'dd:mm', 'xx:mm', 'mx.xxx']) def test_invalid_formats(self, format): fl = ScalarFormatterLocator(number=5, unit=u.m) with pytest.raises(ValueError) as exc: fl.format = format assert exc.value.args[0] == "Invalid format: " + format @pytest.mark.parametrize(('format', 'base_spacing'), [('x', 1. * u.m), ('x.x', 0.1 * u.m), ('x.xxx', 0.001 * u.m)]) def test_base_spacing(self, format, base_spacing): fl = ScalarFormatterLocator(number=5, format=format, unit=u.m) assert fl.base_spacing == base_spacing def test_incorrect_spacing(self): fl = ScalarFormatterLocator(unit=u.m) fl.spacing = 0.032 * u.m with pytest.warns(UserWarning, match=r'Spacing is not a multiple of base spacing'): fl.format = 'x.xx' assert_almost_equal(fl.spacing.to_value(u.m), 0.03) def test_values_unit(self): # Make sure that the intrinsic unit and format unit are correctly # taken into account when using the locator fl = ScalarFormatterLocator(unit=u.cm, format_unit=u.m) assert_quantity_allclose(fl.locator(850, 2150)[0], [1000., 1200., 1400., 1600., 1800., 2000.] * u.cm) fl = ScalarFormatterLocator(unit=u.cm, format_unit=u.m) fl.format = 'x.x' assert_quantity_allclose(fl.locator(1, 19)[0], [10] * u.cm)
321a531012a746eba449bcc1233a617f83c3ea5304e8adfc9430fee11f4c4751
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os import warnings from textwrap import dedent import pytest import numpy as np import matplotlib.pyplot as plt from matplotlib.transforms import Affine2D, IdentityTransform from astropy.io import fits from astropy import units as u from astropy.wcs.wcsapi import BaseLowLevelWCS, SlicedLowLevelWCS from astropy.coordinates import SkyCoord from astropy.time import Time from astropy.units import Quantity from astropy.tests.image_tests import IMAGE_REFERENCE_DIR from astropy.utils.data import get_pkg_data_filename from astropy.wcs import WCS from astropy.visualization.wcsaxes.frame import RectangularFrame, RectangularFrame1D from astropy.visualization.wcsaxes.wcsapi import (WCSWorld2PixelTransform, transform_coord_meta_from_wcs, apply_slices) @pytest.fixture def plt_close(): yield plt.close('all') WCS2D = WCS(naxis=2) WCS2D.wcs.ctype = ['x', 'y'] WCS2D.wcs.cunit = ['km', 'km'] WCS2D.wcs.crpix = [614.5, 856.5] WCS2D.wcs.cdelt = [6.25, 6.25] WCS2D.wcs.crval = [0., 0.] WCS3D = WCS(naxis=3) WCS3D.wcs.ctype = ['x', 'y', 'z'] WCS3D.wcs.cunit = ['km', 'km', 'km'] WCS3D.wcs.crpix = [614.5, 856.5, 333] WCS3D.wcs.cdelt = [6.25, 6.25, 23] WCS3D.wcs.crval = [0., 0., 1.] @pytest.fixture def wcs_4d(): header = dedent("""\ WCSAXES = 4 / Number of coordinate axes CRPIX1 = 0.0 / Pixel coordinate of reference point CRPIX2 = 0.0 / Pixel coordinate of reference point CRPIX3 = 0.0 / Pixel coordinate of reference point CRPIX4 = 5.0 / Pixel coordinate of reference point CDELT1 = 0.4 / [min] Coordinate increment at reference point CDELT2 = 2E-11 / [m] Coordinate increment at reference point CDELT3 = 0.0027777777777778 / [deg] Coordinate increment at reference point CDELT4 = 0.0013888888888889 / [deg] Coordinate increment at reference point CUNIT1 = 'min' / Units of coordinate increment and value CUNIT2 = 'm' / Units of coordinate increment and value CUNIT3 = 'deg' / Units of coordinate increment and value CUNIT4 = 'deg' / Units of coordinate increment and value CTYPE1 = 'TIME' / Coordinate type code CTYPE2 = 'WAVE' / Vacuum wavelength (linear) CTYPE3 = 'HPLT-TAN' / Coordinate type codegnomonic projection CTYPE4 = 'HPLN-TAN' / Coordinate type codegnomonic projection CRVAL1 = 0.0 / [min] Coordinate value at reference point CRVAL2 = 0.0 / [m] Coordinate value at reference point CRVAL3 = 0.0 / [deg] Coordinate value at reference point CRVAL4 = 0.0 / [deg] Coordinate value at reference point LONPOLE = 180.0 / [deg] Native longitude of celestial pole LATPOLE = 0.0 / [deg] Native latitude of celestial pole """) return WCS(header=fits.Header.fromstring(header, sep='\n')) @pytest.fixture def cube_wcs(): cube_header = get_pkg_data_filename('data/cube_header') header = fits.Header.fromtextfile(cube_header) return WCS(header=header) def test_shorthand_inversion(): """ Test that the Matplotlib subtraction shorthand for composing and inverting transformations works. """ w1 = WCS(naxis=2) w1.wcs.ctype = ['RA---TAN', 'DEC--TAN'] w1.wcs.crpix = [256.0, 256.0] w1.wcs.cdelt = [-0.05, 0.05] w1.wcs.crval = [120.0, -19.0] w2 = WCS(naxis=2) w2.wcs.ctype = ['RA---SIN', 'DEC--SIN'] w2.wcs.crpix = [256.0, 256.0] w2.wcs.cdelt = [-0.05, 0.05] w2.wcs.crval = [235.0, +23.7] t1 = WCSWorld2PixelTransform(w1) t2 = WCSWorld2PixelTransform(w2) assert t1 - t2 == t1 + t2.inverted() assert t1 - t2 != t2.inverted() + t1 assert t1 - t1 == IdentityTransform() # We add Affine2D to catch the fact that in Matplotlib, having a Composite # transform can end up in more strict requirements for the dimensionality. def test_2d(): world = np.ones((10, 2)) w1 = WCSWorld2PixelTransform(WCS2D) + Affine2D() pixel = w1.transform(world) world_2 = w1.inverted().transform(pixel) np.testing.assert_allclose(world, world_2) def test_3d(): world = np.ones((10, 2)) w1 = WCSWorld2PixelTransform(WCS3D[:, 0, :]) + Affine2D() pixel = w1.transform(world) world_2 = w1.inverted().transform(pixel) np.testing.assert_allclose(world[:, 0], world_2[:, 0]) np.testing.assert_allclose(world[:, 1], world_2[:, 1]) def test_coord_type_from_ctype(cube_wcs): _, coord_meta = transform_coord_meta_from_wcs(cube_wcs, RectangularFrame, slices=(50, 'y', 'x')) axislabel_position = coord_meta['default_axislabel_position'] ticklabel_position = coord_meta['default_ticklabel_position'] ticks_position = coord_meta['default_ticks_position'] # These axes are swapped due to the pixel derivatives assert axislabel_position == ['l', 'r', 'b'] assert ticklabel_position == ['l', 'r', 'b'] assert ticks_position == ['l', 'r', 'b'] wcs = WCS(naxis=2) wcs.wcs.ctype = ['GLON-TAN', 'GLAT-TAN'] wcs.wcs.crpix = [256.0] * 2 wcs.wcs.cdelt = [-0.05] * 2 wcs.wcs.crval = [50.0] * 2 wcs.wcs.cname = ['Longitude', ''] wcs.wcs.set() _, coord_meta = transform_coord_meta_from_wcs(wcs, RectangularFrame) assert coord_meta['type'] == ['longitude', 'latitude'] assert coord_meta['format_unit'] == [u.deg, u.deg] assert coord_meta['wrap'] == [None, None] assert coord_meta['default_axis_label'] == ['Longitude', 'pos.galactic.lat'] assert coord_meta['name'] == [('pos.galactic.lon', 'glon-tan', 'glon', 'Longitude'), ('pos.galactic.lat', 'glat-tan', 'glat')] wcs = WCS(naxis=2) wcs.wcs.ctype = ['HPLN-TAN', 'HPLT-TAN'] wcs.wcs.crpix = [256.0] * 2 wcs.wcs.cdelt = [-0.05] * 2 wcs.wcs.crval = [50.0] * 2 wcs.wcs.set() _, coord_meta = transform_coord_meta_from_wcs(wcs, RectangularFrame) assert coord_meta['type'] == ['longitude', 'latitude'] assert coord_meta['format_unit'] == [u.arcsec, u.arcsec] assert coord_meta['wrap'] == [180., None] _, coord_meta = transform_coord_meta_from_wcs(wcs, RectangularFrame, slices=('y', 'x')) axislabel_position = coord_meta['default_axislabel_position'] ticklabel_position = coord_meta['default_ticklabel_position'] ticks_position = coord_meta['default_ticks_position'] # These axes should be swapped because of slices assert axislabel_position == ['l', 'b'] assert ticklabel_position == ['l', 'b'] assert ticks_position == ['bltr', 'bltr'] wcs = WCS(naxis=2) wcs.wcs.ctype = ['HGLN-TAN', 'HGLT-TAN'] wcs.wcs.crpix = [256.0] * 2 wcs.wcs.cdelt = [-0.05] * 2 wcs.wcs.crval = [50.0] * 2 wcs.wcs.set() _, coord_meta = transform_coord_meta_from_wcs(wcs, RectangularFrame) assert coord_meta['type'] == ['longitude', 'latitude'] assert coord_meta['format_unit'] == [u.deg, u.deg] assert coord_meta['wrap'] == [180., None] wcs = WCS(naxis=2) wcs.wcs.ctype = ['CRLN-TAN', 'CRLT-TAN'] wcs.wcs.crpix = [256.0] * 2 wcs.wcs.cdelt = [-0.05] * 2 wcs.wcs.crval = [50.0] * 2 wcs.wcs.set() _, coord_meta = transform_coord_meta_from_wcs(wcs, RectangularFrame) assert coord_meta['type'] == ['longitude', 'latitude'] assert coord_meta['format_unit'] == [u.deg, u.deg] assert coord_meta['wrap'] == [360., None] wcs = WCS(naxis=2) wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN'] wcs.wcs.crpix = [256.0] * 2 wcs.wcs.cdelt = [-0.05] * 2 wcs.wcs.crval = [50.0] * 2 wcs.wcs.set() _, coord_meta = transform_coord_meta_from_wcs(wcs, RectangularFrame) assert coord_meta['type'] == ['longitude', 'latitude'] assert coord_meta['format_unit'] == [u.hourangle, u.deg] assert coord_meta['wrap'] == [None, None] wcs = WCS(naxis=2) wcs.wcs.ctype = ['spam', 'spam'] wcs.wcs.crpix = [256.0] * 2 wcs.wcs.cdelt = [-0.05] * 2 wcs.wcs.crval = [50.0] * 2 wcs.wcs.set() _, coord_meta = transform_coord_meta_from_wcs(wcs, RectangularFrame) assert coord_meta['type'] == ['scalar', 'scalar'] assert coord_meta['format_unit'] == [u.one, u.one] assert coord_meta['wrap'] == [None, None] def test_coord_type_1d_1d_wcs(): wcs = WCS(naxis=1) wcs.wcs.ctype = ['WAVE'] wcs.wcs.crpix = [256.0] wcs.wcs.cdelt = [-0.05] wcs.wcs.crval = [50.0] wcs.wcs.set() _, coord_meta = transform_coord_meta_from_wcs(wcs, RectangularFrame1D) assert coord_meta['type'] == ['scalar'] assert coord_meta['format_unit'] == [u.m] assert coord_meta['wrap'] == [None] def test_coord_type_1d_2d_wcs_correlated(): wcs = WCS(naxis=2) wcs.wcs.ctype = ['GLON-TAN', 'GLAT-TAN'] wcs.wcs.crpix = [256.0] * 2 wcs.wcs.cdelt = [-0.05] * 2 wcs.wcs.crval = [50.0] * 2 wcs.wcs.set() _, coord_meta = transform_coord_meta_from_wcs(wcs, RectangularFrame1D, slices=('x', 0)) assert coord_meta['type'] == ['longitude', 'latitude'] assert coord_meta['format_unit'] == [u.deg, u.deg] assert coord_meta['wrap'] == [None, None] assert coord_meta['visible'] == [True, True] def test_coord_type_1d_2d_wcs_uncorrelated(): wcs = WCS(naxis=2) wcs.wcs.ctype = ['WAVE', 'UTC'] wcs.wcs.crpix = [256.0] * 2 wcs.wcs.cdelt = [-0.05] * 2 wcs.wcs.crval = [50.0] * 2 wcs.wcs.cunit = ['nm', 's'] wcs.wcs.set() _, coord_meta = transform_coord_meta_from_wcs(wcs, RectangularFrame1D, slices=('x', 0)) assert coord_meta['type'] == ['scalar', 'scalar'] assert coord_meta['format_unit'] == [u.m, u.s] assert coord_meta['wrap'] == [None, None] assert coord_meta['visible'] == [True, False] def test_coord_meta_4d(wcs_4d): _, coord_meta = transform_coord_meta_from_wcs(wcs_4d, RectangularFrame, slices=(0, 0, 'x', 'y')) axislabel_position = coord_meta['default_axislabel_position'] ticklabel_position = coord_meta['default_ticklabel_position'] ticks_position = coord_meta['default_ticks_position'] assert axislabel_position == ['', '', 'b', 'l'] assert ticklabel_position == ['', '', 'b', 'l'] assert ticks_position == ['', '', 'bltr', 'bltr'] def test_coord_meta_4d_line_plot(wcs_4d): _, coord_meta = transform_coord_meta_from_wcs(wcs_4d, RectangularFrame1D, slices=(0, 0, 0, 'x')) axislabel_position = coord_meta['default_axislabel_position'] ticklabel_position = coord_meta['default_ticklabel_position'] ticks_position = coord_meta['default_ticks_position'] # These axes are swapped due to the pixel derivatives assert axislabel_position == ['', '', 't', 'b'] assert ticklabel_position == ['', '', 't', 'b'] assert ticks_position == ['', '', 't', 'b'] @pytest.fixture def sub_wcs(wcs_4d, wcs_slice): return SlicedLowLevelWCS(wcs_4d, wcs_slice) @pytest.mark.parametrize(("wcs_slice", "wcsaxes_slices", "world_map", "ndim"), [ (np.s_[...], [0,0,'x','y'], (2, 3), 2), (np.s_[...], [0,'x',0,'y'], (1, 2, 3), 3), (np.s_[...], ['x',0,0,'y'], (0, 2, 3), 3), (np.s_[...], ['x','y',0,0], (0, 1), 2), (np.s_[:,:,0,:], [0, 'x', 'y'], (1, 2), 2), (np.s_[:,:,0,:], ['x', 0, 'y'], (0, 1, 2), 3), (np.s_[:,:,0,:], ['x', 'y', 0], (0, 1, 2), 3), (np.s_[:,0,:,:], ['x', 'y', 0], (0, 1), 2), ]) def test_apply_slices(sub_wcs, wcs_slice, wcsaxes_slices, world_map, ndim): transform_wcs, _, out_world_map = apply_slices(sub_wcs, wcsaxes_slices) assert transform_wcs.world_n_dim == ndim assert out_world_map == world_map # parametrize here to pass to the fixture @pytest.mark.parametrize("wcs_slice", [np.s_[:,:,0,:]]) def test_sliced_ND_input(wcs_4d, sub_wcs, wcs_slice, plt_close): slices_wcsaxes = [0, 'x', 'y'] for sub_wcs in (sub_wcs, SlicedLowLevelWCS(wcs_4d, wcs_slice)): with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=FutureWarning) _, coord_meta = transform_coord_meta_from_wcs(sub_wcs, RectangularFrame, slices=slices_wcsaxes) assert all(len(x) == 3 for x in coord_meta.values()) assert coord_meta['name'] == ['time', ('custom:pos.helioprojective.lat', 'hplt-tan', 'hplt'), ('custom:pos.helioprojective.lon', 'hpln-tan', 'hpln')] assert coord_meta['type'] == ['scalar', 'latitude', 'longitude'] assert coord_meta['wrap'] == [None, None, 180.0] assert coord_meta['unit'] == [u.Unit("min"), u.Unit("deg"), u.Unit("deg")] assert coord_meta['visible'] == [False, True, True] assert coord_meta['format_unit'] == [u.Unit("min"), u.Unit("arcsec"), u.Unit("arcsec")] assert coord_meta['default_axislabel_position'] == ['', 'b', 'l'] assert coord_meta['default_ticklabel_position'] == ['', 'b', 'l'] assert coord_meta['default_ticks_position'] == ['', 'bltr', 'bltr'] # Validate the axes initialize correctly plt.subplot(projection=sub_wcs, slices=slices_wcsaxes) class LowLevelWCS5D(BaseLowLevelWCS): pixel_dim = 2 @property def pixel_n_dim(self): return self.pixel_dim @property def world_n_dim(self): return 5 @property def world_axis_physical_types(self): return ['em.freq', 'time', 'pos.eq.ra', 'pos.eq.dec', 'phys.polarization.stokes'] @property def world_axis_units(self): return ['Hz', 'day', 'deg', 'deg', ''] @property def world_axis_names(self): return ['Frequency', '', 'RA', 'DEC', ''] def pixel_to_world_values(self, *pixel_arrays): pixel_arrays = (list(pixel_arrays) * 3)[:-1] # make list have 5 elements return [np.asarray(pix) * scale for pix, scale in zip(pixel_arrays, [10, 0.2, 0.4, 0.39, 2])] def world_to_pixel_values(self, *world_arrays): world_arrays = world_arrays[:2] # make list have 2 elements return [np.asarray(world) / scale for world, scale in zip(world_arrays, [10, 0.2])] @property def world_axis_object_components(self): return [('freq', 0, 'value'), ('time', 0, 'mjd'), ('celestial', 0, 'spherical.lon.degree'), ('celestial', 1, 'spherical.lat.degree'), ('stokes', 0, 'value')] @property def world_axis_object_classes(self): return {'celestial': (SkyCoord, (), {'unit': 'deg'}), 'time': (Time, (), {'format': 'mjd'}), 'freq': (Quantity, (), {'unit': 'Hz'}), 'stokes': (Quantity, (), {'unit': 'one'})} def test_edge_axes(): # Check that axes on the edge of a spherical projection are shown properley # (see https://github.com/astropy/astropy/issues/10441) shape = [180, 360] data = np.random.rand(*shape) header = {'wcsaxes': 2, 'crpix1': 180.5, 'crpix2': 90.5, 'cdelt1': 1.0, 'cdelt2': 1.0, 'cunit1': 'deg', 'cunit2': 'deg', 'ctype1': 'CRLN-CAR', 'ctype2': 'CRLT-CAR', 'crval1': 0.0, 'crval2': 0.0, 'lonpole': 0.0, 'latpole': 90.0, } wcs = WCS(header) fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection=wcs) ax.imshow(data, origin='lower') # By default the x- and y- axes should be drawn lon = ax.coords[0] lat = ax.coords[1] fig.canvas.draw() np.testing.assert_equal(lon.ticks.world['b'], np.array([90.0, 180.0, 180.0, 270.0, 0.0])) np.testing.assert_equal(lat.ticks.world['l'], np.array([-90.0, -60.0, -30.0, 0.0, 30.0, 60.0, 90.0])) def test_coord_meta_wcsapi(): wcs = LowLevelWCS5D() wcs.pixel_dim = 5 _, coord_meta = transform_coord_meta_from_wcs(wcs, RectangularFrame, slices=[0, 0, 'x', 'y', 0]) assert coord_meta['name'] == [('em.freq', 'Frequency'), 'time', ('pos.eq.ra', 'RA'), ('pos.eq.dec', 'DEC'), 'phys.polarization.stokes'] assert coord_meta['type'] == ['scalar', 'scalar', 'longitude', 'latitude', 'scalar'] assert coord_meta['wrap'] == [None, None, None, None, None] assert coord_meta['unit'] == [u.Unit("Hz"), u.Unit("d"), u.Unit("deg"), u.Unit("deg"), u.one] assert coord_meta['visible'] == [True, True, True, True, True] assert coord_meta['format_unit'] == [u.Unit("Hz"), u.Unit("d"), u.Unit("hourangle"), u.Unit("deg"), u.one] assert coord_meta['default_axislabel_position'] == ['b', 'l', 't', 'r', ''] assert coord_meta['default_ticklabel_position'] == ['b', 'l', 't', 'r', ''] assert coord_meta['default_ticks_position'] == ['b', 'l', 't', 'r', ''] assert coord_meta['default_axis_label'] == ['Frequency', 'time', 'RA', 'DEC', 'phys.polarization.stokes'] @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_wcsapi_5d_with_names(plt_close): # Test for plotting image and also setting values of ticks fig = plt.figure(figsize=(6, 6)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection=LowLevelWCS5D()) ax.set_xlim(-0.5, 148.5) ax.set_ylim(-0.5, 148.5) return fig
3fa6c0004abba4f5ed2edf1e7994963172018ea41ae51befcae547dbe6cf4a7c
# Licensed under a 3-clause BSD style license - see LICENSE.rst import matplotlib.pyplot as plt import pytest from matplotlib.backend_bases import KeyEvent import numpy as np import astropy.units as u from astropy.coordinates import FK5, SkyCoord from astropy.io import fits from astropy.time import Time from astropy.utils.data import get_pkg_data_filename from astropy.visualization.wcsaxes.core import WCSAxes from astropy.wcs import WCS from astropy.coordinates import galactocentric_frame_defaults from .test_images import BaseImageTests class TestDisplayWorldCoordinate(BaseImageTests): def teardown_method(self, method): plt.close('all') def test_overlay_coords(self, ignore_matplotlibrc, tmpdir): wcs = WCS(self.msx_header) fig = plt.figure(figsize=(4, 4)) canvas = fig.canvas ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=wcs) fig.add_axes(ax) # On some systems, fig.canvas.draw is not enough to force a draw, so we # save to a temporary file. fig.savefig(tmpdir.join('test1.png').strpath) # Testing default displayed world coordinates string_world = ax._display_world_coords(0.523412, 0.518311) assert string_world == '0\xb029\'45" -0\xb029\'20" (world)' # Test pixel coordinates event1 = KeyEvent('test_pixel_coords', canvas, 'w') fig.canvas.key_press_event(event1.key, guiEvent=event1) string_pixel = ax._display_world_coords(0.523412, 0.523412) assert string_pixel == "0.523412 0.523412 (pixel)" event3 = KeyEvent('test_pixel_coords', canvas, 'w') fig.canvas.key_press_event(event3.key, guiEvent=event3) # Test that it still displays world coords when there are no overlay coords string_world2 = ax._display_world_coords(0.523412, 0.518311) assert string_world2 == '0\xb029\'45" -0\xb029\'20" (world)' overlay = ax.get_coords_overlay('fk5') # Regression test for bug that caused format to always be taken from # main world coordinates. overlay[0].set_major_formatter('d.ddd') # On some systems, fig.canvas.draw is not enough to force a draw, so we # save to a temporary file. fig.savefig(tmpdir.join('test2.png').strpath) event4 = KeyEvent('test_pixel_coords', canvas, 'w') fig.canvas.key_press_event(event4.key, guiEvent=event4) # Test that it displays the overlay world coordinates string_world3 = ax._display_world_coords(0.523412, 0.518311) assert string_world3 == '267.176\xb0 -28\xb045\'56" (world, overlay 1)' overlay = ax.get_coords_overlay(FK5()) # Regression test for bug that caused format to always be taken from # main world coordinates. overlay[0].set_major_formatter('d.ddd') # On some systems, fig.canvas.draw is not enough to force a draw, so we # save to a temporary file. fig.savefig(tmpdir.join('test3.png').strpath) event5 = KeyEvent('test_pixel_coords', canvas, 'w') fig.canvas.key_press_event(event4.key, guiEvent=event4) # Test that it displays the overlay world coordinates string_world4 = ax._display_world_coords(0.523412, 0.518311) assert string_world4 == '267.176\xb0 -28\xb045\'56" (world, overlay 2)' overlay = ax.get_coords_overlay(FK5(equinox=Time("J2030"))) # Regression test for bug that caused format to always be taken from # main world coordinates. overlay[0].set_major_formatter('d.ddd') # On some systems, fig.canvas.draw is not enough to force a draw, so we # save to a temporary file. fig.savefig(tmpdir.join('test4.png').strpath) event6 = KeyEvent('test_pixel_coords', canvas, 'w') fig.canvas.key_press_event(event5.key, guiEvent=event6) # Test that it displays the overlay world coordinates string_world5 = ax._display_world_coords(0.523412, 0.518311) assert string_world5 == '267.652\xb0 -28\xb046\'23" (world, overlay 3)' def test_cube_coords(self, ignore_matplotlibrc, tmpdir): wcs = WCS(self.cube_header) fig = plt.figure(figsize=(4, 4)) canvas = fig.canvas ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=wcs, slices=('y', 50, 'x')) fig.add_axes(ax) # On some systems, fig.canvas.draw is not enough to force a draw, so we # save to a temporary file. fig.savefig(tmpdir.join('test.png').strpath) # Testing default displayed world coordinates string_world = ax._display_world_coords(0.523412, 0.518311) assert string_world == '3h26m52.0s 30\xb037\'17\" 2563 (world)' # Test pixel coordinates event1 = KeyEvent('test_pixel_coords', canvas, 'w') fig.canvas.key_press_event(event1.key, guiEvent=event1) string_pixel = ax._display_world_coords(0.523412, 0.523412) assert string_pixel == "0.523412 0.523412 (pixel)" def test_cube_coords_uncorr_slicing(self, ignore_matplotlibrc, tmpdir): # Regression test for a bug that occurred with coordinate formatting if # some dimensions were uncorrelated and sliced out. wcs = WCS(self.cube_header) fig = plt.figure(figsize=(4, 4)) canvas = fig.canvas ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=wcs, slices=('x', 'y', 2)) fig.add_axes(ax) # On some systems, fig.canvas.draw is not enough to force a draw, so we # save to a temporary file. fig.savefig(tmpdir.join('test.png').strpath) # Testing default displayed world coordinates string_world = ax._display_world_coords(0.523412, 0.518311) assert string_world == '3h26m56.6s 30\xb018\'19\" (world)' # Test pixel coordinates event1 = KeyEvent('test_pixel_coords', canvas, 'w') fig.canvas.key_press_event(event1.key, guiEvent=event1) string_pixel = ax._display_world_coords(0.523412, 0.523412) assert string_pixel == "0.523412 0.523412 (pixel)" def test_plot_coord_3d_transform(self): wcs = WCS(self.msx_header) with galactocentric_frame_defaults.set('latest'): coord = SkyCoord(0 * u.kpc, 0 * u.kpc, 0 * u.kpc, frame='galactocentric') fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=wcs) point, = ax.plot_coord(coord, 'ro') np.testing.assert_allclose(point.get_xydata()[0], [0, 0], atol=1e-4)
f0ea20139c8ca96d6303b8bd914db5b89c4060ef0080ff59c0ecc9cb15caf4ba
import numpy as np import pytest from matplotlib.lines import Path from astropy.visualization.wcsaxes.grid_paths import get_lon_lat_path @pytest.mark.parametrize('step_in_degrees', [10, 1, 0.01]) def test_round_trip_visibility(step_in_degrees): zero = np.zeros(100) # The pixel values are irrelevant for this test pixel = np.stack([zero, zero]).T # Create a grid line of constant latitude with a point every step line = np.stack([np.arange(100), zero]).T * step_in_degrees # Create a modified grid line where the point spacing is larger by 5% # Starting with point 20, the discrepancy between `line` and `line_round` is greater than `step` line_round = line * 1.05 # Perform the round-trip check path = get_lon_lat_path(line, pixel, line_round) # The grid line should be visible for only the initial part line (19 points) codes_check = np.full(100, Path.MOVETO) codes_check[line_round[:, 0] - line[:, 0] < step_in_degrees] = Path.LINETO assert np.all(path.codes[1:] == codes_check[1:])
dd530b6f93519674f8e30b10755c653a18bf1e19e107e1867030fcfb228ff4cb
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os from unittest.mock import patch import pytest import matplotlib.pyplot as plt from astropy.wcs import WCS from astropy.io import fits from astropy.utils.data import get_pkg_data_filename from astropy.visualization.wcsaxes.core import WCSAxes from astropy import units as u MSX_HEADER = fits.Header.fromtextfile(get_pkg_data_filename('data/msx_header')) def teardown_function(function): plt.close('all') def test_getaxislabel(ignore_matplotlibrc): fig = plt.figure() ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], aspect='equal') ax.coords[0].set_axislabel("X") ax.coords[1].set_axislabel("Y") assert ax.coords[0].get_axislabel() == "X" assert ax.coords[1].get_axislabel() == "Y" @pytest.fixture def ax(): fig = plt.figure() ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], aspect='equal') fig.add_axes(ax) return ax def assert_label_draw(ax, x_label, y_label): ax.coords[0].set_axislabel("Label 1") ax.coords[1].set_axislabel("Label 2") with patch.object(ax.coords[0].axislabels, 'set_position') as pos1: with patch.object(ax.coords[1].axislabels, 'set_position') as pos2: ax.figure.canvas.draw() assert pos1.call_count == x_label assert pos2.call_count == y_label def test_label_visibility_rules_default(ignore_matplotlibrc, ax): assert_label_draw(ax, True, True) def test_label_visibility_rules_label(ignore_matplotlibrc, ax): ax.coords[0].set_ticklabel_visible(False) ax.coords[1].set_ticks(values=[-9999]*u.one) assert_label_draw(ax, False, False) def test_label_visibility_rules_ticks(ignore_matplotlibrc, ax): ax.coords[0].set_axislabel_visibility_rule('ticks') ax.coords[1].set_axislabel_visibility_rule('ticks') ax.coords[0].set_ticklabel_visible(False) ax.coords[1].set_ticks(values=[-9999]*u.one) assert_label_draw(ax, True, False) def test_label_visibility_rules_always(ignore_matplotlibrc, ax): ax.coords[0].set_axislabel_visibility_rule('always') ax.coords[1].set_axislabel_visibility_rule('always') ax.coords[0].set_ticklabel_visible(False) ax.coords[1].set_ticks(values=[-9999]*u.one) assert_label_draw(ax, True, True) def test_format_unit(tmpdir): fig = plt.figure() ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=WCS(MSX_HEADER)) fig.add_axes(ax) # Force a draw which is required for format_coord to work ax.figure.canvas.draw() ori_fu = ax.coords[1].get_format_unit() assert ori_fu == "deg" ax.coords[1].set_format_unit("arcsec") fu = ax.coords[1].get_format_unit() assert fu == "arcsec" def test_set_separator(tmpdir): fig = plt.figure() ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=WCS(MSX_HEADER)) fig.add_axes(ax) # Force a draw which is required for format_coord to work ax.figure.canvas.draw() ax.coords[1].set_format_unit('deg') assert ax.coords[1].format_coord(4) == '4\xb000\'00\"' ax.coords[1].set_separator((':', ':', '')) assert ax.coords[1].format_coord(4) == '4:00:00' ax.coords[1].set_separator('abc') assert ax.coords[1].format_coord(4) == '4a00b00c' ax.coords[1].set_separator(None) assert ax.coords[1].format_coord(4) == '4\xb000\'00\"'
1db69d66d3aed8614e9dd14296386ece7f91cc3cf772965535c33107273bfd0e
# Licensed under a 3-clause BSD style license - see LICENSE.rst import matplotlib.lines import matplotlib.pyplot as plt import pytest from matplotlib import rc_context from matplotlib.patches import Circle, Rectangle import numpy as np from astropy import units as u from astropy.coordinates import SkyCoord from astropy.io import fits from astropy.tests.image_tests import IMAGE_REFERENCE_DIR from astropy.utils.data import get_pkg_data_filename from astropy.utils.exceptions import AstropyUserWarning from astropy.visualization.wcsaxes import WCSAxes from astropy.visualization.wcsaxes.frame import EllipticalFrame from astropy.visualization.wcsaxes.patches import Quadrangle, SphericalCircle from astropy.wcs import WCS class BaseImageTests: @classmethod def setup_class(cls): msx_header = get_pkg_data_filename('data/msx_header') cls.msx_header = fits.Header.fromtextfile(msx_header) rosat_header = get_pkg_data_filename('data/rosat_header') cls.rosat_header = fits.Header.fromtextfile(rosat_header) twoMASS_k_header = get_pkg_data_filename('data/2MASS_k_header') cls.twoMASS_k_header = fits.Header.fromtextfile(twoMASS_k_header) cube_header = get_pkg_data_filename('data/cube_header') cls.cube_header = fits.Header.fromtextfile(cube_header) slice_header = get_pkg_data_filename('data/slice_header') cls.slice_header = fits.Header.fromtextfile(slice_header) def teardown_method(self, method): plt.close('all') class TestBasic(BaseImageTests): @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_image_plot(self): # Test for plotting image and also setting values of ticks fig = plt.figure(figsize=(6, 6)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection=WCS(self.msx_header), aspect='equal') ax.set_xlim(-0.5, 148.5) ax.set_ylim(-0.5, 148.5) ax.coords[0].set_ticks([-0.30, 0., 0.20] * u.degree, size=5, width=1) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_axes_off(self): # Test for turning the axes off fig = plt.figure(figsize=(3, 3)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection=WCS(self.msx_header)) ax.imshow(np.arange(12).reshape((3, 4))) ax.set_axis_off() return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=1.5, style={}) @pytest.mark.parametrize('axisbelow', [True, False, 'line']) def test_axisbelow(self, axisbelow): # Test that tick marks, labels, and gridlines are drawn with the # correct zorder controlled by the axisbelow property. fig = plt.figure(figsize=(6, 6)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection=WCS(self.msx_header), aspect='equal') ax.set_axisbelow(axisbelow) ax.set_xlim(-0.5, 148.5) ax.set_ylim(-0.5, 148.5) ax.coords[0].set_ticks([-0.30, 0., 0.20] * u.degree, size=5, width=1) ax.grid() ax.coords[0].set_auto_axislabel(False) ax.coords[1].set_auto_axislabel(False) # Add an image (default zorder=0). ax.imshow(np.zeros((64, 64))) # Add a patch (default zorder=1). r = Rectangle((30., 50.), 60., 50., facecolor='green', edgecolor='red') ax.add_patch(r) # Add a line (default zorder=2). ax.plot([32, 128], [32, 128], linewidth=10) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_contour_overlay(self): # Test for overlaying contours on images path = get_pkg_data_filename('galactic_center/gc_msx_e.fits') with fits.open(path) as pf: data = pf[0].data wcs_msx = WCS(self.msx_header) fig = plt.figure(figsize=(6, 6)) ax = fig.add_axes([0.15, 0.15, 0.8, 0.8], projection=WCS(self.twoMASS_k_header), aspect='equal') ax.set_xlim(-0.5, 720.5) ax.set_ylim(-0.5, 720.5) # Overplot contour ax.contour(data, transform=ax.get_transform(wcs_msx), colors='orange', levels=[2.5e-5, 5e-5, 1.e-4]) ax.coords[0].set_ticks(size=5, width=1) ax.coords[1].set_ticks(size=5, width=1) ax.set_xlim(0., 720.) ax.set_ylim(0., 720.) # In previous versions, all angle axes defaulted to being displayed in # degrees. We now automatically show RA axes in hour angle units, but # for backward-compatibility with previous reference images we # explicitly use degrees here. ax.coords[0].set_format_unit(u.degree) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_contourf_overlay(self): # Test for overlaying contours on images path = get_pkg_data_filename('galactic_center/gc_msx_e.fits') with fits.open(path) as pf: data = pf[0].data wcs_msx = WCS(self.msx_header) fig = plt.figure(figsize=(6, 6)) ax = fig.add_axes([0.15, 0.15, 0.8, 0.8], projection=WCS(self.twoMASS_k_header), aspect='equal') ax.set_xlim(-0.5, 720.5) ax.set_ylim(-0.5, 720.5) # Overplot contour ax.contourf(data, transform=ax.get_transform(wcs_msx), levels=[2.5e-5, 5e-5, 1.e-4]) ax.coords[0].set_ticks(size=5, width=1) ax.coords[1].set_ticks(size=5, width=1) ax.set_xlim(0., 720.) ax.set_ylim(0., 720.) # In previous versions, all angle axes defaulted to being displayed in # degrees. We now automatically show RA axes in hour angle units, but # for backward-compatibility with previous reference images we # explicitly use degrees here. ax.coords[0].set_format_unit(u.degree) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_overlay_features_image(self): # Test for overlaying grid, changing format of ticks, setting spacing # and number of ticks fig = plt.figure(figsize=(6, 6)) ax = fig.add_axes([0.25, 0.25, 0.65, 0.65], projection=WCS(self.msx_header), aspect='equal') # Change the format of the ticks ax.coords[0].set_major_formatter('dd:mm:ss') ax.coords[1].set_major_formatter('dd:mm:ss.ssss') # Overlay grid on image ax.grid(color='red', alpha=1.0, lw=1, linestyle='dashed') # Set the spacing of ticks on the 'glon' axis to 4 arcsec ax.coords['glon'].set_ticks(spacing=4 * u.arcsec, size=5, width=1) # Set the number of ticks on the 'glat' axis to 9 ax.coords['glat'].set_ticks(number=9, size=5, width=1) # Set labels on axes ax.coords['glon'].set_axislabel('Galactic Longitude', minpad=1.6) ax.coords['glat'].set_axislabel('Galactic Latitude', minpad=-0.75) # Change the frame linewidth and color ax.coords.frame.set_color('red') ax.coords.frame.set_linewidth(2) assert ax.coords.frame.get_color() == 'red' assert ax.coords.frame.get_linewidth() == 2 return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_curvilinear_grid_patches_image(self): # Overlay curvilinear grid and patches on image fig = plt.figure(figsize=(8, 8)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection=WCS(self.rosat_header), aspect='equal') ax.set_xlim(-0.5, 479.5) ax.set_ylim(-0.5, 239.5) ax.grid(color='black', alpha=1.0, lw=1, linestyle='dashed') p = Circle((300, 100), radius=40, ec='yellow', fc='none') ax.add_patch(p) p = Circle((30., 20.), radius=20., ec='orange', fc='none', transform=ax.get_transform('world')) ax.add_patch(p) p = Circle((60., 50.), radius=20., ec='red', fc='none', transform=ax.get_transform('fk5')) ax.add_patch(p) p = Circle((40., 60.), radius=20., ec='green', fc='none', transform=ax.get_transform('galactic')) ax.add_patch(p) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_cube_slice_image(self): # Test for cube slicing fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection=WCS(self.cube_header), slices=(50, 'y', 'x'), aspect='equal') ax.set_xlim(-0.5, 52.5) ax.set_ylim(-0.5, 106.5) ax.coords[2].set_axislabel('Velocity m/s') ax.coords[1].set_ticks(spacing=0.2 * u.deg, width=1) ax.coords[2].set_ticks(spacing=400 * u.m / u.s, width=1) ax.coords[1].set_ticklabel(exclude_overlapping=True) ax.coords[2].set_ticklabel(exclude_overlapping=True) ax.coords[0].grid(grid_type='contours', color='purple', linestyle='solid') ax.coords[1].grid(grid_type='contours', color='orange', linestyle='solid') ax.coords[2].grid(grid_type='contours', color='red', linestyle='solid') return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_cube_slice_image_lonlat(self): # Test for cube slicing. Here we test with longitude and latitude since # there is some longitude-specific code in _update_grid_contour. fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection=WCS(self.cube_header), slices=('x', 'y', 50), aspect='equal') ax.set_xlim(-0.5, 106.5) ax.set_ylim(-0.5, 106.5) ax.coords[0].grid(grid_type='contours', color='blue', linestyle='solid') ax.coords[1].grid(grid_type='contours', color='red', linestyle='solid') # In previous versions, all angle axes defaulted to being displayed in # degrees. We now automatically show RA axes in hour angle units, but # for backward-compatibility with previous reference images we # explicitly use degrees here. ax.coords[0].set_format_unit(u.degree) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_plot_coord(self): fig = plt.figure(figsize=(6, 6)) ax = fig.add_axes([0.15, 0.15, 0.8, 0.8], projection=WCS(self.twoMASS_k_header), aspect='equal') ax.set_xlim(-0.5, 720.5) ax.set_ylim(-0.5, 720.5) c = SkyCoord(266 * u.deg, -29 * u.deg) lines = ax.plot_coord(c, 'o') # Test that plot_coord returns the results from ax.plot assert isinstance(lines, list) assert isinstance(lines[0], matplotlib.lines.Line2D) # In previous versions, all angle axes defaulted to being displayed in # degrees. We now automatically show RA axes in hour angle units, but # for backward-compatibility with previous reference images we # explicitly use degrees here. ax.coords[0].set_format_unit(u.degree) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_plot_line(self): fig = plt.figure(figsize=(6, 6)) ax = fig.add_axes([0.15, 0.15, 0.8, 0.8], projection=WCS(self.twoMASS_k_header), aspect='equal') ax.set_xlim(-0.5, 720.5) ax.set_ylim(-0.5, 720.5) c = SkyCoord([266, 266.8] * u.deg, [-29, -28.9] * u.deg) ax.plot_coord(c) # In previous versions, all angle axes defaulted to being displayed in # degrees. We now automatically show RA axes in hour angle units, but # for backward-compatibility with previous reference images we # explicitly use degrees here. ax.coords[0].set_format_unit(u.degree) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_changed_axis_units(self): # Test to see if changing the units of axis works fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection=WCS(self.cube_header), slices=(50, 'y', 'x'), aspect='equal') ax.set_xlim(-0.5, 52.5) ax.set_ylim(-0.5, 106.5) ax.coords[0].set_ticks_position('') ax.coords[0].set_ticklabel_position('') ax.coords[0].set_axislabel_position('') ax.coords[1].set_ticks_position('lr') ax.coords[1].set_ticklabel_position('l') ax.coords[1].set_axislabel_position('l') ax.coords[2].set_ticks_position('bt') ax.coords[2].set_ticklabel_position('b') ax.coords[2].set_axislabel_position('b') ax.coords[2].set_major_formatter('x.xx') ax.coords[2].set_format_unit(u.km / u.s) ax.coords[2].set_axislabel('Velocity km/s') ax.coords[1].set_ticks(width=1) ax.coords[2].set_ticks(width=1) ax.coords[1].set_ticklabel(exclude_overlapping=True) ax.coords[2].set_ticklabel(exclude_overlapping=True) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_minor_ticks(self): # Test for drawing minor ticks fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection=WCS(self.cube_header), slices=(50, 'y', 'x'), aspect='equal') ax.set_xlim(-0.5, 52.5) ax.set_ylim(-0.5, 106.5) ax.coords[0].set_ticks_position('') ax.coords[0].set_ticklabel_position('') ax.coords[0].set_axislabel_position('') ax.coords[1].set_ticks_position('lr') ax.coords[1].set_ticklabel_position('l') ax.coords[1].set_axislabel_position('l') ax.coords[2].set_ticks_position('bt') ax.coords[2].set_ticklabel_position('b') ax.coords[2].set_axislabel_position('b') ax.coords[2].set_ticklabel(exclude_overlapping=True) ax.coords[1].set_ticklabel(exclude_overlapping=True) ax.coords[2].display_minor_ticks(True) ax.coords[1].display_minor_ticks(True) ax.coords[2].set_minor_frequency(3) ax.coords[1].set_minor_frequency(10) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_ticks_labels(self): fig = plt.figure(figsize=(6, 6)) ax = WCSAxes(fig, [0.1, 0.1, 0.7, 0.7], wcs=None) fig.add_axes(ax) ax.set_xlim(-0.5, 2) ax.set_ylim(-0.5, 2) ax.coords[0].set_ticks(size=10, color='blue', alpha=0.2, width=1) ax.coords[1].set_ticks(size=20, color='red', alpha=0.9, width=1) ax.coords[0].set_ticks_position('all') ax.coords[1].set_ticks_position('all') ax.coords[0].set_axislabel('X-axis', size=20) ax.coords[1].set_axislabel('Y-axis', color='green', size=25, weight='regular', style='normal', family='cmtt10') ax.coords[0].set_axislabel_position('t') ax.coords[1].set_axislabel_position('r') ax.coords[0].set_ticklabel(color='purple', size=15, alpha=1, weight='light', style='normal', family='cmss10') ax.coords[1].set_ticklabel(color='black', size=18, alpha=0.9, weight='bold', family='cmr10') ax.coords[0].set_ticklabel_position('all') ax.coords[1].set_ticklabel_position('r') return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_rcparams(self): # Test custom rcParams with rc_context({ 'axes.labelcolor': 'purple', 'axes.labelsize': 14, 'axes.labelweight': 'bold', 'axes.linewidth': 3, 'axes.facecolor': '0.5', 'axes.edgecolor': 'green', 'xtick.color': 'red', 'xtick.labelsize': 8, 'xtick.direction': 'in', 'xtick.minor.visible': True, 'xtick.minor.size': 5, 'xtick.major.size': 20, 'xtick.major.width': 3, 'xtick.major.pad': 10, 'grid.color': 'blue', 'grid.linestyle': ':', 'grid.linewidth': 1, 'grid.alpha': 0.5}): fig = plt.figure(figsize=(6, 6)) ax = WCSAxes(fig, [0.15, 0.1, 0.7, 0.7], wcs=None) fig.add_axes(ax) ax.set_xlim(-0.5, 2) ax.set_ylim(-0.5, 2) ax.grid() ax.set_xlabel('X label') ax.set_ylabel('Y label') ax.coords[0].set_ticklabel(exclude_overlapping=True) ax.coords[1].set_ticklabel(exclude_overlapping=True) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_tick_angles(self): # Test that tick marks point in the correct direction, even when the # axes limits extend only over a few FITS pixels. Addresses #45, #46. w = WCS() w.wcs.ctype = ['RA---TAN', 'DEC--TAN'] w.wcs.crval = [90, 70] w.wcs.cdelt = [16, 16] w.wcs.crpix = [1, 1] w.wcs.radesys = 'ICRS' w.wcs.equinox = 2000.0 fig = plt.figure(figsize=(3, 3)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection=w) ax.set_xlim(1, -1) ax.set_ylim(-1, 1) ax.grid(color='gray', alpha=0.5, linestyle='solid') ax.coords['ra'].set_ticks(color='red', size=20) ax.coords['dec'].set_ticks(color='red', size=20) # In previous versions, all angle axes defaulted to being displayed in # degrees. We now automatically show RA axes in hour angle units, but # for backward-compatibility with previous reference images we # explicitly use degrees here. ax.coords[0].set_format_unit(u.degree) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_tick_angles_non_square_axes(self): # Test that tick marks point in the correct direction, even when the # axes limits extend only over a few FITS pixels, and the axes are # non-square. w = WCS() w.wcs.ctype = ['RA---TAN', 'DEC--TAN'] w.wcs.crval = [90, 70] w.wcs.cdelt = [16, 16] w.wcs.crpix = [1, 1] w.wcs.radesys = 'ICRS' w.wcs.equinox = 2000.0 fig = plt.figure(figsize=(6, 3)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection=w) ax.set_xlim(1, -1) ax.set_ylim(-1, 1) ax.grid(color='gray', alpha=0.5, linestyle='solid') ax.coords['ra'].set_ticks(color='red', size=20) ax.coords['dec'].set_ticks(color='red', size=20) # In previous versions, all angle axes defaulted to being displayed in # degrees. We now automatically show RA axes in hour angle units, but # for backward-compatibility with previous reference images we # explicitly use degrees here. ax.coords[0].set_format_unit(u.degree) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_set_coord_type(self): # Test for setting coord_type fig = plt.figure(figsize=(3, 3)) ax = fig.add_axes([0.2, 0.2, 0.6, 0.6], projection=WCS(self.msx_header), aspect='equal') ax.set_xlim(-0.5, 148.5) ax.set_ylim(-0.5, 148.5) ax.coords[0].set_coord_type('scalar') ax.coords[1].set_coord_type('scalar') ax.coords[0].set_major_formatter('x.xxx') ax.coords[1].set_major_formatter('x.xxx') ax.coords[0].set_ticklabel(exclude_overlapping=True) ax.coords[1].set_ticklabel(exclude_overlapping=True) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_ticks_regression(self): # Regression test for a bug that caused ticks aligned exactly with a # sampled frame point to not appear. This also checks that tick labels # don't get added more than once, and that no error occurs when e.g. # the top part of the frame is all at the same coordinate as one of the # potential ticks (which causes the tick angle calculation to return # NaN). wcs = WCS(self.slice_header) fig = plt.figure(figsize=(3, 3)) ax = fig.add_axes([0.25, 0.25, 0.5, 0.5], projection=wcs, aspect='auto') limits = wcs.wcs_world2pix([0, 0], [35e3, 80e3], 0)[1] ax.set_ylim(*limits) ax.coords[0].set_ticks(spacing=0.002 * u.deg) ax.coords[1].set_ticks(spacing=5 * u.km / u.s) ax.coords[0].set_ticklabel(alpha=0.5) # to see multiple labels ax.coords[1].set_ticklabel(alpha=0.5) ax.coords[0].set_ticklabel_position('all') ax.coords[1].set_ticklabel_position('all') return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, savefig_kwargs={'bbox_inches': 'tight'}, tolerance=0, style={}) def test_axislabels_regression(self): # Regression test for a bug that meant that if tick labels were made # invisible with ``set_visible(False)``, they were still added to the # list of bounding boxes for tick labels, but with default values of 0 # to 1, which caused issues. wcs = WCS(self.msx_header) fig = plt.figure(figsize=(3, 3)) ax = fig.add_axes([0.25, 0.25, 0.5, 0.5], projection=wcs, aspect='auto') ax.coords[0].set_axislabel("Label 1") ax.coords[1].set_axislabel("Label 2") ax.coords[1].set_axislabel_visibility_rule('always') ax.coords[1].ticklabels.set_visible(False) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, savefig_kwargs={'bbox_inches': 'tight'}, tolerance=0, style={}) def test_noncelestial_angular(self, tmpdir): # Regression test for a bug that meant that when passing a WCS that had # angular axes and using set_coord_type to set the coordinates to # longitude/latitude, but where the WCS wasn't recognized as celestial, # the WCS units are not converted to deg, so we can't assume that # transform will always return degrees. wcs = WCS(naxis=2) wcs.wcs.ctype = ['solar-x', 'solar-y'] wcs.wcs.cunit = ['arcsec', 'arcsec'] fig = plt.figure(figsize=(3, 3)) ax = fig.add_subplot(1, 1, 1, projection=wcs) ax.imshow(np.zeros([1024, 1024]), origin='lower') ax.coords[0].set_coord_type('longitude', coord_wrap=180) ax.coords[1].set_coord_type('latitude') ax.coords[0].set_major_formatter('s.s') ax.coords[1].set_major_formatter('s.s') ax.coords[0].set_format_unit(u.arcsec, show_decimal_unit=False) ax.coords[1].set_format_unit(u.arcsec, show_decimal_unit=False) ax.grid(color='white', ls='solid') # Force drawing (needed for format_coord) fig.savefig(tmpdir.join('nothing').strpath) assert ax.format_coord(512, 512) == '513.0 513.0 (world)' return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, savefig_kwargs={'bbox_inches': 'tight'}, tolerance=0, style={}) def test_patches_distortion(self, tmpdir): # Check how patches get distorted (and make sure that scatter markers # and SphericalCircle don't) wcs = WCS(self.msx_header) fig = plt.figure(figsize=(3, 3)) ax = fig.add_axes([0.25, 0.25, 0.5, 0.5], projection=wcs, aspect='equal') # Pixel coordinates r = Rectangle((30., 50.), 60., 50., edgecolor='green', facecolor='none') ax.add_patch(r) # FK5 coordinates r = Rectangle((266.4, -28.9), 0.3, 0.3, edgecolor='cyan', facecolor='none', transform=ax.get_transform('fk5')) ax.add_patch(r) # FK5 coordinates c = Circle((266.4, -29.1), 0.15, edgecolor='magenta', facecolor='none', transform=ax.get_transform('fk5')) ax.add_patch(c) # Pixel coordinates ax.scatter([40, 100, 130], [30, 130, 60], s=100, edgecolor='red', facecolor=(1, 0, 0, 0.5)) # World coordinates (should not be distorted) ax.scatter(266.78238, -28.769255, transform=ax.get_transform('fk5'), s=300, edgecolor='red', facecolor='none') # World coordinates (should not be distorted) r1 = SphericalCircle((266.4 * u.deg, -29.1 * u.deg), 0.15 * u.degree, edgecolor='purple', facecolor='none', transform=ax.get_transform('fk5')) ax.add_patch(r1) r2 = SphericalCircle(SkyCoord(266.4 * u.deg, -29.1 * u.deg), 0.15 * u.degree, edgecolor='purple', facecolor='none', transform=ax.get_transform('fk5')) with pytest.warns(AstropyUserWarning, match="Received `center` of representation type " "<class 'astropy.coordinates.representation.CartesianRepresentation'> " "will be converted to SphericalRepresentation"): r3 = SphericalCircle(SkyCoord(x=-0.05486461, y=-0.87204803, z=-0.48633538, representation_type='cartesian'), 0.15 * u.degree, edgecolor='purple', facecolor='none', transform=ax.get_transform('fk5')) ax.coords[0].set_ticklabel_visible(False) ax.coords[1].set_ticklabel_visible(False) # Test to verify that SphericalCircle works irrespective of whether # the input(center) is a tuple or a SkyCoord object. assert (r1.get_xy() == r2.get_xy()).all() assert np.allclose(r1.get_xy(), r3.get_xy()) assert np.allclose(r2.get_xy()[0], [266.4, -29.25]) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_quadrangle(self, tmpdir): # Test that Quadrangle can have curved edges while Rectangle does not wcs = WCS(self.msx_header) fig = plt.figure(figsize=(3, 3)) ax = fig.add_axes([0.25, 0.25, 0.5, 0.5], projection=wcs, aspect='equal') ax.set_xlim(0, 10000) ax.set_ylim(-10000, 0) # Add a quadrangle patch (100 degrees by 20 degrees) q = Quadrangle((255, -70)*u.deg, 100*u.deg, 20*u.deg, label='Quadrangle', edgecolor='blue', facecolor='none', transform=ax.get_transform('icrs')) ax.add_patch(q) # Add a rectangle patch (100 degrees by 20 degrees) r = Rectangle((255, -70), 100, 20, label='Rectangle', edgecolor='red', facecolor='none', linestyle='--', transform=ax.get_transform('icrs')) ax.add_patch(r) ax.coords[0].set_ticklabel_visible(False) ax.coords[1].set_ticklabel_visible(False) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_elliptical_frame(self): # Regression test for a bug (astropy/astropy#6063) that caused labels to # be incorrectly simplified. wcs = WCS(self.msx_header) fig = plt.figure(figsize=(5, 3)) fig.add_axes([0.2, 0.2, 0.6, 0.6], projection=wcs, frame_class=EllipticalFrame) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_hms_labels(self): # This tests the apparance of the hms superscripts in tick labels fig = plt.figure(figsize=(3, 3)) ax = fig.add_axes([0.3, 0.2, 0.65, 0.6], projection=WCS(self.twoMASS_k_header), aspect='equal') ax.set_xlim(-0.5, 0.5) ax.set_ylim(-0.5, 0.5) ax.coords[0].set_ticks(spacing=0.2 * 15 * u.arcsec) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={'text.usetex': True}) def test_latex_labels(self): fig = plt.figure(figsize=(3, 3)) ax = fig.add_axes([0.3, 0.2, 0.65, 0.6], projection=WCS(self.twoMASS_k_header), aspect='equal') ax.set_xlim(-0.5, 0.5) ax.set_ylim(-0.5, 0.5) ax.coords[0].set_ticks(spacing=0.2 * 15 * u.arcsec) return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_tick_params(self): # This is a test to make sure that tick_params works correctly. We try # and test as much as possible with a single reference image. wcs = WCS() wcs.wcs.ctype = ['lon', 'lat'] fig = plt.figure(figsize=(6, 6)) # The first subplot tests: # - that plt.tick_params works # - that by default both axes are changed # - changing the tick direction and appearance, the label appearance and padding ax = fig.add_subplot(2, 2, 1, projection=wcs) plt.tick_params(direction='in', length=20, width=5, pad=6, labelsize=6, color='red', labelcolor='blue') ax.coords[0].set_auto_axislabel(False) ax.coords[1].set_auto_axislabel(False) # The second subplot tests: # - that specifying grid parameters doesn't actually cause the grid to # be shown (as expected) # - that axis= can be given integer coordinates or their string name # - that the tick positioning works (bottom/left/top/right) # Make sure that we can pass things that can index coords ax = fig.add_subplot(2, 2, 2, projection=wcs) plt.tick_params(axis=0, direction='in', length=20, width=5, pad=4, labelsize=6, color='red', labelcolor='blue', bottom=True, grid_color='purple') plt.tick_params(axis='lat', direction='out', labelsize=8, color='blue', labelcolor='purple', left=True, right=True, grid_color='red') ax.coords[0].set_auto_axislabel(False) ax.coords[1].set_auto_axislabel(False) # The third subplot tests: # - that ax.tick_params works # - that the grid has the correct settings once shown explicitly # - that we can use axis='x' and axis='y' ax = fig.add_subplot(2, 2, 3, projection=wcs) ax.tick_params(axis='x', direction='in', length=20, width=5, pad=20, labelsize=6, color='red', labelcolor='blue', bottom=True, grid_color='purple') ax.tick_params(axis='y', direction='out', labelsize=8, color='blue', labelcolor='purple', left=True, right=True, grid_color='red') plt.grid() ax.coords[0].set_auto_axislabel(False) ax.coords[1].set_auto_axislabel(False) # The final subplot tests: # - that we can use tick_params on a specific coordinate # - that the label positioning can be customized # - that the colors argument works # - that which='minor' works ax = fig.add_subplot(2, 2, 4, projection=wcs) ax.coords[0].tick_params(length=4, pad=2, colors='orange', labelbottom=True, labeltop=True, labelsize=10) ax.coords[1].display_minor_ticks(True) ax.coords[1].tick_params(which='minor', length=6) ax.coords[0].set_auto_axislabel(False) ax.coords[1].set_auto_axislabel(False) return fig @pytest.fixture def wave_wcs_1d(): wcs = WCS(naxis=1) wcs.wcs.ctype = ['WAVE'] wcs.wcs.cunit = ['m'] wcs.wcs.crpix = [1] wcs.wcs.cdelt = [5] wcs.wcs.crval = [45] wcs.wcs.set() return wcs @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_1d_plot_1d_wcs(wave_wcs_1d): fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=wave_wcs_1d) lines, = ax.plot([10, 12, 14, 12, 10]) ax.set_xlabel("this is the x-axis") ax.set_ylabel("this is the y-axis") return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_1d_plot_1d_wcs_format_unit(wave_wcs_1d): """ This test ensures that the format unit is updated and displayed for both the axis ticks and default axis labels. """ fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=wave_wcs_1d) lines, = ax.plot([10, 12, 14, 12, 10]) ax.coords[0].set_format_unit("nm") return fig @pytest.fixture def spatial_wcs_2d(): wcs = WCS(naxis=2) wcs.wcs.ctype = ['GLON-TAN', 'GLAT-TAN'] wcs.wcs.crpix = [3.0] * 2 wcs.wcs.cdelt = [15] * 2 wcs.wcs.crval = [50.0] * 2 wcs.wcs.set() return wcs @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_1d_plot_2d_wcs_correlated(spatial_wcs_2d): fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=spatial_wcs_2d, slices=('x', 0)) lines, = ax.plot([10, 12, 14, 12, 10], '-o', color="orange") ax.coords['glon'].set_ticks(color="red") ax.coords['glon'].set_ticklabel(color="red") ax.coords['glon'].grid(color="red") ax.coords['glat'].set_ticks(color="blue") ax.coords['glat'].set_ticklabel(color="blue") ax.coords['glat'].grid(color="blue") return fig @pytest.fixture def spatial_wcs_2d_small_angle(): """ This WCS has an almost linear correlation between the pixel and world axes close to the reference pixel. """ wcs = WCS(naxis=2) wcs.wcs.ctype = ['HPLN-TAN', 'HPLT-TAN'] wcs.wcs.crpix = [3.0] * 2 wcs.wcs.cdelt = [10/3600, 5/3600] wcs.wcs.crval = [0] * 2 wcs.wcs.set() return wcs @pytest.mark.parametrize("slices, bottom_axis", [ # Remember SLLWCS takes slices in array order (np.s_[0, :], 'custom:pos.helioprojective.lon'), (np.s_[:, 0], 'custom:pos.helioprojective.lat')]) @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_1d_plot_1d_sliced_low_level_wcs(spatial_wcs_2d_small_angle, slices, bottom_axis): """ Test that a SLLWCS through a coupled 2D WCS plots as line OK. """ fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=spatial_wcs_2d_small_angle[slices]) lines, = ax.plot([10, 12, 14, 12, 10], '-o', color="orange") # Draw to trigger rendering the ticks. plt.draw() assert ax.coords[bottom_axis].ticks.get_visible_axes() == ['b'] return fig @pytest.mark.parametrize("slices, bottom_axis", [ (('x', 0), 'hpln'), ((0, 'x'), 'hplt')]) @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_1d_plot_put_varying_axis_on_bottom_lon(spatial_wcs_2d_small_angle, slices, bottom_axis): """ When we plot a 1D slice through spatial axes, we want to put the axis which actually changes on the bottom. For example an aligned wcs, pixel grid where you plot a lon slice through a lat axis, you would end up with no ticks on the bottom as the lon doesn't change, and a set of lat ticks on the top because it does but it's the correlated axis not the actual one you are plotting against. """ fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=spatial_wcs_2d_small_angle, slices=slices) lines, = ax.plot([10, 12, 14, 12, 10], '-o', color="orange") # Draw to trigger rendering the ticks. plt.draw() assert ax.coords[bottom_axis].ticks.get_visible_axes() == ['b'] return fig @pytest.mark.remote_data(source='astropy') @pytest.mark.mpl_image_compare(baseline_dir=IMAGE_REFERENCE_DIR, tolerance=0, style={}) def test_allsky_labels_wrap(): # Regression test for a bug that caused some tick labels to not be shown # when looking at all-sky maps in the case where coord_wrap < 360 fig = plt.figure(figsize=(4, 4)) icen = 0 for ctype in [('GLON-CAR', 'GLAT-CAR'), ('HGLN-CAR', 'HGLT-CAR')]: for cen in [0, 90, 180, 270]: icen += 1 wcs = WCS(naxis=2) wcs.wcs.ctype = ctype wcs.wcs.crval = cen, 0 wcs.wcs.crpix = 360.5, 180.5 wcs.wcs.cdelt = -0.5, 0.5 ax = fig.add_subplot(8, 1, icen, projection=wcs) ax.set_xlim(-0.5, 719.5) ax.coords[0].set_ticks(spacing=50 * u.deg) ax.coords[0].set_ticks_position('b') ax.coords[0].set_auto_axislabel(False) ax.coords[1].set_auto_axislabel(False) ax.coords[1].set_ticklabel_visible(False) ax.coords[1].set_ticks_visible(False) fig.subplots_adjust(hspace=2, left=0.05, right=0.95, bottom=0.1, top=0.95) return fig
02dc324bc20afb2233686f80c95f9a292ac7d53672ce0871986f6b3ec302fdca
# Licensed under a 3-clause BSD style license - see LICENSE.rst # This module implements the Slicing mixin to the NDData class. from astropy import log from astropy.wcs.wcsapi import (BaseLowLevelWCS, BaseHighLevelWCS, SlicedLowLevelWCS, HighLevelWCSWrapper) __all__ = ['NDSlicingMixin'] class NDSlicingMixin: """Mixin to provide slicing on objects using the `NDData` interface. The ``data``, ``mask``, ``uncertainty`` and ``wcs`` will be sliced, if set and sliceable. The ``unit`` and ``meta`` will be untouched. The return will be a reference and not a copy, if possible. Examples -------- Using this Mixin with `~astropy.nddata.NDData`: >>> from astropy.nddata import NDData, NDSlicingMixin >>> class NDDataSliceable(NDSlicingMixin, NDData): ... pass Slicing an instance containing data:: >>> nd = NDDataSliceable([1,2,3,4,5]) >>> nd[1:3] NDDataSliceable([2, 3]) Also the other attributes are sliced for example the ``mask``:: >>> import numpy as np >>> mask = np.array([True, False, True, True, False]) >>> nd2 = NDDataSliceable(nd, mask=mask) >>> nd2slc = nd2[1:3] >>> nd2slc[nd2slc.mask] NDDataSliceable([3]) Be aware that changing values of the sliced instance will change the values of the original:: >>> nd3 = nd2[1:3] >>> nd3.data[0] = 100 >>> nd2 NDDataSliceable([ 1, 100, 3, 4, 5]) See also -------- NDDataRef NDDataArray """ def __getitem__(self, item): # Abort slicing if the data is a single scalar. if self.data.shape == (): raise TypeError('scalars cannot be sliced.') # Let the other methods handle slicing. kwargs = self._slice(item) return self.__class__(**kwargs) def _slice(self, item): """Collects the sliced attributes and passes them back as `dict`. It passes uncertainty, mask and wcs to their appropriate ``_slice_*`` method, while ``meta`` and ``unit`` are simply taken from the original. The data is assumed to be sliceable and is sliced directly. When possible the return should *not* be a copy of the data but a reference. Parameters ---------- item : slice The slice passed to ``__getitem__``. Returns ------- dict : Containing all the attributes after slicing - ready to use them to create ``self.__class__.__init__(**kwargs)`` in ``__getitem__``. """ kwargs = {} kwargs['data'] = self.data[item] # Try to slice some attributes kwargs['uncertainty'] = self._slice_uncertainty(item) kwargs['mask'] = self._slice_mask(item) kwargs['wcs'] = self._slice_wcs(item) # Attributes which are copied and not intended to be sliced kwargs['unit'] = self.unit kwargs['meta'] = self.meta return kwargs def _slice_uncertainty(self, item): if self.uncertainty is None: return None try: return self.uncertainty[item] except TypeError: # Catching TypeError in case the object has no __getitem__ method. # But let IndexError raise. log.info("uncertainty cannot be sliced.") return self.uncertainty def _slice_mask(self, item): if self.mask is None: return None try: return self.mask[item] except TypeError: log.info("mask cannot be sliced.") return self.mask def _slice_wcs(self, item): if self.wcs is None: return None try: llwcs = SlicedLowLevelWCS(self.wcs.low_level_wcs, item) return HighLevelWCSWrapper(llwcs) except Exception as err: self._handle_wcs_slicing_error(err, item) # Implement this in a method to allow subclasses to customise the error. def _handle_wcs_slicing_error(self, err, item): raise ValueError(f"Slicing the WCS object with the slice '{item}' " "failed, if you want to slice the NDData object without the WCS, you " "can remove by setting `NDData.wcs = None` and then retry.") from err
b8178dee0a65bdb7c9734b1878348f3ba48301deb13aefbac6b7262059ab2f37
# Licensed under a 3-clause BSD style license - see LICENSE.rst # This module implements the Arithmetic mixin to the NDData class. from copy import deepcopy import numpy as np from astropy.nddata.nduncertainty import NDUncertainty from astropy.units import dimensionless_unscaled from astropy.utils import format_doc, sharedmethod __all__ = ['NDArithmeticMixin'] # Global so it doesn't pollute the class dict unnecessarily: # Docstring templates for add, subtract, multiply, divide methods. _arit_doc = """ Performs {name} by evaluating ``self`` {op} ``operand``. Parameters ---------- operand, operand2 : `NDData`-like instance If ``operand2`` is ``None`` or not given it will perform the operation ``self`` {op} ``operand``. If ``operand2`` is given it will perform ``operand`` {op} ``operand2``. If the method was called on a class rather than on the instance ``operand2`` must be given. propagate_uncertainties : `bool` or ``None``, optional If ``None`` the result will have no uncertainty. If ``False`` the result will have a copied version of the first operand that has an uncertainty. If ``True`` the result will have a correctly propagated uncertainty from the uncertainties of the operands but this assumes that the uncertainties are `NDUncertainty`-like. Default is ``True``. .. versionchanged:: 1.2 This parameter must be given as keyword-parameter. Using it as positional parameter is deprecated. ``None`` was added as valid parameter value. handle_mask : callable, ``'first_found'`` or ``None``, optional If ``None`` the result will have no mask. If ``'first_found'`` the result will have a copied version of the first operand that has a mask). If it is a callable then the specified callable must create the results ``mask`` and if necessary provide a copy. Default is `numpy.logical_or`. .. versionadded:: 1.2 handle_meta : callable, ``'first_found'`` or ``None``, optional If ``None`` the result will have no meta. If ``'first_found'`` the result will have a copied version of the first operand that has a (not empty) meta. If it is a callable then the specified callable must create the results ``meta`` and if necessary provide a copy. Default is ``None``. .. versionadded:: 1.2 compare_wcs : callable, ``'first_found'`` or ``None``, optional If ``None`` the result will have no wcs and no comparison between the wcs of the operands is made. If ``'first_found'`` the result will have a copied version of the first operand that has a wcs. If it is a callable then the specified callable must compare the ``wcs``. The resulting ``wcs`` will be like if ``False`` was given otherwise it raises a ``ValueError`` if the comparison was not successful. Default is ``'first_found'``. .. versionadded:: 1.2 uncertainty_correlation : number or `~numpy.ndarray`, optional The correlation between the two operands is used for correct error propagation for correlated data as given in: https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas Default is 0. .. versionadded:: 1.2 kwargs : Any other parameter that should be passed to the callables used. Returns ------- result : `~astropy.nddata.NDData`-like The resulting dataset Notes ----- If a ``callable`` is used for ``mask``, ``wcs`` or ``meta`` the callable must accept the corresponding attributes as first two parameters. If the callable also needs additional parameters these can be defined as ``kwargs`` and must start with ``"wcs_"`` (for wcs callable) or ``"meta_"`` (for meta callable). This startstring is removed before the callable is called. ``"first_found"`` can also be abbreviated with ``"ff"``. """ class NDArithmeticMixin: """ Mixin class to add arithmetic to an NDData object. When subclassing, be sure to list the superclasses in the correct order so that the subclass sees NDData as the main superclass. See `~astropy.nddata.NDDataArray` for an example. Notes ----- This class only aims at covering the most common cases so there are certain restrictions on the saved attributes:: - ``uncertainty`` : has to be something that has a `NDUncertainty`-like interface for uncertainty propagation - ``mask`` : has to be something that can be used by a bitwise ``or`` operation. - ``wcs`` : has to implement a way of comparing with ``=`` to allow the operation. But there is a workaround that allows to disable handling a specific attribute and to simply set the results attribute to ``None`` or to copy the existing attribute (and neglecting the other). For example for uncertainties not representing an `NDUncertainty`-like interface you can alter the ``propagate_uncertainties`` parameter in :meth:`NDArithmeticMixin.add`. ``None`` means that the result will have no uncertainty, ``False`` means it takes the uncertainty of the first operand (if this does not exist from the second operand) as the result's uncertainty. This behavior is also explained in the docstring for the different arithmetic operations. Decomposing the units is not attempted, mainly due to the internal mechanics of `~astropy.units.Quantity`, so the resulting data might have units like ``km/m`` if you divided for example 100km by 5m. So this Mixin has adopted this behavior. Examples -------- Using this Mixin with `~astropy.nddata.NDData`: >>> from astropy.nddata import NDData, NDArithmeticMixin >>> class NDDataWithMath(NDArithmeticMixin, NDData): ... pass Using it with one operand on an instance:: >>> ndd = NDDataWithMath(100) >>> ndd.add(20) NDDataWithMath(120) Using it with two operand on an instance:: >>> ndd = NDDataWithMath(-4) >>> ndd.divide(1, ndd) NDDataWithMath(-0.25) Using it as classmethod requires two operands:: >>> NDDataWithMath.subtract(5, 4) NDDataWithMath(1) """ def _arithmetic(self, operation, operand, propagate_uncertainties=True, handle_mask=np.logical_or, handle_meta=None, uncertainty_correlation=0, compare_wcs='first_found', **kwds): """ Base method which calculates the result of the arithmetic operation. This method determines the result of the arithmetic operation on the ``data`` including their units and then forwards to other methods to calculate the other properties for the result (like uncertainty). Parameters ---------- operation : callable The operation that is performed on the `NDData`. Supported are `numpy.add`, `numpy.subtract`, `numpy.multiply` and `numpy.true_divide`. operand : same type (class) as self see :meth:`NDArithmeticMixin.add` propagate_uncertainties : `bool` or ``None``, optional see :meth:`NDArithmeticMixin.add` handle_mask : callable, ``'first_found'`` or ``None``, optional see :meth:`NDArithmeticMixin.add` handle_meta : callable, ``'first_found'`` or ``None``, optional see :meth:`NDArithmeticMixin.add` compare_wcs : callable, ``'first_found'`` or ``None``, optional see :meth:`NDArithmeticMixin.add` uncertainty_correlation : ``Number`` or `~numpy.ndarray`, optional see :meth:`NDArithmeticMixin.add` kwargs : Any other parameter that should be passed to the different :meth:`NDArithmeticMixin._arithmetic_mask` (or wcs, ...) methods. Returns ------- result : ndarray or `~astropy.units.Quantity` The resulting data as array (in case both operands were without unit) or as quantity if at least one had a unit. kwargs : `dict` The kwargs should contain all the other attributes (besides data and unit) needed to create a new instance for the result. Creating the new instance is up to the calling method, for example :meth:`NDArithmeticMixin.add`. """ # Find the appropriate keywords for the appropriate method (not sure # if data and uncertainty are ever used ...) kwds2 = {'mask': {}, 'meta': {}, 'wcs': {}, 'data': {}, 'uncertainty': {}} for i in kwds: splitted = i.split('_', 1) try: kwds2[splitted[0]][splitted[1]] = kwds[i] except KeyError: raise KeyError(f'Unknown prefix {splitted[0]} for parameter {i}') kwargs = {} # First check that the WCS allows the arithmetic operation if compare_wcs is None: kwargs['wcs'] = None elif compare_wcs in ['ff', 'first_found']: if self.wcs is None: kwargs['wcs'] = deepcopy(operand.wcs) else: kwargs['wcs'] = deepcopy(self.wcs) else: kwargs['wcs'] = self._arithmetic_wcs(operation, operand, compare_wcs, **kwds2['wcs']) # Then calculate the resulting data (which can but not needs to be a # quantity) result = self._arithmetic_data(operation, operand, **kwds2['data']) # Determine the other properties if propagate_uncertainties is None: kwargs['uncertainty'] = None elif not propagate_uncertainties: if self.uncertainty is None: kwargs['uncertainty'] = deepcopy(operand.uncertainty) else: kwargs['uncertainty'] = deepcopy(self.uncertainty) else: kwargs['uncertainty'] = self._arithmetic_uncertainty( operation, operand, result, uncertainty_correlation, **kwds2['uncertainty']) if handle_mask is None: kwargs['mask'] = None elif handle_mask in ['ff', 'first_found']: if self.mask is None: kwargs['mask'] = deepcopy(operand.mask) else: kwargs['mask'] = deepcopy(self.mask) else: kwargs['mask'] = self._arithmetic_mask(operation, operand, handle_mask, **kwds2['mask']) if handle_meta is None: kwargs['meta'] = None elif handle_meta in ['ff', 'first_found']: if not self.meta: kwargs['meta'] = deepcopy(operand.meta) else: kwargs['meta'] = deepcopy(self.meta) else: kwargs['meta'] = self._arithmetic_meta( operation, operand, handle_meta, **kwds2['meta']) # Wrap the individual results into a new instance of the same class. return result, kwargs def _arithmetic_data(self, operation, operand, **kwds): """ Calculate the resulting data Parameters ---------- operation : callable see `NDArithmeticMixin._arithmetic` parameter description. operand : `NDData`-like instance The second operand wrapped in an instance of the same class as self. kwds : Additional parameters. Returns ------- result_data : ndarray or `~astropy.units.Quantity` If both operands had no unit the resulting data is a simple numpy array, but if any of the operands had a unit the return is a Quantity. """ # Do the calculation with or without units if self.unit is None and operand.unit is None: result = operation(self.data, operand.data) elif self.unit is None: result = operation(self.data << dimensionless_unscaled, operand.data << operand.unit) elif operand.unit is None: result = operation(self.data << self.unit, operand.data << dimensionless_unscaled) else: result = operation(self.data << self.unit, operand.data << operand.unit) return result def _arithmetic_uncertainty(self, operation, operand, result, correlation, **kwds): """ Calculate the resulting uncertainty. Parameters ---------- operation : callable see :meth:`NDArithmeticMixin._arithmetic` parameter description. operand : `NDData`-like instance The second operand wrapped in an instance of the same class as self. result : `~astropy.units.Quantity` or `~numpy.ndarray` The result of :meth:`NDArithmeticMixin._arithmetic_data`. correlation : number or `~numpy.ndarray` see :meth:`NDArithmeticMixin.add` parameter description. kwds : Additional parameters. Returns ------- result_uncertainty : `NDUncertainty` subclass instance or None The resulting uncertainty already saved in the same `NDUncertainty` subclass that ``self`` had (or ``operand`` if self had no uncertainty). ``None`` only if both had no uncertainty. """ # Make sure these uncertainties are NDUncertainties so this kind of # propagation is possible. if (self.uncertainty is not None and not isinstance(self.uncertainty, NDUncertainty)): raise TypeError("Uncertainty propagation is only defined for " "subclasses of NDUncertainty.") if (operand.uncertainty is not None and not isinstance(operand.uncertainty, NDUncertainty)): raise TypeError("Uncertainty propagation is only defined for " "subclasses of NDUncertainty.") # Now do the uncertainty propagation # TODO: There is no enforced requirement that actually forbids the # uncertainty to have negative entries but with correlation the # sign of the uncertainty DOES matter. if self.uncertainty is None and operand.uncertainty is None: # Neither has uncertainties so the result should have none. return None elif self.uncertainty is None: # Create a temporary uncertainty to allow uncertainty propagation # to yield the correct results. (issue #4152) self.uncertainty = operand.uncertainty.__class__(None) result_uncert = self.uncertainty.propagate(operation, operand, result, correlation) # Delete the temporary uncertainty again. self.uncertainty = None return result_uncert elif operand.uncertainty is None: # As with self.uncertainty is None but the other way around. operand.uncertainty = self.uncertainty.__class__(None) result_uncert = self.uncertainty.propagate(operation, operand, result, correlation) operand.uncertainty = None return result_uncert else: # Both have uncertainties so just propagate. return self.uncertainty.propagate(operation, operand, result, correlation) def _arithmetic_mask(self, operation, operand, handle_mask, **kwds): """ Calculate the resulting mask This is implemented as the piecewise ``or`` operation if both have a mask. Parameters ---------- operation : callable see :meth:`NDArithmeticMixin._arithmetic` parameter description. By default, the ``operation`` will be ignored. operand : `NDData`-like instance The second operand wrapped in an instance of the same class as self. handle_mask : callable see :meth:`NDArithmeticMixin.add` kwds : Additional parameters given to ``handle_mask``. Returns ------- result_mask : any type If only one mask was present this mask is returned. If neither had a mask ``None`` is returned. Otherwise ``handle_mask`` must create (and copy) the returned mask. """ # If only one mask is present we need not bother about any type checks if self.mask is None and operand.mask is None: return None elif self.mask is None: # Make a copy so there is no reference in the result. return deepcopy(operand.mask) elif operand.mask is None: return deepcopy(self.mask) else: # Now lets calculate the resulting mask (operation enforces copy) return handle_mask(self.mask, operand.mask, **kwds) def _arithmetic_wcs(self, operation, operand, compare_wcs, **kwds): """ Calculate the resulting wcs. There is actually no calculation involved but it is a good place to compare wcs information of both operands. This is currently not working properly with `~astropy.wcs.WCS` (which is the suggested class for storing as wcs property) but it will not break it neither. Parameters ---------- operation : callable see :meth:`NDArithmeticMixin._arithmetic` parameter description. By default, the ``operation`` will be ignored. operand : `NDData` instance or subclass The second operand wrapped in an instance of the same class as self. compare_wcs : callable see :meth:`NDArithmeticMixin.add` parameter description. kwds : Additional parameters given to ``compare_wcs``. Raises ------ ValueError If ``compare_wcs`` returns ``False``. Returns ------- result_wcs : any type The ``wcs`` of the first operand is returned. """ # ok, not really arithmetics but we need to check which wcs makes sense # for the result and this is an ideal place to compare the two WCS, # too. # I'll assume that the comparison returned None or False in case they # are not equal. if not compare_wcs(self.wcs, operand.wcs, **kwds): raise ValueError("WCS are not equal.") return deepcopy(self.wcs) def _arithmetic_meta(self, operation, operand, handle_meta, **kwds): """ Calculate the resulting meta. Parameters ---------- operation : callable see :meth:`NDArithmeticMixin._arithmetic` parameter description. By default, the ``operation`` will be ignored. operand : `NDData`-like instance The second operand wrapped in an instance of the same class as self. handle_meta : callable see :meth:`NDArithmeticMixin.add` kwds : Additional parameters given to ``handle_meta``. Returns ------- result_meta : any type The result of ``handle_meta``. """ # Just return what handle_meta does with both of the metas. return handle_meta(self.meta, operand.meta, **kwds) @sharedmethod @format_doc(_arit_doc, name='addition', op='+') def add(self, operand, operand2=None, **kwargs): return self._prepare_then_do_arithmetic(np.add, operand, operand2, **kwargs) @sharedmethod @format_doc(_arit_doc, name='subtraction', op='-') def subtract(self, operand, operand2=None, **kwargs): return self._prepare_then_do_arithmetic(np.subtract, operand, operand2, **kwargs) @sharedmethod @format_doc(_arit_doc, name="multiplication", op="*") def multiply(self, operand, operand2=None, **kwargs): return self._prepare_then_do_arithmetic(np.multiply, operand, operand2, **kwargs) @sharedmethod @format_doc(_arit_doc, name="division", op="/") def divide(self, operand, operand2=None, **kwargs): return self._prepare_then_do_arithmetic(np.true_divide, operand, operand2, **kwargs) @sharedmethod def _prepare_then_do_arithmetic(self_or_cls, operation, operand, operand2, **kwargs): """Intermediate method called by public arithmetics (i.e. ``add``) before the processing method (``_arithmetic``) is invoked. .. warning:: Do not override this method in subclasses. This method checks if it was called as instance or as class method and then wraps the operands and the result from ``_arithmetics`` in the appropriate subclass. Parameters ---------- self_or_cls : instance or class ``sharedmethod`` behaves like a normal method if called on the instance (then this parameter is ``self``) but like a classmethod when called on the class (then this parameter is ``cls``). operations : callable The operation (normally a numpy-ufunc) that represents the appropriate action. operand, operand2, kwargs : See for example ``add``. Result ------ result : `~astropy.nddata.NDData`-like Depending how this method was called either ``self_or_cls`` (called on class) or ``self_or_cls.__class__`` (called on instance) is the NDData-subclass that is used as wrapper for the result. """ # DO NOT OVERRIDE THIS METHOD IN SUBCLASSES. if isinstance(self_or_cls, NDArithmeticMixin): # True means it was called on the instance, so self_or_cls is # a reference to self cls = self_or_cls.__class__ if operand2 is None: # Only one operand was given. Set operand2 to operand and # operand to self so that we call the appropriate method of the # operand. operand2 = operand operand = self_or_cls else: # Convert the first operand to the class of this method. # This is important so that always the correct _arithmetics is # called later that method. operand = cls(operand) else: # It was used as classmethod so self_or_cls represents the cls cls = self_or_cls # It was called on the class so we expect two operands! if operand2 is None: raise TypeError("operand2 must be given when the method isn't " "called on an instance.") # Convert to this class. See above comment why. operand = cls(operand) # At this point operand, operand2, kwargs and cls are determined. # Let's try to convert operand2 to the class of operand to allows for # arithmetic operations with numbers, lists, numpy arrays, numpy masked # arrays, astropy quantities, masked quantities and of other subclasses # of NDData. operand2 = cls(operand2) # Now call the _arithmetics method to do the arithmetics. result, init_kwds = operand._arithmetic(operation, operand2, **kwargs) # Return a new class based on the result return cls(result, **init_kwds)
d13e953abdab945d00eb41390e7c9a8c8ac943ad9f66eedf09c4aa9ad838edb2
# Licensed under a 3-clause BSD style license - see LICENSE.rst # This module implements the I/O mixin to the NDData class. from astropy.io import registry __all__ = ['NDIOMixin'] __doctest_skip__ = ['NDDataRead', 'NDDataWrite'] class NDDataRead(registry.UnifiedReadWrite): """Read and parse gridded N-dimensional data and return as an NDData-derived object. This function provides the NDDataBase interface to the astropy unified I/O layer. This allows easily reading a file in the supported data formats, for example:: >>> from astropy.nddata import CCDData >>> dat = CCDData.read('image.fits') Get help on the available readers for ``CCDData`` using the``help()`` method:: >>> CCDData.read.help() # Get help reading CCDData and list supported formats >>> CCDData.read.help('fits') # Get detailed help on CCDData FITS reader >>> CCDData.read.list_formats() # Print list of available formats See also: - https://docs.astropy.org/en/stable/nddata - https://docs.astropy.org/en/stable/io/unified.html Parameters ---------- *args : tuple, optional Positional arguments passed through to data reader. If supplied the first argument is the input filename. format : str, optional File format specifier. cache : bool, optional Caching behavior if file is a URL. **kwargs : dict, optional Keyword arguments passed through to data reader. Returns ------- out : `NDData` subclass NDData-basd object corresponding to file contents Notes ----- """ def __init__(self, instance, cls): super().__init__(instance, cls, 'read', registry=None) # uses default global registry def __call__(self, *args, **kwargs): return self.registry.read(self._cls, *args, **kwargs) class NDDataWrite(registry.UnifiedReadWrite): """Write this CCDData object out in the specified format. This function provides the NDData interface to the astropy unified I/O layer. This allows easily writing a file in many supported data formats using syntax such as:: >>> from astropy.nddata import CCDData >>> dat = CCDData(np.zeros((12, 12)), unit='adu') # 12x12 image of zeros >>> dat.write('zeros.fits') Get help on the available writers for ``CCDData`` using the``help()`` method:: >>> CCDData.write.help() # Get help writing CCDData and list supported formats >>> CCDData.write.help('fits') # Get detailed help on CCDData FITS writer >>> CCDData.write.list_formats() # Print list of available formats See also: - https://docs.astropy.org/en/stable/nddata - https://docs.astropy.org/en/stable/io/unified.html Parameters ---------- *args : tuple, optional Positional arguments passed through to data writer. If supplied the first argument is the output filename. format : str, optional File format specifier. **kwargs : dict, optional Keyword arguments passed through to data writer. Notes ----- """ def __init__(self, instance, cls): super().__init__(instance, cls, 'write', registry=None) # uses default global registry def __call__(self, *args, **kwargs): self.registry.write(self._instance, *args, **kwargs) class NDIOMixin: """ Mixin class to connect NDData to the astropy input/output registry. This mixin adds two methods to its subclasses, ``read`` and ``write``. """ read = registry.UnifiedReadWriteMethod(NDDataRead) write = registry.UnifiedReadWriteMethod(NDDataWrite)
82b1097a6cc93afbe45814a6da1d684dd8974614fbe88677f74ea5a9abd3976d
# Licensed under a 3-clause BSD style license - see LICENSE.rst import textwrap import numpy as np import pytest from astropy.io import fits from astropy.nddata.nduncertainty import ( StdDevUncertainty, MissingDataAssociationException, VarianceUncertainty, InverseVariance) from astropy import units as u from astropy import log from astropy.wcs import WCS, FITSFixedWarning from astropy.utils import NumpyRNGContext from astropy.utils.data import (get_pkg_data_filename, get_pkg_data_filenames, get_pkg_data_contents) from astropy.utils.exceptions import AstropyWarning from astropy.nddata.ccddata import CCDData from astropy.nddata import _testing as nd_testing from astropy.table import Table DEFAULT_DATA_SIZE = 100 with NumpyRNGContext(123): _random_array = np.random.normal(size=[DEFAULT_DATA_SIZE, DEFAULT_DATA_SIZE]) def create_ccd_data(): """ Return a CCDData object of size DEFAULT_DATA_SIZE x DEFAULT_DATA_SIZE with units of ADU. """ data = _random_array.copy() fake_meta = {'my_key': 42, 'your_key': 'not 42'} ccd = CCDData(data, unit=u.adu) ccd.header = fake_meta return ccd def test_ccddata_empty(): with pytest.raises(TypeError): CCDData() # empty initializer should fail def test_ccddata_must_have_unit(): with pytest.raises(ValueError): CCDData(np.zeros([2, 2])) def test_ccddata_unit_cannot_be_set_to_none(): ccd_data = create_ccd_data() with pytest.raises(TypeError): ccd_data.unit = None def test_ccddata_meta_header_conflict(): with pytest.raises(ValueError) as exc: CCDData([1, 2, 3], unit='', meta={1: 1}, header={2: 2}) assert "can't have both header and meta." in str(exc.value) def test_ccddata_simple(): ccd_data = create_ccd_data() assert ccd_data.shape == (DEFAULT_DATA_SIZE, DEFAULT_DATA_SIZE) assert ccd_data.size == DEFAULT_DATA_SIZE * DEFAULT_DATA_SIZE assert ccd_data.dtype == np.dtype(float) def test_ccddata_init_with_string_electron_unit(): ccd = CCDData(np.zeros([2, 2]), unit="electron") assert ccd.unit is u.electron def test_initialize_from_FITS(tmpdir): ccd_data = create_ccd_data() hdu = fits.PrimaryHDU(ccd_data) hdulist = fits.HDUList([hdu]) filename = tmpdir.join('afile.fits').strpath hdulist.writeto(filename) cd = CCDData.read(filename, unit=u.electron) assert cd.shape == (DEFAULT_DATA_SIZE, DEFAULT_DATA_SIZE) assert cd.size == DEFAULT_DATA_SIZE * DEFAULT_DATA_SIZE assert np.issubdtype(cd.data.dtype, np.floating) for k, v in hdu.header.items(): assert cd.meta[k] == v def test_initialize_from_fits_with_unit_in_header(tmpdir): fake_img = np.zeros([2, 2]) hdu = fits.PrimaryHDU(fake_img) hdu.header['bunit'] = u.adu.to_string() filename = tmpdir.join('afile.fits').strpath hdu.writeto(filename) ccd = CCDData.read(filename) # ccd should pick up the unit adu from the fits header...did it? assert ccd.unit is u.adu # An explicit unit in the read overrides any unit in the FITS file ccd2 = CCDData.read(filename, unit="photon") assert ccd2.unit is u.photon def test_initialize_from_fits_with_ADU_in_header(tmpdir): fake_img = np.zeros([2, 2]) hdu = fits.PrimaryHDU(fake_img) hdu.header['bunit'] = 'ADU' filename = tmpdir.join('afile.fits').strpath hdu.writeto(filename) ccd = CCDData.read(filename) # ccd should pick up the unit adu from the fits header...did it? assert ccd.unit is u.adu def test_initialize_from_fits_with_invalid_unit_in_header(tmpdir): hdu = fits.PrimaryHDU(np.ones((2, 2))) hdu.header['bunit'] = 'definetely-not-a-unit' filename = tmpdir.join('afile.fits').strpath hdu.writeto(filename) with pytest.raises(ValueError): CCDData.read(filename) def test_initialize_from_fits_with_technically_invalid_but_not_really(tmpdir): hdu = fits.PrimaryHDU(np.ones((2, 2))) hdu.header['bunit'] = 'ELECTRONS/S' filename = tmpdir.join('afile.fits').strpath hdu.writeto(filename) ccd = CCDData.read(filename) assert ccd.unit == u.electron/u.s def test_initialize_from_fits_with_data_in_different_extension(tmpdir): fake_img = np.arange(4).reshape(2, 2) hdu1 = fits.PrimaryHDU() hdu2 = fits.ImageHDU(fake_img) hdus = fits.HDUList([hdu1, hdu2]) filename = tmpdir.join('afile.fits').strpath hdus.writeto(filename) ccd = CCDData.read(filename, unit='adu') # ccd should pick up the unit adu from the fits header...did it? np.testing.assert_array_equal(ccd.data, fake_img) # check that the header is the combined header assert hdu2.header + hdu1.header == ccd.header def test_initialize_from_fits_with_extension(tmpdir): fake_img1 = np.zeros([2, 2]) fake_img2 = np.arange(4).reshape(2, 2) hdu0 = fits.PrimaryHDU() hdu1 = fits.ImageHDU(fake_img1, name='first', ver=1) hdu2 = fits.ImageHDU(fake_img2, name='second', ver=1) hdus = fits.HDUList([hdu0, hdu1, hdu2]) filename = tmpdir.join('afile.fits').strpath hdus.writeto(filename) ccd = CCDData.read(filename, hdu=2, unit='adu') # ccd should pick up the unit adu from the fits header...did it? np.testing.assert_array_equal(ccd.data, fake_img2) # check hdu string parameter ccd = CCDData.read(filename, hdu='second', unit='adu') np.testing.assert_array_equal(ccd.data, fake_img2) # check hdu tuple parameter ccd = CCDData.read(filename, hdu=('second', 1), unit='adu') np.testing.assert_array_equal(ccd.data, fake_img2) def test_write_unit_to_hdu(): ccd_data = create_ccd_data() ccd_unit = ccd_data.unit hdulist = ccd_data.to_hdu() assert 'bunit' in hdulist[0].header assert hdulist[0].header['bunit'] == ccd_unit.to_string() def test_initialize_from_FITS_bad_keyword_raises_error(tmpdir): # There are two fits.open keywords that are not permitted in ccdproc: # do_not_scale_image_data and scale_back ccd_data = create_ccd_data() filename = tmpdir.join('test.fits').strpath ccd_data.write(filename) with pytest.raises(TypeError): CCDData.read(filename, unit=ccd_data.unit, do_not_scale_image_data=True) with pytest.raises(TypeError): CCDData.read(filename, unit=ccd_data.unit, scale_back=True) def test_ccddata_writer(tmpdir): ccd_data = create_ccd_data() filename = tmpdir.join('test.fits').strpath ccd_data.write(filename) ccd_disk = CCDData.read(filename, unit=ccd_data.unit) np.testing.assert_array_equal(ccd_data.data, ccd_disk.data) def test_ccddata_meta_is_case_sensitive(): ccd_data = create_ccd_data() key = 'SoMeKEY' ccd_data.meta[key] = 10 assert key.lower() not in ccd_data.meta assert key.upper() not in ccd_data.meta assert key in ccd_data.meta def test_ccddata_meta_is_not_fits_header(): ccd_data = create_ccd_data() ccd_data.meta = {'OBSERVER': 'Edwin Hubble'} assert not isinstance(ccd_data.meta, fits.Header) def test_fromMEF(tmpdir): ccd_data = create_ccd_data() hdu = fits.PrimaryHDU(ccd_data) hdu2 = fits.PrimaryHDU(2 * ccd_data.data) hdulist = fits.HDUList(hdu) hdulist.append(hdu2) filename = tmpdir.join('afile.fits').strpath hdulist.writeto(filename) # by default, we reading from the first extension cd = CCDData.read(filename, unit=u.electron) np.testing.assert_array_equal(cd.data, ccd_data.data) # but reading from the second should work too cd = CCDData.read(filename, hdu=1, unit=u.electron) np.testing.assert_array_equal(cd.data, 2 * ccd_data.data) def test_metafromheader(): hdr = fits.header.Header() hdr['observer'] = 'Edwin Hubble' hdr['exptime'] = '3600' d1 = CCDData(np.ones((5, 5)), meta=hdr, unit=u.electron) assert d1.meta['OBSERVER'] == 'Edwin Hubble' assert d1.header['OBSERVER'] == 'Edwin Hubble' def test_metafromdict(): dic = {'OBSERVER': 'Edwin Hubble', 'EXPTIME': 3600} d1 = CCDData(np.ones((5, 5)), meta=dic, unit=u.electron) assert d1.meta['OBSERVER'] == 'Edwin Hubble' def test_header2meta(): hdr = fits.header.Header() hdr['observer'] = 'Edwin Hubble' hdr['exptime'] = '3600' d1 = CCDData(np.ones((5, 5)), unit=u.electron) d1.header = hdr assert d1.meta['OBSERVER'] == 'Edwin Hubble' assert d1.header['OBSERVER'] == 'Edwin Hubble' def test_metafromstring_fail(): hdr = 'this is not a valid header' with pytest.raises(TypeError): CCDData(np.ones((5, 5)), meta=hdr, unit=u.adu) def test_setting_bad_uncertainty_raises_error(): ccd_data = create_ccd_data() with pytest.raises(TypeError): # Uncertainty is supposed to be an instance of NDUncertainty ccd_data.uncertainty = 10 def test_setting_uncertainty_with_array(): ccd_data = create_ccd_data() ccd_data.uncertainty = None fake_uncertainty = np.sqrt(np.abs(ccd_data.data)) ccd_data.uncertainty = fake_uncertainty.copy() np.testing.assert_array_equal(ccd_data.uncertainty.array, fake_uncertainty) def test_setting_uncertainty_wrong_shape_raises_error(): ccd_data = create_ccd_data() with pytest.raises(ValueError): ccd_data.uncertainty = np.zeros([3, 4]) def test_to_hdu(): ccd_data = create_ccd_data() ccd_data.meta = {'observer': 'Edwin Hubble'} fits_hdulist = ccd_data.to_hdu() assert isinstance(fits_hdulist, fits.HDUList) for k, v in ccd_data.meta.items(): assert fits_hdulist[0].header[k] == v np.testing.assert_array_equal(fits_hdulist[0].data, ccd_data.data) def test_copy(): ccd_data = create_ccd_data() ccd_copy = ccd_data.copy() np.testing.assert_array_equal(ccd_copy.data, ccd_data.data) assert ccd_copy.unit == ccd_data.unit assert ccd_copy.meta == ccd_data.meta @pytest.mark.parametrize('operation,affects_uncertainty', [ ("multiply", True), ("divide", True), ]) @pytest.mark.parametrize('operand', [ 2.0, 2 * u.dimensionless_unscaled, 2 * u.photon / u.adu, ]) @pytest.mark.parametrize('with_uncertainty', [ True, False]) def test_mult_div_overload(operand, with_uncertainty, operation, affects_uncertainty): ccd_data = create_ccd_data() if with_uncertainty: ccd_data.uncertainty = StdDevUncertainty(np.ones_like(ccd_data)) method = getattr(ccd_data, operation) np_method = getattr(np, operation) result = method(operand) assert result is not ccd_data assert isinstance(result, CCDData) assert (result.uncertainty is None or isinstance(result.uncertainty, StdDevUncertainty)) try: op_value = operand.value except AttributeError: op_value = operand np.testing.assert_array_equal(result.data, np_method(ccd_data.data, op_value)) if with_uncertainty: if affects_uncertainty: np.testing.assert_array_equal(result.uncertainty.array, np_method(ccd_data.uncertainty.array, op_value)) else: np.testing.assert_array_equal(result.uncertainty.array, ccd_data.uncertainty.array) else: assert result.uncertainty is None if isinstance(operand, u.Quantity): # Need the "1 *" below to force arguments to be Quantity to work around # astropy/astropy#2377 expected_unit = np_method(1 * ccd_data.unit, 1 * operand.unit).unit assert result.unit == expected_unit else: assert result.unit == ccd_data.unit @pytest.mark.parametrize('operation,affects_uncertainty', [ ("add", False), ("subtract", False), ]) @pytest.mark.parametrize('operand,expect_failure', [ (2.0, u.UnitsError), # fail--units don't match image (2 * u.dimensionless_unscaled, u.UnitsError), # same (2 * u.adu, False), ]) @pytest.mark.parametrize('with_uncertainty', [ True, False]) def test_add_sub_overload(operand, expect_failure, with_uncertainty, operation, affects_uncertainty): ccd_data = create_ccd_data() if with_uncertainty: ccd_data.uncertainty = StdDevUncertainty(np.ones_like(ccd_data)) method = getattr(ccd_data, operation) np_method = getattr(np, operation) if expect_failure: with pytest.raises(expect_failure): result = method(operand) return else: result = method(operand) assert result is not ccd_data assert isinstance(result, CCDData) assert (result.uncertainty is None or isinstance(result.uncertainty, StdDevUncertainty)) try: op_value = operand.value except AttributeError: op_value = operand np.testing.assert_array_equal(result.data, np_method(ccd_data.data, op_value)) if with_uncertainty: if affects_uncertainty: np.testing.assert_array_equal(result.uncertainty.array, np_method(ccd_data.uncertainty.array, op_value)) else: np.testing.assert_array_equal(result.uncertainty.array, ccd_data.uncertainty.array) else: assert result.uncertainty is None if isinstance(operand, u.Quantity): assert (result.unit == ccd_data.unit and result.unit == operand.unit) else: assert result.unit == ccd_data.unit def test_arithmetic_overload_fails(): ccd_data = create_ccd_data() with pytest.raises(TypeError): ccd_data.multiply("five") with pytest.raises(TypeError): ccd_data.divide("five") with pytest.raises(TypeError): ccd_data.add("five") with pytest.raises(TypeError): ccd_data.subtract("five") def test_arithmetic_no_wcs_compare(): ccd = CCDData(np.ones((10, 10)), unit='') assert ccd.add(ccd, compare_wcs=None).wcs is None assert ccd.subtract(ccd, compare_wcs=None).wcs is None assert ccd.multiply(ccd, compare_wcs=None).wcs is None assert ccd.divide(ccd, compare_wcs=None).wcs is None def test_arithmetic_with_wcs_compare(): def return_true(_, __): return True wcs1, wcs2 = nd_testing.create_two_equal_wcs(naxis=2) ccd1 = CCDData(np.ones((10, 10)), unit='', wcs=wcs1) ccd2 = CCDData(np.ones((10, 10)), unit='', wcs=wcs2) nd_testing.assert_wcs_seem_equal( ccd1.add(ccd2, compare_wcs=return_true).wcs, wcs1) nd_testing.assert_wcs_seem_equal( ccd1.subtract(ccd2, compare_wcs=return_true).wcs, wcs1) nd_testing.assert_wcs_seem_equal( ccd1.multiply(ccd2, compare_wcs=return_true).wcs, wcs1) nd_testing.assert_wcs_seem_equal( ccd1.divide(ccd2, compare_wcs=return_true).wcs, wcs1) def test_arithmetic_with_wcs_compare_fail(): def return_false(_, __): return False ccd1 = CCDData(np.ones((10, 10)), unit='', wcs=WCS()) ccd2 = CCDData(np.ones((10, 10)), unit='', wcs=WCS()) with pytest.raises(ValueError): ccd1.add(ccd2, compare_wcs=return_false) with pytest.raises(ValueError): ccd1.subtract(ccd2, compare_wcs=return_false) with pytest.raises(ValueError): ccd1.multiply(ccd2, compare_wcs=return_false) with pytest.raises(ValueError): ccd1.divide(ccd2, compare_wcs=return_false) def test_arithmetic_overload_ccddata_operand(): ccd_data = create_ccd_data() ccd_data.uncertainty = StdDevUncertainty(np.ones_like(ccd_data)) operand = ccd_data.copy() result = ccd_data.add(operand) assert len(result.meta) == 0 np.testing.assert_array_equal(result.data, 2 * ccd_data.data) np.testing.assert_array_almost_equal_nulp( result.uncertainty.array, np.sqrt(2) * ccd_data.uncertainty.array ) result = ccd_data.subtract(operand) assert len(result.meta) == 0 np.testing.assert_array_equal(result.data, 0 * ccd_data.data) np.testing.assert_array_almost_equal_nulp( result.uncertainty.array, np.sqrt(2) * ccd_data.uncertainty.array ) result = ccd_data.multiply(operand) assert len(result.meta) == 0 np.testing.assert_array_equal(result.data, ccd_data.data ** 2) expected_uncertainty = (np.sqrt(2) * np.abs(ccd_data.data) * ccd_data.uncertainty.array) np.testing.assert_allclose(result.uncertainty.array, expected_uncertainty) result = ccd_data.divide(operand) assert len(result.meta) == 0 np.testing.assert_array_equal(result.data, np.ones_like(ccd_data.data)) expected_uncertainty = (np.sqrt(2) / np.abs(ccd_data.data) * ccd_data.uncertainty.array) np.testing.assert_allclose(result.uncertainty.array, expected_uncertainty) def test_arithmetic_overload_differing_units(): a = np.array([1, 2, 3]) * u.m b = np.array([1, 2, 3]) * u.cm ccddata = CCDData(a) # TODO: Could also be parametrized. res = ccddata.add(b) np.testing.assert_array_almost_equal(res.data, np.add(a, b).value) assert res.unit == np.add(a, b).unit res = ccddata.subtract(b) np.testing.assert_array_almost_equal(res.data, np.subtract(a, b).value) assert res.unit == np.subtract(a, b).unit res = ccddata.multiply(b) np.testing.assert_array_almost_equal(res.data, np.multiply(a, b).value) assert res.unit == np.multiply(a, b).unit res = ccddata.divide(b) np.testing.assert_array_almost_equal(res.data, np.divide(a, b).value) assert res.unit == np.divide(a, b).unit def test_arithmetic_add_with_array(): ccd = CCDData(np.ones((3, 3)), unit='') res = ccd.add(np.arange(3)) np.testing.assert_array_equal(res.data, [[1, 2, 3]] * 3) ccd = CCDData(np.ones((3, 3)), unit='adu') with pytest.raises(ValueError): ccd.add(np.arange(3)) def test_arithmetic_subtract_with_array(): ccd = CCDData(np.ones((3, 3)), unit='') res = ccd.subtract(np.arange(3)) np.testing.assert_array_equal(res.data, [[1, 0, -1]] * 3) ccd = CCDData(np.ones((3, 3)), unit='adu') with pytest.raises(ValueError): ccd.subtract(np.arange(3)) def test_arithmetic_multiply_with_array(): ccd = CCDData(np.ones((3, 3)) * 3, unit=u.m) res = ccd.multiply(np.ones((3, 3)) * 2) np.testing.assert_array_equal(res.data, [[6, 6, 6]] * 3) assert res.unit == ccd.unit def test_arithmetic_divide_with_array(): ccd = CCDData(np.ones((3, 3)), unit=u.m) res = ccd.divide(np.ones((3, 3)) * 2) np.testing.assert_array_equal(res.data, [[0.5, 0.5, 0.5]] * 3) assert res.unit == ccd.unit def test_history_preserved_if_metadata_is_fits_header(tmpdir): fake_img = np.zeros([2, 2]) hdu = fits.PrimaryHDU(fake_img) hdu.header['history'] = 'one' hdu.header['history'] = 'two' hdu.header['history'] = 'three' assert len(hdu.header['history']) == 3 tmp_file = tmpdir.join('temp.fits').strpath hdu.writeto(tmp_file) ccd_read = CCDData.read(tmp_file, unit="adu") assert ccd_read.header['history'] == hdu.header['history'] def test_infol_logged_if_unit_in_fits_header(tmpdir): ccd_data = create_ccd_data() tmpfile = tmpdir.join('temp.fits') ccd_data.write(tmpfile.strpath) log.setLevel('INFO') explicit_unit_name = "photon" with log.log_to_list() as log_list: _ = CCDData.read(tmpfile.strpath, unit=explicit_unit_name) assert explicit_unit_name in log_list[0].message def test_wcs_attribute(tmpdir): """ Check that WCS attribute gets added to header, and that if a CCDData object is created from a FITS file with a header, and the WCS attribute is modified, then the CCDData object is turned back into an hdu, the WCS object overwrites the old WCS information in the header. """ ccd_data = create_ccd_data() tmpfile = tmpdir.join('temp.fits') # This wcs example is taken from the astropy.wcs docs. wcs = WCS(naxis=2) wcs.wcs.crpix = np.array(ccd_data.shape) / 2 wcs.wcs.cdelt = np.array([-0.066667, 0.066667]) wcs.wcs.crval = [0, -90] wcs.wcs.ctype = ["RA---AIR", "DEC--AIR"] wcs.wcs.set_pv([(2, 1, 45.0)]) ccd_data.header = ccd_data.to_hdu()[0].header ccd_data.header.extend(wcs.to_header(), useblanks=False) ccd_data.write(tmpfile.strpath) # Get the header length after it has been extended by the WCS keywords original_header_length = len(ccd_data.header) ccd_new = CCDData.read(tmpfile.strpath) # WCS attribute should be set for ccd_new assert ccd_new.wcs is not None # WCS attribute should be equal to wcs above. assert ccd_new.wcs.wcs == wcs.wcs # Converting CCDData object with wcs to an hdu shouldn't # create duplicate wcs-related entries in the header. ccd_new_hdu = ccd_new.to_hdu()[0] assert len(ccd_new_hdu.header) == original_header_length # Making a CCDData with WCS (but not WCS in the header) should lead to # WCS information in the header when it is converted to an HDU. ccd_wcs_not_in_header = CCDData(ccd_data.data, wcs=wcs, unit="adu") hdu = ccd_wcs_not_in_header.to_hdu()[0] wcs_header = wcs.to_header() for k in wcs_header.keys(): # Skip these keywords if they are in the WCS header because they are # not WCS-specific. if k in ['', 'COMMENT', 'HISTORY']: continue # No keyword from the WCS should be in the header. assert k not in ccd_wcs_not_in_header.header # Every keyword in the WCS should be in the header of the HDU assert hdu.header[k] == wcs_header[k] # Now check that if WCS of a CCDData is modified, then the CCDData is # converted to an HDU, the WCS keywords in the header are overwritten # with the appropriate keywords from the header. # # ccd_new has a WCS and WCS keywords in the header, so try modifying # the WCS. ccd_new.wcs.wcs.cdelt *= 2 ccd_new_hdu_mod_wcs = ccd_new.to_hdu()[0] assert ccd_new_hdu_mod_wcs.header['CDELT1'] == ccd_new.wcs.wcs.cdelt[0] assert ccd_new_hdu_mod_wcs.header['CDELT2'] == ccd_new.wcs.wcs.cdelt[1] def test_wcs_keywords_removed_from_header(): """ Test, for the file included with the nddata tests, that WCS keywords are properly removed from header. """ from astropy.nddata.ccddata import _KEEP_THESE_KEYWORDS_IN_HEADER keepers = set(_KEEP_THESE_KEYWORDS_IN_HEADER) data_file = get_pkg_data_filename('data/sip-wcs.fits') ccd = CCDData.read(data_file) with pytest.warns(AstropyWarning, match=r'Some non-standard WCS keywords were excluded'): wcs_header = ccd.wcs.to_header() assert not (set(wcs_header) & set(ccd.meta) - keepers) # Make sure that exceptions are not raised when trying to remove missing # keywords. o4sp040b0_raw.fits of io.fits is missing keyword 'PC1_1'. data_file1 = get_pkg_data_filename('../../io/fits/tests/data/o4sp040b0_raw.fits') with pytest.warns(FITSFixedWarning, match=r"'unitfix' made the change"): ccd = CCDData.read(data_file1, unit='count') def test_wcs_SIP_coefficient_keywords_removed(): # If SIP polynomials are present, check that no more polynomial # coefficients remain in the header. See #8598 # The SIP paper is ambiguous as to whether keywords like # A_0_0 can appear in the header for a 2nd order or higher # polynomial. The paper clearly says that the corrections # are only for quadratic or higher order, so A_0_0 and the like # should be zero if they are present, but they apparently can be # there (or at least astrometry.net produces them). # astropy WCS does not write those coefficients, so they were # not being removed from the header even though they are WCS-related. data_file = get_pkg_data_filename('data/sip-wcs.fits') test_keys = ['A_0_0', 'B_0_1'] # Make sure the keywords added to this file for testing are there with fits.open(data_file) as hdu: for key in test_keys: assert key in hdu[0].header ccd = CCDData.read(data_file) # Now the test...the two keywords above should have been removed. for key in test_keys: assert key not in ccd.header @pytest.mark.filterwarnings('ignore') def test_wcs_keyword_removal_for_wcs_test_files(): """ Test, for the WCS test files, that keyword removal works as expected. Those cover a much broader range of WCS types than test_wcs_keywords_removed_from_header. Includes regression test for #8597 """ from astropy.nddata.ccddata import _generate_wcs_and_update_header from astropy.nddata.ccddata import (_KEEP_THESE_KEYWORDS_IN_HEADER, _CDs, _PCs) keepers = set(_KEEP_THESE_KEYWORDS_IN_HEADER) wcs_headers = get_pkg_data_filenames('../../wcs/tests/data', pattern='*.hdr') for hdr in wcs_headers: # Skip the files that are expected to be bad... if ('invalid' in hdr or 'nonstandard' in hdr or 'segfault' in hdr or 'chandra-pixlist-wcs' in hdr): continue header_string = get_pkg_data_contents(hdr) header = fits.Header.fromstring(header_string) wcs = WCS(header_string) header_from_wcs = wcs.to_header(relax=True) new_header, new_wcs = _generate_wcs_and_update_header(header) new_wcs_header = new_wcs.to_header(relax=True) # Make sure all of the WCS-related keywords generated by astropy # have been removed. assert not (set(new_header) & set(new_wcs_header) - keepers) # Check that new_header contains no remaining WCS information. # Specifically, check that # 1. The combination of new_header and new_wcs does not contain # both PCi_j and CDi_j keywords. See #8597. # Check for 1 final_header = new_header + new_wcs_header final_header_set = set(final_header) if _PCs & final_header_set: assert not (_CDs & final_header_set) elif _CDs & final_header_set: assert not (_PCs & final_header_set) # Check that the new wcs is the same as the old. for k, v in new_wcs_header.items(): if isinstance(v, str): assert header_from_wcs[k] == v else: np.testing.assert_almost_equal(header_from_wcs[k], v) def test_read_wcs_not_creatable(tmpdir): # The following Header can't be converted to a WCS object. See also #6499. hdr_txt_example_WCS = textwrap.dedent(''' SIMPLE = T / Fits standard BITPIX = 16 / Bits per pixel NAXIS = 2 / Number of axes NAXIS1 = 1104 / Axis length NAXIS2 = 4241 / Axis length CRVAL1 = 164.98110962 / Physical value of the reference pixel X CRVAL2 = 44.34089279 / Physical value of the reference pixel Y CRPIX1 = -34.0 / Reference pixel in X (pixel) CRPIX2 = 2041.0 / Reference pixel in Y (pixel) CDELT1 = 0.10380000 / X Scale projected on detector (#/pix) CDELT2 = 0.10380000 / Y Scale projected on detector (#/pix) CTYPE1 = 'RA---TAN' / Pixel coordinate system CTYPE2 = 'WAVELENGTH' / Pixel coordinate system CUNIT1 = 'degree ' / Units used in both CRVAL1 and CDELT1 CUNIT2 = 'nm ' / Units used in both CRVAL2 and CDELT2 CD1_1 = 0.20760000 / Pixel Coordinate translation matrix CD1_2 = 0.00000000 / Pixel Coordinate translation matrix CD2_1 = 0.00000000 / Pixel Coordinate translation matrix CD2_2 = 0.10380000 / Pixel Coordinate translation matrix C2YPE1 = 'RA---TAN' / Pixel coordinate system C2YPE2 = 'DEC--TAN' / Pixel coordinate system C2NIT1 = 'degree ' / Units used in both C2VAL1 and C2ELT1 C2NIT2 = 'degree ' / Units used in both C2VAL2 and C2ELT2 RADECSYS= 'FK5 ' / The equatorial coordinate system ''') hdr = fits.Header.fromstring(hdr_txt_example_WCS, sep='\n') hdul = fits.HDUList([fits.PrimaryHDU(np.ones((4241, 1104)), header=hdr)]) filename = tmpdir.join('afile.fits').strpath hdul.writeto(filename) # The hdr cannot be converted to a WCS object because of an # InconsistentAxisTypesError but it should still open the file ccd = CCDData.read(filename, unit='adu') assert ccd.wcs is None def test_header(): ccd_data = create_ccd_data() a = {'Observer': 'Hubble'} ccd = CCDData(ccd_data, header=a) assert ccd.meta == a def test_wcs_arithmetic(): ccd_data = create_ccd_data() wcs = WCS(naxis=2) ccd_data.wcs = wcs result = ccd_data.multiply(1.0) nd_testing.assert_wcs_seem_equal(result.wcs, wcs) @pytest.mark.parametrize('operation', ['multiply', 'divide', 'add', 'subtract']) def test_wcs_arithmetic_ccd(operation): ccd_data = create_ccd_data() ccd_data2 = ccd_data.copy() ccd_data.wcs = WCS(naxis=2) method = getattr(ccd_data, operation) result = method(ccd_data2) nd_testing.assert_wcs_seem_equal(result.wcs, ccd_data.wcs) assert ccd_data2.wcs is None def test_wcs_sip_handling(): """ Check whether the ctypes RA---TAN-SIP and DEC--TAN-SIP survive a roundtrip unchanged. """ data_file = get_pkg_data_filename('data/sip-wcs.fits') def check_wcs_ctypes(header): expected_wcs_ctypes = { 'CTYPE1': 'RA---TAN-SIP', 'CTYPE2': 'DEC--TAN-SIP' } return [header[k] == v for k, v in expected_wcs_ctypes.items()] ccd_original = CCDData.read(data_file) # After initialization the keywords should be in the WCS, not in the # meta. with fits.open(data_file) as raw: good_ctype = check_wcs_ctypes(raw[0].header) assert all(good_ctype) ccd_new = ccd_original.to_hdu() good_ctype = check_wcs_ctypes(ccd_new[0].header) assert all(good_ctype) # Try converting to header with wcs_relax=False and # the header should contain the CTYPE keywords without # the -SIP ccd_no_relax = ccd_original.to_hdu(wcs_relax=False) good_ctype = check_wcs_ctypes(ccd_no_relax[0].header) assert not any(good_ctype) assert ccd_no_relax[0].header['CTYPE1'] == 'RA---TAN' assert ccd_no_relax[0].header['CTYPE2'] == 'DEC--TAN' @pytest.mark.parametrize('operation', ['multiply', 'divide', 'add', 'subtract']) def test_mask_arithmetic_ccd(operation): ccd_data = create_ccd_data() ccd_data2 = ccd_data.copy() ccd_data.mask = (ccd_data.data > 0) method = getattr(ccd_data, operation) result = method(ccd_data2) np.testing.assert_equal(result.mask, ccd_data.mask) def test_write_read_multiextensionfits_mask_default(tmpdir): # Test that if a mask is present the mask is saved and loaded by default. ccd_data = create_ccd_data() ccd_data.mask = ccd_data.data > 10 filename = tmpdir.join('afile.fits').strpath ccd_data.write(filename) ccd_after = CCDData.read(filename) assert ccd_after.mask is not None np.testing.assert_array_equal(ccd_data.mask, ccd_after.mask) @pytest.mark.parametrize( 'uncertainty_type', [StdDevUncertainty, VarianceUncertainty, InverseVariance]) def test_write_read_multiextensionfits_uncertainty_default( tmpdir, uncertainty_type): # Test that if a uncertainty is present it is saved and loaded by default. ccd_data = create_ccd_data() ccd_data.uncertainty = uncertainty_type(ccd_data.data * 10) filename = tmpdir.join('afile.fits').strpath ccd_data.write(filename) ccd_after = CCDData.read(filename) assert ccd_after.uncertainty is not None assert type(ccd_after.uncertainty) is uncertainty_type np.testing.assert_array_equal(ccd_data.uncertainty.array, ccd_after.uncertainty.array) @pytest.mark.parametrize( 'uncertainty_type', [StdDevUncertainty, VarianceUncertainty, InverseVariance]) def test_write_read_multiextensionfits_uncertainty_different_uncertainty_key( tmpdir, uncertainty_type): # Test that if a uncertainty is present it is saved and loaded by default. ccd_data = create_ccd_data() ccd_data.uncertainty = uncertainty_type(ccd_data.data * 10) filename = tmpdir.join('afile.fits').strpath ccd_data.write(filename, key_uncertainty_type='Blah') ccd_after = CCDData.read(filename, key_uncertainty_type='Blah') assert ccd_after.uncertainty is not None assert type(ccd_after.uncertainty) is uncertainty_type np.testing.assert_array_equal(ccd_data.uncertainty.array, ccd_after.uncertainty.array) def test_write_read_multiextensionfits_not(tmpdir): # Test that writing mask and uncertainty can be disabled ccd_data = create_ccd_data() ccd_data.mask = ccd_data.data > 10 ccd_data.uncertainty = StdDevUncertainty(ccd_data.data * 10) filename = tmpdir.join('afile.fits').strpath ccd_data.write(filename, hdu_mask=None, hdu_uncertainty=None) ccd_after = CCDData.read(filename) assert ccd_after.uncertainty is None assert ccd_after.mask is None def test_write_read_multiextensionfits_custom_ext_names(tmpdir): # Test writing mask, uncertainty in another extension than default ccd_data = create_ccd_data() ccd_data.mask = ccd_data.data > 10 ccd_data.uncertainty = StdDevUncertainty(ccd_data.data * 10) filename = tmpdir.join('afile.fits').strpath ccd_data.write(filename, hdu_mask='Fun', hdu_uncertainty='NoFun') # Try reading with defaults extension names ccd_after = CCDData.read(filename) assert ccd_after.uncertainty is None assert ccd_after.mask is None # Try reading with custom extension names ccd_after = CCDData.read(filename, hdu_mask='Fun', hdu_uncertainty='NoFun') assert ccd_after.uncertainty is not None assert ccd_after.mask is not None np.testing.assert_array_equal(ccd_data.mask, ccd_after.mask) np.testing.assert_array_equal(ccd_data.uncertainty.array, ccd_after.uncertainty.array) def test_read_old_style_multiextensionfits(tmpdir): # Regression test for https://github.com/astropy/ccdproc/issues/664 # # Prior to astropy 3.1 there was no uncertainty type saved # in the multiextension fits files generated by CCDData # because the uncertainty had to be StandardDevUncertainty. # # Current version should be able to read those in. # size = 4 # Value of the variables below are not important to the test. data = np.zeros([size, size]) mask = data > 0.9 uncert = np.sqrt(data) ccd = CCDData(data=data, mask=mask, uncertainty=uncert, unit='adu') # We'll create the file manually to ensure we have the # right extension names and no uncertainty type. hdulist = ccd.to_hdu() del hdulist[2].header['UTYPE'] file_name = tmpdir.join('old_ccddata_mef.fits').strpath hdulist.writeto(file_name) ccd = CCDData.read(file_name) assert isinstance(ccd.uncertainty, StdDevUncertainty) def test_wcs(): ccd_data = create_ccd_data() wcs = WCS(naxis=2) ccd_data.wcs = wcs assert ccd_data.wcs is wcs def test_recognized_fits_formats_for_read_write(tmpdir): # These are the extensions that are supposed to be supported. ccd_data = create_ccd_data() supported_extensions = ['fit', 'fits', 'fts'] for ext in supported_extensions: path = tmpdir.join(f"test.{ext}") ccd_data.write(path.strpath) from_disk = CCDData.read(path.strpath) assert (ccd_data.data == from_disk.data).all() def test_stddevuncertainty_compat_descriptor_no_parent(): with pytest.raises(MissingDataAssociationException): StdDevUncertainty(np.ones((10, 10))).parent_nddata def test_stddevuncertainty_compat_descriptor_no_weakref(): # TODO: Remove this test if astropy 1.0 isn't supported anymore # This test might create a Memoryleak on purpose, so the last lines after # the assert are IMPORTANT cleanup. ccd = CCDData(np.ones((10, 10)), unit='') uncert = StdDevUncertainty(np.ones((10, 10))) uncert._parent_nddata = ccd assert uncert.parent_nddata is ccd uncert._parent_nddata = None # https://github.com/astropy/astropy/issues/7595 def test_read_returns_image(tmpdir): # Test if CCData.read returns a image when reading a fits file containing # a table and image, in that order. tbl = Table(np.ones(10).reshape(5, 2)) img = np.ones((5, 5)) hdul = fits.HDUList(hdus=[fits.PrimaryHDU(), fits.TableHDU(tbl.as_array()), fits.ImageHDU(img)]) filename = tmpdir.join('table_image.fits').strpath hdul.writeto(filename) ccd = CCDData.read(filename, unit='adu') # Expecting to get (5, 5), the size of the image assert ccd.data.shape == (5, 5) # https://github.com/astropy/astropy/issues/9664 def test_sliced_ccdata_to_hdu(): wcs = WCS(naxis=2) wcs.wcs.crpix = 10, 10 ccd = CCDData(np.ones((10, 10)), wcs=wcs, unit='pixel') trimmed = ccd[2:-2, 2:-2] hdul = trimmed.to_hdu() assert isinstance(hdul, fits.HDUList) assert hdul[0].header['CRPIX1'] == 8 assert hdul[0].header['CRPIX2'] == 8
c1995c21d244f3eccad169577c1fe31b5fbb30aff4f5280dbe1be7fbbde9ef7d
# Licensed under a 3-clause BSD style license - see LICENSE.rst # Tests of NDDataBase from astropy.nddata.nddata_base import NDDataBase class MinimalSubclass(NDDataBase): def __init__(self): super().__init__() @property def data(self): return None @property def mask(self): return super().mask @property def unit(self): return super().unit @property def wcs(self): return super().wcs @property def meta(self): return super().meta @property def uncertainty(self): return super().uncertainty def test_nddata_base_subclass(): a = MinimalSubclass() assert a.meta is None assert a.data is None assert a.mask is None assert a.unit is None assert a.wcs is None assert a.uncertainty is None
06f218eb55d052cc7dfadf6e7738d7a2622cd5cbd774637d4256f9041541ad49
# Licensed under a 3-clause BSD style license - see LICENSE.rst from packaging.version import Version import pytest import numpy as np from numpy.testing import assert_allclose, assert_array_equal from astropy.tests.helper import assert_quantity_allclose from astropy.nddata import (extract_array, add_array, subpixel_indices, overlap_slices, NoOverlapError, PartialOverlapError, Cutout2D) from astropy.wcs import WCS, Sip from astropy.wcs.utils import proj_plane_pixel_area from astropy.coordinates import SkyCoord from astropy import units as u from astropy.nddata import CCDData test_positions = [(10.52, 3.12), (5.62, 12.97), (31.33, 31.77), (0.46, 0.94), (20.45, 12.12), (42.24, 24.42)] test_position_indices = [(0, 3), (0, 2), (4, 1), (4, 2), (4, 3), (3, 4)] test_slices = [slice(10.52, 3.12), slice(5.62, 12.97), slice(31.33, 31.77), slice(0.46, 0.94), slice(20.45, 12.12), slice(42.24, 24.42)] subsampling = 5 test_pos_bad = [(-1, -4), (-2, 0), (6, 2), (6, 6)] test_nonfinite_positions = [(np.nan, np.nan), (np.inf, np.inf), (1, np.nan), (np.nan, 2), (2, -np.inf), (-np.inf, 3)] def test_slices_different_dim(): '''Overlap from arrays with different number of dim is undefined.''' with pytest.raises(ValueError) as e: overlap_slices((4, 5, 6), (1, 2), (0, 0)) assert "the same number of dimensions" in str(e.value) def test_slices_pos_different_dim(): '''Position must have same dim as arrays.''' with pytest.raises(ValueError) as e: overlap_slices((4, 5), (1, 2), (0, 0, 3)) assert "the same number of dimensions" in str(e.value) @pytest.mark.parametrize('pos', test_pos_bad) def test_slices_no_overlap(pos): '''If there is no overlap between arrays, an error should be raised.''' with pytest.raises(NoOverlapError): overlap_slices((5, 5), (2, 2), pos) def test_slices_partial_overlap(): '''Compute a slice for partially overlapping arrays.''' temp = overlap_slices((5,), (3,), (0,)) assert temp == ((slice(0, 2, None),), (slice(1, 3, None),)) temp = overlap_slices((5,), (3,), (0,), mode='partial') assert temp == ((slice(0, 2, None),), (slice(1, 3, None),)) for pos in [0, 4]: with pytest.raises(PartialOverlapError) as e: temp = overlap_slices((5,), (3,), (pos,), mode='strict') assert 'Arrays overlap only partially.' in str(e.value) def test_slices_edges(): """ Test overlap_slices when extracting along edges. """ slc_lg, slc_sm = overlap_slices((10, 10), (3, 3), (1, 1), mode='strict') assert slc_lg[0].start == slc_lg[1].start == 0 assert slc_lg[0].stop == slc_lg[1].stop == 3 assert slc_sm[0].start == slc_sm[1].start == 0 assert slc_sm[0].stop == slc_sm[1].stop == 3 slc_lg, slc_sm = overlap_slices((10, 10), (3, 3), (8, 8), mode='strict') assert slc_lg[0].start == slc_lg[1].start == 7 assert slc_lg[0].stop == slc_lg[1].stop == 10 assert slc_sm[0].start == slc_sm[1].start == 0 assert slc_sm[0].stop == slc_sm[1].stop == 3 # test (0, 0) shape slc_lg, slc_sm = overlap_slices((10, 10), (0, 0), (0, 0)) assert slc_lg[0].start == slc_lg[0].stop == 0 assert slc_lg[1].start == slc_lg[1].stop == 0 assert slc_sm[0].start == slc_sm[0].stop == 0 assert slc_sm[1].start == slc_sm[1].stop == 0 slc_lg, slc_sm = overlap_slices((10, 10), (0, 0), (5, 5)) assert slc_lg[0].start == slc_lg[0].stop == 5 assert slc_lg[1].start == slc_lg[1].stop == 5 assert slc_sm[0].start == slc_sm[0].stop == 0 assert slc_sm[1].start == slc_sm[1].stop == 0 def test_slices_overlap_wrong_mode(): '''Call overlap_slices with non-existing mode.''' with pytest.raises(ValueError) as e: overlap_slices((5,), (3,), (0,), mode='full') assert "Mode can be only" in str(e.value) @pytest.mark.parametrize('position', test_nonfinite_positions) def test_slices_nonfinite_position(position): """ A ValueError should be raised if position contains a non-finite value. """ with pytest.raises(ValueError): overlap_slices((7, 7), (3, 3), position) def test_extract_array_even_shape_rounding(): """ Test overlap_slices (via extract_array) for rounding with an even-shaped extraction. """ data = np.arange(10) shape = (2,) positions_expected = [(1.49, (1, 2)), (1.5, (1, 2)), (1.501, (1, 2)), (1.99, (1, 2)), (2.0, (1, 2)), (2.01, (2, 3)), (2.49, (2, 3)), (2.5, (2, 3)), (2.501, (2, 3)), (2.99, (2, 3)), (3.0, (2, 3)), (3.01, (3, 4))] for pos, exp in positions_expected: out = extract_array(data, shape, (pos, ), mode='partial') assert_array_equal(out, exp) # test negative positions positions = (-0.99, -0.51, -0.5, -0.49, -0.01, 0) exp1 = (-99, 0) exp2 = (0, 1) expected = [exp1, ] * 6 + [exp2, ] for pos, exp in zip(positions, expected): out = extract_array(data, shape, (pos, ), mode='partial', fill_value=-99) assert_array_equal(out, exp) def test_extract_array_odd_shape_rounding(): """ Test overlap_slices (via extract_array) for rounding with an even-shaped extraction. """ data = np.arange(10) shape = (3,) positions_expected = [(1.49, (0, 1, 2)), (1.5, (0, 1, 2)), (1.501, (1, 2, 3)), (1.99, (1, 2, 3)), (2.0, (1, 2, 3)), (2.01, (1, 2, 3)), (2.49, (1, 2, 3)), (2.5, (1, 2, 3)), (2.501, (2, 3, 4)), (2.99, (2, 3, 4)), (3.0, (2, 3, 4)), (3.01, (2, 3, 4))] for pos, exp in positions_expected: out = extract_array(data, shape, (pos, ), mode='partial') assert_array_equal(out, exp) # test negative positions positions = (-0.99, -0.51, -0.5, -0.49, -0.01, 0) exp1 = (-99, -99, 0) exp2 = (-99, 0, 1) expected = [exp1, ] * 3 + [exp2, ] * 4 for pos, exp in zip(positions, expected): out = extract_array(data, shape, (pos, ), mode='partial', fill_value=-99) assert_array_equal(out, exp) def test_extract_array_wrong_mode(): '''Call extract_array with non-existing mode.''' with pytest.raises(ValueError) as e: extract_array(np.arange(4), (2, ), (0, ), mode='full') assert "Valid modes are 'partial', 'trim', and 'strict'." == str(e.value) def test_extract_array_1d_even(): '''Extract 1 d arrays. All dimensions are treated the same, so we can test in 1 dim. ''' assert np.all(extract_array(np.arange(4), (2, ), (0, ), fill_value=-99) == np.array([-99, 0])) for i in [1, 2, 3]: assert np.all(extract_array(np.arange(4), (2, ), (i, )) == np.array([i - 1, i])) assert np.all(extract_array(np.arange(4.), (2, ), (4, ), fill_value=np.inf) == np.array([3, np.inf])) def test_extract_array_1d_odd(): '''Extract 1 d arrays. All dimensions are treated the same, so we can test in 1 dim. The first few lines test the most error-prone part: Extraction of an array on the boundaries. Additional tests (e.g. dtype of return array) are done for the last case only. ''' assert np.all(extract_array(np.arange(4), (3,), (-1, ), fill_value=-99) == np.array([-99, -99, 0])) assert np.all(extract_array(np.arange(4), (3,), (0, ), fill_value=-99) == np.array([-99, 0, 1])) for i in [1, 2]: assert np.all(extract_array(np.arange(4), (3,), (i, )) == np.array([i-1, i, i+1])) assert np.all(extract_array(np.arange(4), (3,), (3, ), fill_value=-99) == np.array([2, 3, -99])) arrayin = np.arange(4.) extracted = extract_array(arrayin, (3,), (4, )) assert extracted[0] == 3 assert np.isnan(extracted[1]) # since I cannot use `==` to test for nan assert extracted.dtype == arrayin.dtype def test_extract_array_1d(): """In 1d, shape can be int instead of tuple""" assert np.all(extract_array(np.arange(4), 3, (-1, ), fill_value=-99) == np.array([-99, -99, 0])) assert np.all(extract_array(np.arange(4), 3, -1, fill_value=-99) == np.array([-99, -99, 0])) def test_extract_Array_float(): """integer is at bin center""" for a in np.arange(2.51, 3.49, 0.1): assert np.all(extract_array(np.arange(5), 3, a) == np.array([2, 3, 4])) def test_extract_array_1d_trim(): '''Extract 1 d arrays. All dimensions are treated the same, so we can test in 1 dim. ''' assert np.all(extract_array(np.arange(4), (2, ), (0, ), mode='trim') == np.array([0])) for i in [1, 2, 3]: assert np.all(extract_array(np.arange(4), (2, ), (i, ), mode='trim') == np.array([i - 1, i])) assert np.all(extract_array(np.arange(4.), (2, ), (4, ), mode='trim') == np.array([3])) @pytest.mark.parametrize('mode', ['partial', 'trim', 'strict']) def test_extract_array_easy(mode): """ Test extract_array utility function. Test by extracting an array of ones out of an array of zeros. """ large_test_array = np.zeros((11, 11)) small_test_array = np.ones((5, 5)) large_test_array[3:8, 3:8] = small_test_array extracted_array = extract_array(large_test_array, (5, 5), (5, 5), mode=mode) assert np.all(extracted_array == small_test_array) def test_extract_array_return_pos(): '''Check that the return position is calculated correctly. The result will differ by mode. All test here are done in 1d because it's easier to construct correct test cases. ''' large_test_array = np.arange(5, dtype=float) for i in np.arange(-1, 6): extracted, new_pos = extract_array(large_test_array, 3, i, mode='partial', return_position=True) assert new_pos == (1, ) # Now check an array with an even number for i, expected in zip([1.49, 1.51, 3], [0.49, 0.51, 1]): extracted, new_pos = extract_array(large_test_array, (2,), (i,), mode='strict', return_position=True) assert new_pos == (expected, ) # For mode='trim' the answer actually depends for i, expected in zip(np.arange(-1, 6), (-1, 0, 1, 1, 1, 1, 1)): extracted, new_pos = extract_array(large_test_array, (3,), (i,), mode='trim', return_position=True) assert new_pos == (expected, ) def test_extract_array_nan_fillvalue(): if Version(np.__version__) >= Version('1.20'): msg = 'fill_value cannot be set to np.nan if the input array has' with pytest.raises(ValueError, match=msg): extract_array(np.ones((10, 10), dtype=int), (5, 5), (1, 1), fill_value=np.nan) def test_add_array_odd_shape(): """ Test add_array utility function. Test by adding an array of ones out of an array of zeros. """ large_test_array = np.zeros((11, 11)) small_test_array = np.ones((5, 5)) large_test_array_ref = large_test_array.copy() large_test_array_ref[3:8, 3:8] += small_test_array added_array = add_array(large_test_array, small_test_array, (5, 5)) assert np.all(added_array == large_test_array_ref) def test_add_array_even_shape(): """ Test add_array_2D utility function. Test by adding an array of ones out of an array of zeros. """ large_test_array = np.zeros((11, 11)) small_test_array = np.ones((4, 4)) large_test_array_ref = large_test_array.copy() large_test_array_ref[0:2, 0:2] += small_test_array[2:4, 2:4] added_array = add_array(large_test_array, small_test_array, (0, 0)) assert np.all(added_array == large_test_array_ref) def test_add_array_equal_shape(): """ Test add_array_2D utility function. Test by adding an array of ones out of an array of zeros. """ large_test_array = np.zeros((11, 11)) small_test_array = np.ones((11, 11)) large_test_array_ref = large_test_array.copy() large_test_array_ref += small_test_array added_array = add_array(large_test_array, small_test_array, (5, 5)) assert np.all(added_array == large_test_array_ref) @pytest.mark.parametrize(('position', 'subpixel_index'), zip(test_positions, test_position_indices)) def test_subpixel_indices(position, subpixel_index): """ Test subpixel_indices utility function. Test by asserting that the function returns correct results for given test values. """ assert np.all(subpixel_indices(position, subsampling) == subpixel_index) class TestCutout2D: def setup_class(self): self.data = np.arange(20.).reshape(5, 4) self.position = SkyCoord('13h11m29.96s -01d19m18.7s', frame='icrs') wcs = WCS(naxis=2) rho = np.pi / 3. scale = 0.05 / 3600. wcs.wcs.cd = [[scale*np.cos(rho), -scale*np.sin(rho)], [scale*np.sin(rho), scale*np.cos(rho)]] wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN'] wcs.wcs.crval = [self.position.ra.to_value(u.deg), self.position.dec.to_value(u.deg)] wcs.wcs.crpix = [3, 3] self.wcs = wcs # add SIP sipwcs = wcs.deepcopy() sipwcs.wcs.ctype = ['RA---TAN-SIP', 'DEC--TAN-SIP'] a = np.array( [[0, 0, 5.33092692e-08, 3.73753773e-11, -2.02111473e-13], [0, 2.44084308e-05, 2.81394789e-11, 5.17856895e-13, 0.0], [-2.41334657e-07, 1.29289255e-10, 2.35753629e-14, 0.0, 0.0], [-2.37162007e-10, 5.43714947e-13, 0.0, 0.0, 0.0], [-2.81029767e-13, 0.0, 0.0, 0.0, 0.0]] ) b = np.array( [[0, 0, 2.99270374e-05, -2.38136074e-10, 7.23205168e-13], [0, -1.71073858e-07, 6.31243431e-11, -5.16744347e-14, 0.0], [6.95458963e-06, -3.08278961e-10, -1.75800917e-13, 0.0, 0.0], [3.51974159e-11, 5.60993016e-14, 0.0, 0.0, 0.0], [-5.92438525e-13, 0.0, 0.0, 0.0, 0.0]] ) sipwcs.sip = Sip(a, b, None, None, wcs.wcs.crpix) sipwcs.wcs.set() self.sipwcs = sipwcs def test_cutout(self): sizes = [3, 3*u.pixel, (3, 3), (3*u.pixel, 3*u.pix), (3., 3*u.pixel), (2.9, 3.3)] for size in sizes: position = (2.1, 1.9) c = Cutout2D(self.data, position, size) assert c.data.shape == (3, 3) assert c.data[1, 1] == 10 assert c.origin_original == (1, 1) assert c.origin_cutout == (0, 0) assert c.input_position_original == position assert_allclose(c.input_position_cutout, (1.1, 0.9)) assert c.position_original == (2., 2.) assert c.position_cutout == (1., 1.) assert c.center_original == (2., 2.) assert c.center_cutout == (1., 1.) assert c.bbox_original == ((1, 3), (1, 3)) assert c.bbox_cutout == ((0, 2), (0, 2)) assert c.slices_original == (slice(1, 4), slice(1, 4)) assert c.slices_cutout == (slice(0, 3), slice(0, 3)) def test_size_length(self): with pytest.raises(ValueError): Cutout2D(self.data, (2, 2), (1, 1, 1)) def test_size_units(self): for size in [3 * u.cm, (3, 3 * u.K)]: with pytest.raises(ValueError): Cutout2D(self.data, (2, 2), size) def test_size_pixel(self): """ Check size in derived pixel units. """ size = 0.3*u.arcsec / (0.1*u.arcsec/u.pixel) c = Cutout2D(self.data, (2, 2), size) assert c.data.shape == (3, 3) assert c.data[0, 0] == 5 assert c.slices_original == (slice(1, 4), slice(1, 4)) assert c.slices_cutout == (slice(0, 3), slice(0, 3)) def test_size_angle(self): c = Cutout2D(self.data, (2, 2), (0.1*u.arcsec), wcs=self.wcs) assert c.data.shape == (2, 2) assert c.data[0, 0] == 5 assert c.slices_original == (slice(1, 3), slice(1, 3)) assert c.slices_cutout == (slice(0, 2), slice(0, 2)) def test_size_angle_without_wcs(self): with pytest.raises(ValueError): Cutout2D(self.data, (2, 2), (3, 3 * u.arcsec)) def test_cutout_trim_overlap(self): c = Cutout2D(self.data, (0, 0), (3, 3), mode='trim') assert c.data.shape == (2, 2) assert c.data[0, 0] == 0 assert c.slices_original == (slice(0, 2), slice(0, 2)) assert c.slices_cutout == (slice(0, 2), slice(0, 2)) def test_cutout_partial_overlap(self): c = Cutout2D(self.data, (0, 0), (3, 3), mode='partial') assert c.data.shape == (3, 3) assert c.data[1, 1] == 0 assert c.slices_original == (slice(0, 2), slice(0, 2)) assert c.slices_cutout == (slice(1, 3), slice(1, 3)) def test_cutout_partial_overlap_fill_value(self): fill_value = -99 c = Cutout2D(self.data, (0, 0), (3, 3), mode='partial', fill_value=fill_value) assert c.data.shape == (3, 3) assert c.data[1, 1] == 0 assert c.data[0, 0] == fill_value def test_copy(self): data = np.copy(self.data) c = Cutout2D(data, (2, 3), (3, 3)) xy = (0, 0) value = 100. c.data[xy] = value xy_orig = c.to_original_position(xy) yx = xy_orig[::-1] assert data[yx] == value data = np.copy(self.data) c2 = Cutout2D(self.data, (2, 3), (3, 3), copy=True) c2.data[xy] = value assert data[yx] != value def test_to_from_large(self): position = (2, 2) c = Cutout2D(self.data, position, (3, 3)) xy = (0, 0) result = c.to_cutout_position(c.to_original_position(xy)) assert_allclose(result, xy) def test_skycoord_without_wcs(self): with pytest.raises(ValueError): Cutout2D(self.data, self.position, (3, 3)) def test_skycoord(self): c = Cutout2D(self.data, self.position, (3, 3), wcs=self.wcs) skycoord_original = self.position.from_pixel(c.center_original[1], c.center_original[0], self.wcs) skycoord_cutout = self.position.from_pixel(c.center_cutout[1], c.center_cutout[0], c.wcs) assert_quantity_allclose(skycoord_original.ra, skycoord_cutout.ra) assert_quantity_allclose(skycoord_original.dec, skycoord_cutout.dec) def test_skycoord_partial(self): c = Cutout2D(self.data, self.position, (3, 3), wcs=self.wcs, mode='partial') skycoord_original = self.position.from_pixel(c.center_original[1], c.center_original[0], self.wcs) skycoord_cutout = self.position.from_pixel(c.center_cutout[1], c.center_cutout[0], c.wcs) assert_quantity_allclose(skycoord_original.ra, skycoord_cutout.ra) assert_quantity_allclose(skycoord_original.dec, skycoord_cutout.dec) def test_naxis_update(self): xsize = 2 ysize = 3 c = Cutout2D(self.data, self.position, (ysize, xsize), wcs=self.wcs) assert c.wcs.array_shape == (ysize, xsize) def test_crpix_maps_to_crval(self): w = Cutout2D(self.data, (0, 0), (3, 3), wcs=self.sipwcs, mode='partial').wcs pscale = np.sqrt(proj_plane_pixel_area(w)) assert_allclose( w.wcs_pix2world(*w.wcs.crpix, 1), w.wcs.crval, rtol=0.0, atol=1e-6 * pscale ) assert_allclose( w.all_pix2world(*w.wcs.crpix, 1), w.wcs.crval, rtol=0.0, atol=1e-6 * pscale ) def test_cutout_with_nddata_as_input(self): # This is essentially a copy/paste of test_skycoord with the # input a ccd with wcs attribute instead of passing the # wcs separately. ccd = CCDData(data=self.data, wcs=self.wcs, unit='adu') c = Cutout2D(ccd, self.position, (3, 3)) skycoord_original = self.position.from_pixel(c.center_original[1], c.center_original[0], self.wcs) skycoord_cutout = self.position.from_pixel(c.center_cutout[1], c.center_cutout[0], c.wcs) assert_quantity_allclose(skycoord_original.ra, skycoord_cutout.ra) assert_quantity_allclose(skycoord_original.dec, skycoord_cutout.dec)
830d221ff201391b67b10476ba598deffe207907e677ae0be4fc35dd96c4450f
""" A module containing unit tests for the `bitmask` module. Licensed under a 3-clause BSD style license - see LICENSE.rst """ import warnings import numpy as np import pytest from astropy.nddata import bitmask MAX_INT_TYPE = np.maximum_sctype(np.int_) MAX_UINT_TYPE = np.maximum_sctype(np.uint) MAX_UINT_FLAG = np.left_shift( MAX_UINT_TYPE(1), MAX_UINT_TYPE(np.iinfo(MAX_UINT_TYPE).bits - 1) ) MAX_INT_FLAG = np.left_shift( MAX_INT_TYPE(1), MAX_INT_TYPE(np.iinfo(MAX_INT_TYPE).bits - 2) ) SUPER_LARGE_FLAG = 1 << np.iinfo(MAX_UINT_TYPE).bits EXTREME_TEST_DATA = np.array([ 0, 1, 1 + 1 << 2, MAX_INT_FLAG, ~0, MAX_INT_TYPE(MAX_UINT_FLAG), 1 + MAX_INT_TYPE(MAX_UINT_FLAG) ], dtype=MAX_INT_TYPE) @pytest.mark.parametrize('flag', [0, -1]) def test_nonpositive_not_a_bit_flag(flag): assert not bitmask._is_bit_flag(n=flag) @pytest.mark.parametrize('flag', [ 1, MAX_UINT_FLAG, int(MAX_UINT_FLAG), SUPER_LARGE_FLAG ]) def test_is_bit_flag(flag): assert bitmask._is_bit_flag(n=flag) @pytest.mark.parametrize('number', [0, 1, MAX_UINT_FLAG, SUPER_LARGE_FLAG]) def test_is_int(number): assert bitmask._is_int(number) @pytest.mark.parametrize('number', ['1', True, 1.0]) def test_nonint_is_not_an_int(number): assert not bitmask._is_int(number) @pytest.mark.parametrize('flag,flip,expected', [ (3, None, 3), (3, True, -4), (3, False, 3), ([1, 2], False, 3), ([1, 2], True, -4) ]) def test_interpret_valid_int_bit_flags(flag, flip, expected): assert( bitmask.interpret_bit_flags(bit_flags=flag, flip_bits=flip) == expected ) @pytest.mark.parametrize('flag', [None, ' ', 'None', 'Indef']) def test_interpret_none_bit_flags_as_None(flag): assert bitmask.interpret_bit_flags(bit_flags=flag) is None @pytest.mark.parametrize('flag,expected', [ ('1', 1), ('~-1', ~(-1)), ('~1', ~1), ('1,2', 3), ('1|2', 3), ('1+2', 3), ('(1,2)', 3), ('(1+2)', 3), ('~1,2', ~3), ('~1+2', ~3), ('~(1,2)', ~3), ('~(1+2)', ~3) ]) def test_interpret_valid_str_bit_flags(flag, expected): assert( bitmask.interpret_bit_flags(bit_flags=flag) == expected ) @pytest.mark.parametrize('flag,expected', [ ('CR', 1), ('~CR', ~1), ('CR|HOT', 3), ('CR,HOT', 3), ('CR+HOT', 3), (['CR', 'HOT'], 3), ('(CR,HOT)', 3), ('(HOT+CR)', 3), ('~HOT,CR', ~3), ('~CR+HOT', ~3), ('~(HOT,CR)', ~3), ('~(HOT|CR)', ~3), ('~(CR+HOT)', ~3) ]) def test_interpret_valid_mnemonic_bit_flags(flag, expected): flagmap = bitmask.extend_bit_flag_map('DetectorMap', CR=1, HOT=2) assert( bitmask.interpret_bit_flags(bit_flags=flag, flag_name_map=flagmap) == expected ) @pytest.mark.parametrize('flag,flip', [ (None, True), (' ', True), ('None', True), ('Indef', True), (None, False), (' ', False), ('None', False), ('Indef', False), ('1', True), ('1', False) ]) def test_interpret_None_or_str_and_flip_incompatibility(flag, flip): with pytest.raises(TypeError): bitmask.interpret_bit_flags(bit_flags=flag, flip_bits=flip) @pytest.mark.parametrize('flag', [True, 1.0, [1.0], object]) def test_interpret_wrong_flag_type(flag): with pytest.raises(TypeError): bitmask.interpret_bit_flags(bit_flags=flag) @pytest.mark.parametrize('flag', ['SOMETHING', '1.0,2,3']) def test_interpret_wrong_string_int_format(flag): with pytest.raises(ValueError): bitmask.interpret_bit_flags(bit_flags=flag) def test_interpret_duplicate_flag_warning(): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") assert bitmask.interpret_bit_flags([2, 4, 4]) == 6 assert len(w) assert issubclass(w[-1].category, UserWarning) assert "Duplicate" in str(w[-1].message) @pytest.mark.parametrize('flag', [[1, 2, 3], '1, 2, 3']) def test_interpret_non_flag(flag): with pytest.raises(ValueError): bitmask.interpret_bit_flags(bit_flags=flag) def test_interpret_allow_single_value_str_nonflags(): assert bitmask.interpret_bit_flags(bit_flags=str(3)) == 3 @pytest.mark.parametrize('flag', [ '~', '( )', '(~1,2)', '~(1,2', '1,~2', '1,(2,4)', '1,2+4', '1+4,2', '1|4+2' ]) def test_interpret_bad_str_syntax(flag): with pytest.raises(ValueError): bitmask.interpret_bit_flags(bit_flags=flag) def test_bitfield_must_be_integer_check(): with pytest.raises(TypeError): bitmask.bitfield_to_boolean_mask(1.0, 1) @pytest.mark.parametrize('data,flags,flip,goodval,dtype,ref', [ (EXTREME_TEST_DATA, None, None, True, np.bool_, EXTREME_TEST_DATA.size * [1]), (EXTREME_TEST_DATA, None, None, False, np.bool_, EXTREME_TEST_DATA.size * [0]), (EXTREME_TEST_DATA, [1, MAX_UINT_FLAG], False, True, np.bool_, [1, 1, 0, 0, 0, 1, 1]), (EXTREME_TEST_DATA, None, None, True, np.bool_, EXTREME_TEST_DATA.size * [1]), (EXTREME_TEST_DATA, [1, MAX_UINT_FLAG], False, False, np.bool_, [0, 0, 1, 1, 1, 0, 0]), (EXTREME_TEST_DATA, [1, MAX_UINT_FLAG], True, True, np.int8, [1, 0, 1, 1, 0, 0, 0]) ]) def test_bitfield_to_boolean_mask(data, flags, flip, goodval, dtype, ref): mask = bitmask.bitfield_to_boolean_mask( bitfield=data, ignore_flags=flags, flip_bits=flip, good_mask_value=goodval, dtype=dtype ) assert(mask.dtype == dtype) assert np.all(mask == ref) @pytest.mark.parametrize('flag', [(4, 'flag1'), 8]) def test_bitflag(flag): f = bitmask.BitFlag(flag) if isinstance(flag, tuple): assert f == flag[0] assert f.__doc__ == flag[1] f = bitmask.BitFlag(*flag) assert f == flag[0] assert f.__doc__ == flag[1] else: assert f == flag def test_bitflag_docs2(): with pytest.raises(ValueError): bitmask.BitFlag((1, 'docs1'), 'docs2') @pytest.mark.parametrize('flag', [0, 3]) def test_bitflag_not_pow2(flag): with pytest.raises(bitmask.InvalidBitFlag): bitmask.BitFlag(flag, 'custom flag') @pytest.mark.parametrize('flag', [0.0, True, '1']) def test_bitflag_not_int_flag(flag): with pytest.raises(bitmask.InvalidBitFlag): bitmask.BitFlag((flag, 'custom flag')) @pytest.mark.parametrize('caching', [True, False]) def test_basic_map(monkeypatch, caching): monkeypatch.setattr(bitmask, '_ENABLE_BITFLAG_CACHING', False) class ObservatoryDQMap(bitmask.BitFlagNameMap): _not_a_flag = 1 CR = 1, 'cosmic ray' HOT = 2 DEAD = 4 class DetectorMap(ObservatoryDQMap): __version__ = '1.0' _not_a_flag = 181 READOUT_ERR = 16 assert ObservatoryDQMap.cr == 1 assert ObservatoryDQMap.cr.__doc__ == 'cosmic ray' assert DetectorMap.READOUT_ERR == 16 @pytest.mark.parametrize('caching', [True, False]) def test_extend_map(monkeypatch, caching): monkeypatch.setattr(bitmask, '_ENABLE_BITFLAG_CACHING', caching) class ObservatoryDQMap(bitmask.BitFlagNameMap): CR = 1 HOT = 2 DEAD = 4 DetectorMap = bitmask.extend_bit_flag_map( 'DetectorMap', ObservatoryDQMap, __version__='1.0', DEAD=4, READOUT_ERR=16 ) assert DetectorMap.CR == 1 assert DetectorMap.readout_err == 16 @pytest.mark.parametrize('caching', [True, False]) def test_extend_map_redefine_flag(monkeypatch, caching): monkeypatch.setattr(bitmask, '_ENABLE_BITFLAG_CACHING', caching) class ObservatoryDQMap(bitmask.BitFlagNameMap): CR = 1 HOT = 2 DEAD = 4 with pytest.raises(AttributeError): bitmask.extend_bit_flag_map( 'DetectorMap', ObservatoryDQMap, __version__='1.0', DEAD=32 ) with pytest.raises(AttributeError): bitmask.extend_bit_flag_map( 'DetectorMap', ObservatoryDQMap, __version__='1.0', DEAD=32, dead=64 ) @pytest.mark.parametrize('caching', [True, False]) def test_map_redefine_flag(monkeypatch, caching): monkeypatch.setattr(bitmask, '_ENABLE_BITFLAG_CACHING', caching) class ObservatoryDQMap(bitmask.BitFlagNameMap): _not_a_flag = 8 CR = 1 HOT = 2 DEAD = 4 with pytest.raises(AttributeError): class DetectorMap1(ObservatoryDQMap): __version__ = '1.0' CR = 16 with pytest.raises(AttributeError): class DetectorMap2(ObservatoryDQMap): SHADE = 8 _FROZEN = 16 DetectorMap2.novel = 32 with pytest.raises(AttributeError): bitmask.extend_bit_flag_map( 'DetectorMap', ObservatoryDQMap, READOUT_ERR=16, SHADE=32, readout_err=128 ) def test_map_cant_modify_version(): class ObservatoryDQMap(bitmask.BitFlagNameMap): __version__ = '1.2.3' CR = 1 assert ObservatoryDQMap.__version__ == '1.2.3' assert ObservatoryDQMap.CR == 1 with pytest.raises(AttributeError): ObservatoryDQMap.__version__ = '3.2.1' @pytest.mark.parametrize('flag', [0, 3]) def test_map_not_bit_flag(flag): with pytest.raises(ValueError): bitmask.extend_bit_flag_map('DetectorMap', DEAD=flag) with pytest.raises(ValueError): class DetectorMap(bitmask.BitFlagNameMap): DEAD=flag @pytest.mark.parametrize('flag', [0.0, True, '1']) def test_map_not_int_flag(flag): with pytest.raises(bitmask.InvalidBitFlag): bitmask.extend_bit_flag_map('DetectorMap', DEAD=flag) with pytest.raises(bitmask.InvalidBitFlag): class ObservatoryDQMap(bitmask.BitFlagNameMap): CR = flag def test_map_access_undefined_flag(): DetectorMap = bitmask.extend_bit_flag_map('DetectorMap', DEAD=1) with pytest.raises(AttributeError): DetectorMap.DEAD1 with pytest.raises(AttributeError): DetectorMap['DEAD1'] def test_map_delete_flag(): DetectorMap = bitmask.extend_bit_flag_map('DetectorMap', DEAD=1) with pytest.raises(AttributeError): del DetectorMap.DEAD1 with pytest.raises(AttributeError): del DetectorMap['DEAD1'] def test_map_repr(): DetectorMap = bitmask.extend_bit_flag_map('DetectorMap', DEAD=1) assert repr(DetectorMap) == "<BitFlagNameMap 'DetectorMap'>" def test_map_add_flags(): map1 = bitmask.extend_bit_flag_map('DetectorMap', CR=1) map2 = map1 + {'HOT': 2, 'DEAD': (4, 'a really dead pixel')} assert map2.CR == 1 assert map2.HOT == 2 assert map2.DEAD.__doc__ == 'a really dead pixel' assert map2.DEAD == 4 map2 = map1 + [('HOT', 2), ('DEAD', 4)] assert map2.CR == 1 assert map2.HOT == 2 map2 = map1 + ('HOT', 2) assert map2.CR == 1 assert map2.HOT == 2
d3526dbc813d267b630f8b48b4546100c90eb35d8d44dc3698b890aefaa78587
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np import pytest from astropy.nddata import reshape_as_blocks, block_reduce, block_replicate class TestReshapeAsBlocks: def test_1d(self): data = np.arange(16) reshaped = reshape_as_blocks(data, 2) assert reshaped.shape == (8, 2) reshaped = reshape_as_blocks(data, 4) assert reshaped.shape == (4, 4) reshaped = reshape_as_blocks(data, 8) assert reshaped.shape == (2, 8) def test_2d(self): data = np.arange(16).reshape(4, 4) reshaped = reshape_as_blocks(data, (2, 2)) assert reshaped.shape == (2, 2, 2, 2) data = np.arange(64).reshape(8, 8) reshaped = reshape_as_blocks(data, (2, 2)) assert reshaped.shape == (4, 4, 2, 2) reshaped = reshape_as_blocks(data, (4, 4)) assert reshaped.shape == (2, 2, 4, 4) def test_3d(self): data = np.arange(64).reshape(4, 4, 4) reshaped = reshape_as_blocks(data, (2, 2, 2)) assert reshaped.shape == (2, 2, 2, 2, 2, 2) data = np.arange(2*3*4).reshape(2, 3, 4) reshaped = reshape_as_blocks(data, (2, 1, 2)) assert reshaped.shape == (1, 3, 2, 2, 1, 2) def test_view(self): data = np.arange(16).reshape(4, 4) reshaped = reshape_as_blocks(data, (2, 2)) data[0, 0] = 100 assert reshaped[0, 0, 0, 0] == 100 def test_invalid_block_dim(self): data = np.arange(64).reshape(4, 4, 4) match = ('block_size must be a scalar or have the same ' 'length as the number of data dimensions') with pytest.raises(ValueError, match=match): reshape_as_blocks(data, (2, 2)) def test_invalid_block_size(self): data = np.arange(16).reshape(4, 4) match = ('Each dimension of block_size must divide evenly ' 'into the corresponding dimension of data') with pytest.raises(ValueError, match=match): reshape_as_blocks(data, (2, 3)) def test_invalid_block_value(self): data = np.arange(16).reshape(4, 4) match = 'block_size elements must be integers' with pytest.raises(ValueError, match=match): reshape_as_blocks(data, (2.1, 2)) match = 'block_size elements must be strictly positive' with pytest.raises(ValueError, match=match): reshape_as_blocks(data, (-1, 0)) class TestBlockReduce: def test_1d(self): """Test 1D array.""" data = np.arange(4) expected = np.array([1, 5]) result = block_reduce(data, 2) assert np.all(result == expected) def test_1d_mean(self): """Test 1D array with func=np.mean.""" data = np.arange(4) block_size = 2. expected = block_reduce(data, block_size, func=np.sum) / block_size result_mean = block_reduce(data, block_size, func=np.mean) assert np.all(result_mean == expected) def test_2d(self): """Test 2D array.""" data = np.arange(4).reshape(2, 2) expected = np.array([[6]]) result = block_reduce(data, 2) assert np.all(result == expected) def test_2d_mean(self): """Test 2D array with func=np.mean.""" data = np.arange(4).reshape(2, 2) block_size = 2. expected = (block_reduce(data, block_size, func=np.sum) / block_size**2) result = block_reduce(data, block_size, func=np.mean) assert np.all(result == expected) def test_2d_trim(self): """ Test trimming of 2D array when size is not perfectly divisible by block_size. """ data1 = np.arange(15).reshape(5, 3) result1 = block_reduce(data1, 2) data2 = data1[0:4, 0:2] result2 = block_reduce(data2, 2) assert np.all(result1 == result2) def test_block_size_broadcasting(self): """Test scalar block_size broadcasting.""" data = np.arange(16).reshape(4, 4) result1 = block_reduce(data, 2) result2 = block_reduce(data, (2, 2)) assert np.all(result1 == result2) def test_block_size_len(self): """Test block_size length.""" data = np.ones((2, 2)) with pytest.raises(ValueError): block_reduce(data, (2, 2, 2)) class TestBlockReplicate: def test_1d(self): """Test 1D array.""" data = np.arange(2) expected = np.array([0, 0, 0.5, 0.5]) result = block_replicate(data, 2) assert np.all(result == expected) def test_1d_conserve_sum(self): """Test 1D array with conserve_sum=False.""" data = np.arange(2) block_size = 2. expected = block_replicate(data, block_size) * block_size result = block_replicate(data, block_size, conserve_sum=False) assert np.all(result == expected) def test_2d(self): """Test 2D array.""" data = np.arange(2).reshape(2, 1) expected = np.array([[0, 0], [0, 0], [0.25, 0.25], [0.25, 0.25]]) result = block_replicate(data, 2) assert np.all(result == expected) def test_2d_conserve_sum(self): """Test 2D array with conserve_sum=False.""" data = np.arange(6).reshape(2, 3) block_size = 2. expected = block_replicate(data, block_size) * block_size**2 result = block_replicate(data, block_size, conserve_sum=False) assert np.all(result == expected) def test_block_size_broadcasting(self): """Test scalar block_size broadcasting.""" data = np.arange(4).reshape(2, 2) result1 = block_replicate(data, 2) result2 = block_replicate(data, (2, 2)) assert np.all(result1 == result2) def test_block_size_len(self): """Test block_size length.""" data = np.arange(5) with pytest.raises(ValueError): block_replicate(data, (2, 2))
154af441160aadd2bfc29d53434eab1d1edaab7bd781b590b178fa7dd2943c90
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest import numpy as np from astropy.nddata import FlagCollection def test_init(): FlagCollection(shape=(1, 2, 3)) def test_init_noshape(): with pytest.raises(Exception) as exc: FlagCollection() assert exc.value.args[0] == ('FlagCollection should be initialized with ' 'the shape of the data') def test_init_notiterable(): with pytest.raises(Exception) as exc: FlagCollection(shape=1.) assert exc.value.args[0] == ('FlagCollection shape should be ' 'an iterable object') def test_setitem(): f = FlagCollection(shape=(1, 2, 3)) f['a'] = np.ones((1, 2, 3)).astype(float) f['b'] = np.ones((1, 2, 3)).astype(int) f['c'] = np.ones((1, 2, 3)).astype(bool) f['d'] = np.ones((1, 2, 3)).astype(str) @pytest.mark.parametrize(('value'), [1, 1., 'spam', [1, 2, 3], (1., 2., 3.)]) def test_setitem_invalid_type(value): f = FlagCollection(shape=(1, 2, 3)) with pytest.raises(Exception) as exc: f['a'] = value assert exc.value.args[0] == 'flags should be given as a Numpy array' def test_setitem_invalid_shape(): f = FlagCollection(shape=(1, 2, 3)) with pytest.raises(ValueError) as exc: f['a'] = np.ones((3, 2, 1)) assert exc.value.args[0].startswith('flags array shape') assert exc.value.args[0].endswith('does not match data shape (1, 2, 3)')
a77e667b6b5fce344344f418c25c11c84b46303a9edc113aa9e6c57029f28294
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pickle import textwrap from collections import OrderedDict import pytest import numpy as np from numpy.testing import assert_array_equal from astropy.nddata.nddata import NDData from astropy.nddata.nduncertainty import StdDevUncertainty from astropy import units as u from astropy.utils import NumpyRNGContext from astropy.wcs import WCS from astropy.wcs.wcsapi import HighLevelWCSWrapper, SlicedLowLevelWCS, \ BaseHighLevelWCS from .test_nduncertainty import FakeUncertainty from astropy.nddata import _testing as nd_testing class FakeNumpyArray: """ Class that has a few of the attributes of a numpy array. These attributes are checked for by NDData. """ def __init__(self): super().__init__() def shape(self): pass def __getitem__(self): pass def __array__(self): pass @property def dtype(self): return 'fake' class MinimalUncertainty: """ Define the minimum attributes acceptable as an uncertainty object. """ def __init__(self, value): self._uncertainty = value @property def uncertainty_type(self): return "totally and completely fake" class BadNDDataSubclass(NDData): def __init__(self, data, uncertainty=None, mask=None, wcs=None, meta=None, unit=None): self._data = data self._uncertainty = uncertainty self._mask = mask self._wcs = wcs self._unit = unit self._meta = meta # Setter tests def test_uncertainty_setter(): nd = NDData([1, 2, 3]) good_uncertainty = MinimalUncertainty(5) nd.uncertainty = good_uncertainty assert nd.uncertainty is good_uncertainty # Check the fake uncertainty (minimal does not work since it has no # parent_nddata attribute from NDUncertainty) nd.uncertainty = FakeUncertainty(5) assert nd.uncertainty.parent_nddata is nd # Check that it works if the uncertainty was set during init nd = NDData(nd) assert isinstance(nd.uncertainty, FakeUncertainty) nd.uncertainty = 10 assert not isinstance(nd.uncertainty, FakeUncertainty) assert nd.uncertainty.array == 10 def test_mask_setter(): # Since it just changes the _mask attribute everything should work nd = NDData([1, 2, 3]) nd.mask = True assert nd.mask nd.mask = False assert not nd.mask # Check that it replaces a mask from init nd = NDData(nd, mask=True) assert nd.mask nd.mask = False assert not nd.mask # Init tests def test_nddata_empty(): with pytest.raises(TypeError): NDData() # empty initializer should fail def test_nddata_init_data_nonarray(): inp = [1, 2, 3] nd = NDData(inp) assert (np.array(inp) == nd.data).all() def test_nddata_init_data_ndarray(): # random floats with NumpyRNGContext(123): nd = NDData(np.random.random((10, 10))) assert nd.data.shape == (10, 10) assert nd.data.size == 100 assert nd.data.dtype == np.dtype(float) # specific integers nd = NDData(np.array([[1, 2, 3], [4, 5, 6]])) assert nd.data.size == 6 assert nd.data.dtype == np.dtype(int) # Tests to ensure that creating a new NDData object copies by *reference*. a = np.ones((10, 10)) nd_ref = NDData(a) a[0, 0] = 0 assert nd_ref.data[0, 0] == 0 # Except we choose copy=True a = np.ones((10, 10)) nd_ref = NDData(a, copy=True) a[0, 0] = 0 assert nd_ref.data[0, 0] != 0 def test_nddata_init_data_maskedarray(): with NumpyRNGContext(456): NDData(np.random.random((10, 10)), mask=np.random.random((10, 10)) > 0.5) # Another test (just copied here) with NumpyRNGContext(12345): a = np.random.randn(100) marr = np.ma.masked_where(a > 0, a) nd = NDData(marr) # check that masks and data match assert_array_equal(nd.mask, marr.mask) assert_array_equal(nd.data, marr.data) # check that they are both by reference marr.mask[10] = ~marr.mask[10] marr.data[11] = 123456789 assert_array_equal(nd.mask, marr.mask) assert_array_equal(nd.data, marr.data) # or not if we choose copy=True nd = NDData(marr, copy=True) marr.mask[10] = ~marr.mask[10] marr.data[11] = 0 assert nd.mask[10] != marr.mask[10] assert nd.data[11] != marr.data[11] @pytest.mark.parametrize('data', [np.array([1, 2, 3]), 5]) def test_nddata_init_data_quantity(data): # Test an array and a scalar because a scalar Quantity does not always # behaves the same way as an array. quantity = data * u.adu ndd = NDData(quantity) assert ndd.unit == quantity.unit assert_array_equal(ndd.data, np.array(quantity.value)) if ndd.data.size > 1: # check that if it is an array it is not copied quantity.value[1] = 100 assert ndd.data[1] == quantity.value[1] # or is copied if we choose copy=True ndd = NDData(quantity, copy=True) quantity.value[1] = 5 assert ndd.data[1] != quantity.value[1] def test_nddata_init_data_masked_quantity(): a = np.array([2, 3]) q = a * u.m m = False mq = np.ma.array(q, mask=m) nd = NDData(mq) assert_array_equal(nd.data, a) # This test failed before the change in nddata init because the masked # arrays data (which in fact was a quantity was directly saved) assert nd.unit == u.m assert not isinstance(nd.data, u.Quantity) np.testing.assert_array_equal(nd.mask, np.array(m)) def test_nddata_init_data_nddata(): nd1 = NDData(np.array([1])) nd2 = NDData(nd1) assert nd2.wcs == nd1.wcs assert nd2.uncertainty == nd1.uncertainty assert nd2.mask == nd1.mask assert nd2.unit == nd1.unit assert nd2.meta == nd1.meta # Check that it is copied by reference nd1 = NDData(np.ones((5, 5))) nd2 = NDData(nd1) assert nd1.data is nd2.data # Check that it is really copied if copy=True nd2 = NDData(nd1, copy=True) nd1.data[2, 3] = 10 assert nd1.data[2, 3] != nd2.data[2, 3] # Now let's see what happens if we have all explicitly set nd1 = NDData(np.array([1]), mask=False, uncertainty=StdDevUncertainty(10), unit=u.s, meta={'dest': 'mordor'}, wcs=WCS(naxis=1)) nd2 = NDData(nd1) assert nd2.data is nd1.data assert nd2.wcs is nd1.wcs assert nd2.uncertainty.array == nd1.uncertainty.array assert nd2.mask == nd1.mask assert nd2.unit == nd1.unit assert nd2.meta == nd1.meta # now what happens if we overwrite them all too nd3 = NDData(nd1, mask=True, uncertainty=StdDevUncertainty(200), unit=u.km, meta={'observer': 'ME'}, wcs=WCS(naxis=1)) assert nd3.data is nd1.data assert nd3.wcs is not nd1.wcs assert nd3.uncertainty.array != nd1.uncertainty.array assert nd3.mask != nd1.mask assert nd3.unit != nd1.unit assert nd3.meta != nd1.meta def test_nddata_init_data_nddata_subclass(): uncert = StdDevUncertainty(3) # There might be some incompatible subclasses of NDData around. bnd = BadNDDataSubclass(False, True, 3, 2, 'gollum', 100) # Before changing the NDData init this would not have raised an error but # would have lead to a compromised nddata instance with pytest.raises(TypeError): NDData(bnd) # but if it has no actual incompatible attributes it passes bnd_good = BadNDDataSubclass(np.array([1, 2]), uncert, 3, HighLevelWCSWrapper(WCS(naxis=1)), {'enemy': 'black knight'}, u.km) nd = NDData(bnd_good) assert nd.unit == bnd_good.unit assert nd.meta == bnd_good.meta assert nd.uncertainty == bnd_good.uncertainty assert nd.mask == bnd_good.mask assert nd.wcs is bnd_good.wcs assert nd.data is bnd_good.data def test_nddata_init_data_fail(): # First one is sliceable but has no shape, so should fail. with pytest.raises(TypeError): NDData({'a': 'dict'}) # This has a shape but is not sliceable class Shape: def __init__(self): self.shape = 5 def __repr__(self): return '7' with pytest.raises(TypeError): NDData(Shape()) def test_nddata_init_data_fakes(): ndd1 = NDData(FakeNumpyArray()) # First make sure that NDData isn't converting its data to a numpy array. assert isinstance(ndd1.data, FakeNumpyArray) # Make a new NDData initialized from an NDData ndd2 = NDData(ndd1) # Check that the data wasn't converted to numpy assert isinstance(ndd2.data, FakeNumpyArray) # Specific parameters def test_param_uncertainty(): u = StdDevUncertainty(array=np.ones((5, 5))) d = NDData(np.ones((5, 5)), uncertainty=u) # Test that the parent_nddata is set. assert d.uncertainty.parent_nddata is d # Test conflicting uncertainties (other NDData) u2 = StdDevUncertainty(array=np.ones((5, 5))*2) d2 = NDData(d, uncertainty=u2) assert d2.uncertainty is u2 assert d2.uncertainty.parent_nddata is d2 def test_param_wcs(): # Since everything is allowed we only need to test something nd = NDData([1], wcs=WCS(naxis=1)) assert nd.wcs is not None # Test conflicting wcs (other NDData) nd2 = NDData(nd, wcs=WCS(naxis=1)) assert nd2.wcs is not None and nd2.wcs is not nd.wcs def test_param_meta(): # everything dict-like is allowed with pytest.raises(TypeError): NDData([1], meta=3) nd = NDData([1, 2, 3], meta={}) assert len(nd.meta) == 0 nd = NDData([1, 2, 3]) assert isinstance(nd.meta, OrderedDict) assert len(nd.meta) == 0 # Test conflicting meta (other NDData) nd2 = NDData(nd, meta={'image': 'sun'}) assert len(nd2.meta) == 1 nd3 = NDData(nd2, meta={'image': 'moon'}) assert len(nd3.meta) == 1 assert nd3.meta['image'] == 'moon' def test_param_mask(): # Since everything is allowed we only need to test something nd = NDData([1], mask=False) assert not nd.mask # Test conflicting mask (other NDData) nd2 = NDData(nd, mask=True) assert nd2.mask # (masked array) nd3 = NDData(np.ma.array([1], mask=False), mask=True) assert nd3.mask # (masked quantity) mq = np.ma.array(np.array([2, 3])*u.m, mask=False) nd4 = NDData(mq, mask=True) assert nd4.mask def test_param_unit(): with pytest.raises(ValueError): NDData(np.ones((5, 5)), unit="NotAValidUnit") NDData([1, 2, 3], unit='meter') # Test conflicting units (quantity as data) q = np.array([1, 2, 3]) * u.m nd = NDData(q, unit='cm') assert nd.unit != q.unit assert nd.unit == u.cm # (masked quantity) mq = np.ma.array(np.array([2, 3])*u.m, mask=False) nd2 = NDData(mq, unit=u.s) assert nd2.unit == u.s # (another NDData as data) nd3 = NDData(nd, unit='km') assert nd3.unit == u.km def test_pickle_nddata_with_uncertainty(): ndd = NDData(np.ones(3), uncertainty=StdDevUncertainty(np.ones(5), unit=u.m), unit=u.m) ndd_dumped = pickle.dumps(ndd) ndd_restored = pickle.loads(ndd_dumped) assert type(ndd_restored.uncertainty) is StdDevUncertainty assert ndd_restored.uncertainty.parent_nddata is ndd_restored assert ndd_restored.uncertainty.unit == u.m def test_pickle_uncertainty_only(): ndd = NDData(np.ones(3), uncertainty=StdDevUncertainty(np.ones(5), unit=u.m), unit=u.m) uncertainty_dumped = pickle.dumps(ndd.uncertainty) uncertainty_restored = pickle.loads(uncertainty_dumped) np.testing.assert_array_equal(ndd.uncertainty.array, uncertainty_restored.array) assert ndd.uncertainty.unit == uncertainty_restored.unit # Even though it has a parent there is no one that references the parent # after unpickling so the weakref "dies" immediately after unpickling # finishes. assert uncertainty_restored.parent_nddata is None def test_pickle_nddata_without_uncertainty(): ndd = NDData(np.ones(3), unit=u.m) dumped = pickle.dumps(ndd) ndd_restored = pickle.loads(dumped) np.testing.assert_array_equal(ndd.data, ndd_restored.data) # Check that the meta descriptor is working as expected. The MetaBaseTest class # takes care of defining all the tests, and we simply have to define the class # and any minimal set of args to pass. from astropy.utils.tests.test_metadata import MetaBaseTest class TestMetaNDData(MetaBaseTest): test_class = NDData args = np.array([[1.]]) # Representation tests def test_nddata_str(): arr1d = NDData(np.array([1, 2, 3])) assert str(arr1d) == '[1 2 3]' arr2d = NDData(np.array([[1, 2], [3, 4]])) assert str(arr2d) == textwrap.dedent(""" [[1 2] [3 4]]"""[1:]) arr3d = NDData(np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])) assert str(arr3d) == textwrap.dedent(""" [[[1 2] [3 4]] [[5 6] [7 8]]]"""[1:]) # let's add units! arr = NDData(np.array([1, 2, 3]), unit="km") assert str(arr) == '[1 2 3] km' # what if it had these units? arr = NDData(np.array([1, 2, 3]), unit="erg cm^-2 s^-1 A^-1") assert str(arr) == '[1 2 3] erg / (A cm2 s)' def test_nddata_repr(): # The big test is eval(repr()) should be equal to the original! arr1d = NDData(np.array([1, 2, 3])) s = repr(arr1d) assert s == 'NDData([1, 2, 3])' got = eval(s) assert np.all(got.data == arr1d.data) assert got.unit == arr1d.unit arr2d = NDData(np.array([[1, 2], [3, 4]])) s = repr(arr2d) assert s == textwrap.dedent(""" NDData([[1, 2], [3, 4]])"""[1:]) got = eval(s) assert np.all(got.data == arr2d.data) assert got.unit == arr2d.unit arr3d = NDData(np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])) s = repr(arr3d) assert s == textwrap.dedent(""" NDData([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])"""[1:]) got = eval(s) assert np.all(got.data == arr3d.data) assert got.unit == arr3d.unit # let's add units! arr = NDData(np.array([1, 2, 3]), unit="km") s = repr(arr) assert s == "NDData([1, 2, 3], unit='km')" got = eval(s) assert np.all(got.data == arr.data) assert got.unit == arr.unit # Not supported features def test_slicing_not_supported(): ndd = NDData(np.ones((5, 5))) with pytest.raises(TypeError): ndd[0] def test_arithmetic_not_supported(): ndd = NDData(np.ones((5, 5))) with pytest.raises(TypeError): ndd + ndd def test_nddata_wcs_setter_error_cases(): ndd = NDData(np.ones((5, 5))) # Setting with a non-WCS should raise an error with pytest.raises(TypeError): ndd.wcs = "I am not a WCS" naxis = 2 # This should succeed since the WCS is currently None ndd.wcs = nd_testing._create_wcs_simple(naxis=naxis, ctype=['deg'] * naxis, crpix=[0] * naxis, crval=[10] * naxis, cdelt=[1] * naxis) with pytest.raises(ValueError): # This should fail since the WCS is not None ndd.wcs = nd_testing._create_wcs_simple(naxis=naxis, ctype=['deg'] * naxis, crpix=[0] * naxis, crval=[10] * naxis, cdelt=[1] * naxis) def test_nddata_wcs_setter_with_low_level_wcs(): ndd = NDData(np.ones((5, 5))) wcs = WCS() # If the wcs property is set with a low level WCS it should get # wrapped to high level. low_level = SlicedLowLevelWCS(wcs, 5) assert not isinstance(low_level, BaseHighLevelWCS) ndd.wcs = low_level assert isinstance(ndd.wcs, BaseHighLevelWCS) def test_nddata_init_with_low_level_wcs(): wcs = WCS() low_level = SlicedLowLevelWCS(wcs, 5) ndd = NDData(np.ones((5, 5)), wcs=low_level) assert isinstance(ndd.wcs, BaseHighLevelWCS) class NDDataCustomWCS(NDData): @property def wcs(self): return WCS() def test_overriden_wcs(): # Check that a sub-class that overrides `.wcs` without providing a setter # works NDDataCustomWCS(np.ones((5, 5)))
34fcde7977ad07f71d77828a240f1f2f9fe8d7576f472c21c9fdb600b6a1847a
# Licensed under a 3-clause BSD style license - see LICENSE.rst # This module contains tests of a class equivalent to pre-1.0 NDData. import pytest import numpy as np from astropy.nddata.nddata import NDData from astropy.nddata.compat import NDDataArray from astropy.nddata.nduncertainty import StdDevUncertainty from astropy.wcs import WCS from astropy import units as u NDDATA_ATTRIBUTES = ['mask', 'flags', 'uncertainty', 'unit', 'shape', 'size', 'dtype', 'ndim', 'wcs', 'convert_unit_to'] def test_nddataarray_has_attributes_of_old_nddata(): ndd = NDDataArray([1, 2, 3]) for attr in NDDATA_ATTRIBUTES: assert hasattr(ndd, attr) def test_nddata_simple(): nd = NDDataArray(np.zeros((10, 10))) assert nd.shape == (10, 10) assert nd.size == 100 assert nd.dtype == np.dtype(float) def test_nddata_parameters(): # Test for issue 4620 nd = NDDataArray(data=np.zeros((10, 10))) assert nd.shape == (10, 10) assert nd.size == 100 assert nd.dtype == np.dtype(float) # Change order; `data` has to be given explicitly here nd = NDDataArray(meta={}, data=np.zeros((10, 10))) assert nd.shape == (10, 10) assert nd.size == 100 assert nd.dtype == np.dtype(float) # Pass uncertainty as second implicit argument data = np.zeros((10, 10)) uncertainty = StdDevUncertainty(0.1 + np.zeros_like(data)) nd = NDDataArray(data, uncertainty) assert nd.shape == (10, 10) assert nd.size == 100 assert nd.dtype == np.dtype(float) assert nd.uncertainty == uncertainty def test_nddata_conversion(): nd = NDDataArray(np.array([[1, 2, 3], [4, 5, 6]])) assert nd.size == 6 assert nd.dtype == np.dtype(int) @pytest.mark.parametrize('flags_in', [ np.array([True, False]), np.array([1, 0]), [True, False], [1, 0], np.array(['a', 'b']), ['a', 'b']]) def test_nddata_flags_init_without_np_array(flags_in): ndd = NDDataArray([1, 1], flags=flags_in) assert (ndd.flags == flags_in).all() @pytest.mark.parametrize(('shape'), [(10,), (5, 5), (3, 10, 10)]) def test_nddata_flags_invalid_shape(shape): with pytest.raises(ValueError) as exc: NDDataArray(np.zeros((10, 10)), flags=np.ones(shape)) assert exc.value.args[0] == 'dimensions of flags do not match data' def test_convert_unit_to(): # convert_unit_to should return a copy of its input d = NDDataArray(np.ones((5, 5))) d.unit = 'km' d.uncertainty = StdDevUncertainty(0.1 + np.zeros_like(d)) # workaround because zeros_like does not support dtype arg until v1.6 # and NDData accepts only bool ndarray as mask tmp = np.zeros_like(d.data) d.mask = np.array(tmp, dtype=bool) d1 = d.convert_unit_to('m') assert np.all(d1.data == np.array(1000.0)) assert np.all(d1.uncertainty.array == 1000.0 * d.uncertainty.array) assert d1.unit == u.m # changing the output mask should not change the original d1.mask[0, 0] = True assert d.mask[0, 0] != d1.mask[0, 0] d.flags = np.zeros_like(d.data) d1 = d.convert_unit_to('m') # check that subclasses can require wcs and/or unit to be present and use # _arithmetic and convert_unit_to class SubNDData(NDDataArray): """ Subclass for test initialization of subclasses in NDData._arithmetic and NDData.convert_unit_to """ def __init__(self, *arg, **kwd): super().__init__(*arg, **kwd) if self.unit is None: raise ValueError("Unit for subclass must be specified") if self.wcs is None: raise ValueError("WCS for subclass must be specified") def test_init_of_subclass_in_convert_unit_to(): data = np.ones([10, 10]) arr1 = SubNDData(data, unit='m', wcs=WCS(naxis=2)) result = arr1.convert_unit_to('km') np.testing.assert_array_equal(arr1.data, 1000 * result.data) # Test for issue #4129: def test_nddataarray_from_nddataarray(): ndd1 = NDDataArray([1., 4., 9.], uncertainty=StdDevUncertainty([1., 2., 3.]), flags=[0, 1, 0]) ndd2 = NDDataArray(ndd1) # Test that the 2 instances point to the same objects and aren't just # equal; this is explicitly documented for the main data array and we # probably want to catch any future change in behavior for the other # attributes too and ensure they are intentional. assert ndd2.data is ndd1.data assert ndd2.uncertainty is ndd1.uncertainty assert ndd2.flags is ndd1.flags assert ndd2.meta == ndd1.meta # Test for issue #4137: def test_nddataarray_from_nddata(): ndd1 = NDData([1., 4., 9.], uncertainty=StdDevUncertainty([1., 2., 3.])) ndd2 = NDDataArray(ndd1) assert ndd2.data is ndd1.data assert ndd2.uncertainty is ndd1.uncertainty assert ndd2.meta == ndd1.meta
b4a6dfc57ab67b8141896550d6f4d9c01e48bc43b30579cd184a0bd4a6ca160c
# Licensed under a 3-clause BSD style license - see LICENSE.rst import inspect import pytest import numpy as np from astropy.utils.exceptions import AstropyUserWarning from astropy import units as u from astropy.wcs import WCS from astropy.nddata.nddata import NDData from astropy.nddata.decorators import support_nddata class CCDData(NDData): pass @support_nddata def wrapped_function_1(data, wcs=None, unit=None): return data, wcs, unit def test_pass_numpy(): data_in = np.array([1, 2, 3]) data_out, wcs_out, unit_out = wrapped_function_1(data=data_in) assert data_out is data_in assert wcs_out is None assert unit_out is None def test_pass_all_separate(): data_in = np.array([1, 2, 3]) wcs_in = WCS(naxis=1) unit_in = u.Jy data_out, wcs_out, unit_out = wrapped_function_1(data=data_in, wcs=wcs_in, unit=unit_in) assert data_out is data_in assert wcs_out is wcs_in assert unit_out is unit_in def test_pass_nddata(): data_in = np.array([1, 2, 3]) wcs_in = WCS(naxis=1) unit_in = u.Jy nddata_in = NDData(data_in, wcs=wcs_in, unit=unit_in) data_out, wcs_out, unit_out = wrapped_function_1(nddata_in) assert data_out is data_in assert wcs_out is wcs_in assert unit_out is unit_in def test_pass_nddata_and_explicit(): data_in = np.array([1, 2, 3]) wcs_in = WCS(naxis=1) unit_in = u.Jy unit_in_alt = u.mJy nddata_in = NDData(data_in, wcs=wcs_in, unit=unit_in) with pytest.warns(AstropyUserWarning, match="Property unit has been passed explicitly and as " "an NDData property, using explicitly specified value") as w: data_out, wcs_out, unit_out = wrapped_function_1(nddata_in, unit=unit_in_alt) assert len(w) == 1 assert data_out is data_in assert wcs_out is wcs_in assert unit_out is unit_in_alt def test_pass_nddata_ignored(): data_in = np.array([1, 2, 3]) wcs_in = WCS(naxis=1) unit_in = u.Jy nddata_in = NDData(data_in, wcs=wcs_in, unit=unit_in, mask=[0, 1, 0]) with pytest.warns(AstropyUserWarning, match="The following attributes were set on the data " "object, but will be ignored by the function: mask") as w: data_out, wcs_out, unit_out = wrapped_function_1(nddata_in) assert len(w) == 1 assert data_out is data_in assert wcs_out is wcs_in assert unit_out is unit_in def test_incorrect_first_argument(): with pytest.raises(ValueError) as exc: @support_nddata def wrapped_function_2(something, wcs=None, unit=None): pass assert exc.value.args[0] == "Can only wrap functions whose first positional argument is `data`" with pytest.raises(ValueError) as exc: @support_nddata def wrapped_function_3(something, data, wcs=None, unit=None): pass assert exc.value.args[0] == "Can only wrap functions whose first positional argument is `data`" with pytest.raises(ValueError) as exc: @support_nddata def wrapped_function_4(wcs=None, unit=None): pass assert exc.value.args[0] == "Can only wrap functions whose first positional argument is `data`" def test_wrap_function_no_kwargs(): @support_nddata def wrapped_function_5(data, other_data): return data data_in = np.array([1, 2, 3]) nddata_in = NDData(data_in) assert wrapped_function_5(nddata_in, [1, 2, 3]) is data_in def test_wrap_function_repack_valid(): @support_nddata(repack=True, returns=['data']) def wrapped_function_5(data, other_data): return data data_in = np.array([1, 2, 3]) nddata_in = NDData(data_in) nddata_out = wrapped_function_5(nddata_in, [1, 2, 3]) assert isinstance(nddata_out, NDData) assert nddata_out.data is data_in def test_wrap_function_accepts(): class MyData(NDData): pass @support_nddata(accepts=MyData) def wrapped_function_5(data, other_data): return data data_in = np.array([1, 2, 3]) nddata_in = NDData(data_in) mydata_in = MyData(data_in) assert wrapped_function_5(mydata_in, [1, 2, 3]) is data_in with pytest.raises(TypeError, match="Only NDData sub-classes that inherit " "from MyData can be used by this function"): wrapped_function_5(nddata_in, [1, 2, 3]) def test_wrap_preserve_signature_docstring(): @support_nddata def wrapped_function_6(data, wcs=None, unit=None): """ An awesome function """ pass if wrapped_function_6.__doc__ is not None: assert wrapped_function_6.__doc__.strip() == "An awesome function" signature = inspect.signature(wrapped_function_6) assert str(signature) == "(data, wcs=None, unit=None)" def test_setup_failures1(): # repack but no returns with pytest.raises(ValueError): support_nddata(repack=True) def test_setup_failures2(): # returns but no repack with pytest.raises(ValueError): support_nddata(returns=['data']) def test_setup_failures9(): # keeps but no repack with pytest.raises(ValueError): support_nddata(keeps=['unit']) def test_setup_failures3(): # same attribute in keeps and returns with pytest.raises(ValueError): support_nddata(repack=True, keeps=['mask'], returns=['data', 'mask']) def test_setup_failures4(): # function accepts *args with pytest.raises(ValueError): @support_nddata def test(data, *args): pass def test_setup_failures10(): # function accepts **kwargs with pytest.raises(ValueError): @support_nddata def test(data, **kwargs): pass def test_setup_failures5(): # function accepts *args (or **kwargs) with pytest.raises(ValueError): @support_nddata def test(data, *args): pass def test_setup_failures6(): # First argument is not data with pytest.raises(ValueError): @support_nddata def test(img): pass def test_setup_failures7(): # accepts CCDData but was given just an NDData with pytest.raises(TypeError): @support_nddata(accepts=CCDData) def test(data): pass test(NDData(np.ones((3, 3)))) def test_setup_failures8(): # function returns a different amount of arguments than specified. Using # NDData here so we don't get into troubles when creating a CCDData without # unit! with pytest.raises(ValueError): @support_nddata(repack=True, returns=['data', 'mask']) def test(data): return 10 test(NDData(np.ones((3, 3)))) # do NOT use CCDData here. def test_setup_failures11(): # function accepts no arguments with pytest.raises(ValueError): @support_nddata def test(): pass def test_setup_numpyarray_default(): # It should be possible (even if it's not advisable to use mutable # defaults) to have a numpy array as default value. @support_nddata def func(data, wcs=np.array([1, 2, 3])): return wcs def test_still_accepts_other_input(): @support_nddata(repack=True, returns=['data']) def test(data): return data assert isinstance(test(NDData(np.ones((3, 3)))), NDData) assert isinstance(test(10), int) assert isinstance(test([1, 2, 3]), list) def test_accepting_property_normal(): # Accepts a mask attribute and takes it from the input @support_nddata def test(data, mask=None): return mask ndd = NDData(np.ones((3, 3))) assert test(ndd) is None ndd._mask = np.zeros((3, 3)) assert np.all(test(ndd) == 0) # Use the explicitly given one (raises a Warning) with pytest.warns(AstropyUserWarning) as w: assert test(ndd, mask=10) == 10 assert len(w) == 1 def test_parameter_default_identical_to_explicit_passed_argument(): # If the default is identical to the explicitly passed argument this # should still raise a Warning and use the explicit one. @support_nddata def func(data, meta={'a': 1}): return meta with pytest.warns(AstropyUserWarning) as w: assert func(NDData(1, meta={'b': 2}), {'a': 1}) == {'a': 1} assert len(w) == 1 assert func(NDData(1, meta={'b': 2})) == {'b': 2} def test_accepting_property_notexist(): # Accepts flags attribute but NDData doesn't have one @support_nddata def test(data, flags=10): return flags ndd = NDData(np.ones((3, 3))) test(ndd) def test_accepting_property_translated(): # Accepts a error attribute and we want to pass in uncertainty! @support_nddata(mask='masked') def test(data, masked=None): return masked ndd = NDData(np.ones((3, 3))) assert test(ndd) is None ndd._mask = np.zeros((3, 3)) assert np.all(test(ndd) == 0) # Use the explicitly given one (raises a Warning) with pytest.warns(AstropyUserWarning) as w: assert test(ndd, masked=10) == 10 assert len(w) == 1 def test_accepting_property_meta_empty(): # Meta is always set (OrderedDict) so it has a special case that it's # ignored if it's empty but not None @support_nddata def test(data, meta=None): return meta ndd = NDData(np.ones((3, 3))) assert test(ndd) is None ndd._meta = {'a': 10} assert test(ndd) == {'a': 10}
c14abf217af5ca49de5f87441682bbe020bfdeca789e1a09aa211f8d2165f5f5
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pickle import pytest import numpy as np from numpy.testing import assert_array_equal from astropy.nddata.nduncertainty import (StdDevUncertainty, VarianceUncertainty, InverseVariance, NDUncertainty, IncompatibleUncertaintiesException, MissingDataAssociationException, UnknownUncertainty) from astropy.nddata.nddata import NDData from astropy.nddata.compat import NDDataArray from astropy.nddata.ccddata import CCDData from astropy import units as u # Regarding setter tests: # No need to test setters since the uncertainty is considered immutable after # creation except of the parent_nddata attribute and this accepts just # everything. # Additionally they should be covered by NDData, NDArithmeticMixin which rely # on it # Regarding propagate, _convert_uncert, _propagate_* tests: # They should be covered by NDArithmeticMixin since there is generally no need # to test them without this mixin. # Regarding __getitem__ tests: # Should be covered by NDSlicingMixin. # Regarding StdDevUncertainty tests: # This subclass only overrides the methods for propagation so the same # they should be covered in NDArithmeticMixin. # Not really fake but the minimum an uncertainty has to override not to be # abstract. class FakeUncertainty(NDUncertainty): @property def uncertainty_type(self): return 'fake' def _data_unit_to_uncertainty_unit(self, value): return None def _propagate_add(self, data, final_data): pass def _propagate_subtract(self, data, final_data): pass def _propagate_multiply(self, data, final_data): pass def _propagate_divide(self, data, final_data): pass # Test the fake (added also StdDevUncertainty which should behave identical) # the list of classes used for parametrization in tests below uncertainty_types_to_be_tested = [ FakeUncertainty, StdDevUncertainty, VarianceUncertainty, InverseVariance, UnknownUncertainty ] @pytest.mark.parametrize(('UncertClass'), uncertainty_types_to_be_tested) def test_init_fake_with_list(UncertClass): fake_uncert = UncertClass([1, 2, 3]) assert_array_equal(fake_uncert.array, np.array([1, 2, 3])) # Copy makes no difference since casting a list to an np.ndarray always # makes a copy. # But let's give the uncertainty a unit too fake_uncert = UncertClass([1, 2, 3], unit=u.adu) assert_array_equal(fake_uncert.array, np.array([1, 2, 3])) assert fake_uncert.unit is u.adu @pytest.mark.parametrize(('UncertClass'), uncertainty_types_to_be_tested) def test_init_fake_with_ndarray(UncertClass): uncert = np.arange(100).reshape(10, 10) fake_uncert = UncertClass(uncert) # Numpy Arrays are copied by default assert_array_equal(fake_uncert.array, uncert) assert fake_uncert.array is not uncert # Now try it without copy fake_uncert = UncertClass(uncert, copy=False) assert fake_uncert.array is uncert # let's provide a unit fake_uncert = UncertClass(uncert, unit=u.adu) assert_array_equal(fake_uncert.array, uncert) assert fake_uncert.array is not uncert assert fake_uncert.unit is u.adu @pytest.mark.parametrize(('UncertClass'), uncertainty_types_to_be_tested) def test_init_fake_with_quantity(UncertClass): uncert = np.arange(10).reshape(2, 5) * u.adu fake_uncert = UncertClass(uncert) # Numpy Arrays are copied by default assert_array_equal(fake_uncert.array, uncert.value) assert fake_uncert.array is not uncert.value assert fake_uncert.unit is u.adu # Try without copy (should not work, quantity.value always returns a copy) fake_uncert = UncertClass(uncert, copy=False) assert fake_uncert.array is not uncert.value assert fake_uncert.unit is u.adu # Now try with an explicit unit parameter too fake_uncert = UncertClass(uncert, unit=u.m) assert_array_equal(fake_uncert.array, uncert.value) # No conversion done assert fake_uncert.array is not uncert.value assert fake_uncert.unit is u.m # It took the explicit one @pytest.mark.parametrize(('UncertClass'), uncertainty_types_to_be_tested) def test_init_fake_with_fake(UncertClass): uncert = np.arange(5).reshape(5, 1) fake_uncert1 = UncertClass(uncert) fake_uncert2 = UncertClass(fake_uncert1) assert_array_equal(fake_uncert2.array, uncert) assert fake_uncert2.array is not uncert # Without making copies fake_uncert1 = UncertClass(uncert, copy=False) fake_uncert2 = UncertClass(fake_uncert1, copy=False) assert_array_equal(fake_uncert2.array, fake_uncert1.array) assert fake_uncert2.array is fake_uncert1.array # With a unit uncert = np.arange(5).reshape(5, 1) * u.adu fake_uncert1 = UncertClass(uncert) fake_uncert2 = UncertClass(fake_uncert1) assert_array_equal(fake_uncert2.array, uncert.value) assert fake_uncert2.array is not uncert.value assert fake_uncert2.unit is u.adu # With a unit and an explicit unit-parameter fake_uncert2 = UncertClass(fake_uncert1, unit=u.cm) assert_array_equal(fake_uncert2.array, uncert.value) assert fake_uncert2.array is not uncert.value assert fake_uncert2.unit is u.cm @pytest.mark.parametrize(('UncertClass'), uncertainty_types_to_be_tested) def test_init_fake_with_somethingElse(UncertClass): # What about a dict? uncert = {'rdnoise': 2.9, 'gain': 0.6} fake_uncert = UncertClass(uncert) assert fake_uncert.array == uncert # We can pass a unit too but since we cannot do uncertainty propagation # the interpretation is up to the user fake_uncert = UncertClass(uncert, unit=u.s) assert fake_uncert.array == uncert assert fake_uncert.unit is u.s # So, now check what happens if copy is False fake_uncert = UncertClass(uncert, copy=False) assert fake_uncert.array == uncert assert id(fake_uncert) != id(uncert) # dicts cannot be referenced without copy # TODO : Find something that can be referenced without copy :-) def test_init_fake_with_StdDevUncertainty(): # Different instances of uncertainties are not directly convertible so this # should fail uncert = np.arange(5).reshape(5, 1) std_uncert = StdDevUncertainty(uncert) with pytest.raises(IncompatibleUncertaintiesException): FakeUncertainty(std_uncert) # Ok try it the other way around fake_uncert = FakeUncertainty(uncert) with pytest.raises(IncompatibleUncertaintiesException): StdDevUncertainty(fake_uncert) def test_uncertainty_type(): fake_uncert = FakeUncertainty([10, 2]) assert fake_uncert.uncertainty_type == 'fake' std_uncert = StdDevUncertainty([10, 2]) assert std_uncert.uncertainty_type == 'std' var_uncert = VarianceUncertainty([10, 2]) assert var_uncert.uncertainty_type == 'var' ivar_uncert = InverseVariance([10, 2]) assert ivar_uncert.uncertainty_type == 'ivar' def test_uncertainty_correlated(): fake_uncert = FakeUncertainty([10, 2]) assert not fake_uncert.supports_correlated std_uncert = StdDevUncertainty([10, 2]) assert std_uncert.supports_correlated def test_for_leak_with_uncertainty(): # Regression test for memory leak because of cyclic references between # NDData and uncertainty from collections import defaultdict from gc import get_objects def test_leak(func, specific_objects=None): """Function based on gc.get_objects to determine if any object or a specific object leaks. It requires a function to be given and if any objects survive the function scope it's considered a leak (so don't return anything). """ before = defaultdict(int) for i in get_objects(): before[type(i)] += 1 func() after = defaultdict(int) for i in get_objects(): after[type(i)] += 1 if specific_objects is None: assert all(after[k] - before[k] == 0 for k in after) else: assert after[specific_objects] - before[specific_objects] == 0 def non_leaker_nddata(): # Without uncertainty there is no reason to assume that there is a # memory leak but test it nevertheless. NDData(np.ones(100)) def leaker_nddata(): # With uncertainty there was a memory leak! NDData(np.ones(100), uncertainty=StdDevUncertainty(np.ones(100))) test_leak(non_leaker_nddata, NDData) test_leak(leaker_nddata, NDData) # Same for NDDataArray: from astropy.nddata.compat import NDDataArray def non_leaker_nddataarray(): NDDataArray(np.ones(100)) def leaker_nddataarray(): NDDataArray(np.ones(100), uncertainty=StdDevUncertainty(np.ones(100))) test_leak(non_leaker_nddataarray, NDDataArray) test_leak(leaker_nddataarray, NDDataArray) def test_for_stolen_uncertainty(): # Sharing uncertainties should not overwrite the parent_nddata attribute ndd1 = NDData(1, uncertainty=1) ndd2 = NDData(2, uncertainty=ndd1.uncertainty) # uncertainty.parent_nddata.data should be the original data! assert ndd1.uncertainty.parent_nddata.data == ndd1.data assert ndd2.uncertainty.parent_nddata.data == ndd2.data def test_stddevuncertainty_pickle(): uncertainty = StdDevUncertainty(np.ones(3), unit=u.m) uncertainty_restored = pickle.loads(pickle.dumps(uncertainty)) np.testing.assert_array_equal(uncertainty.array, uncertainty_restored.array) assert uncertainty.unit == uncertainty_restored.unit with pytest.raises(MissingDataAssociationException): uncertainty_restored.parent_nddata @pytest.mark.parametrize(('UncertClass'), uncertainty_types_to_be_tested) def test_quantity(UncertClass): fake_uncert = UncertClass([1, 2, 3], unit=u.adu) assert isinstance(fake_uncert.quantity, u.Quantity) assert fake_uncert.quantity.unit.is_equivalent(u.adu) fake_uncert_nounit = UncertClass([1, 2, 3]) assert isinstance(fake_uncert_nounit.quantity, u.Quantity) assert fake_uncert_nounit.quantity.unit.is_equivalent(u.dimensionless_unscaled) @pytest.mark.parametrize(('UncertClass'), [VarianceUncertainty, StdDevUncertainty, InverseVariance]) def test_setting_uncertainty_unit_results_in_unit_object(UncertClass): v = UncertClass([1, 1]) v.unit = 'electron' assert isinstance(v.unit, u.UnitBase) @pytest.mark.parametrize('NDClass', [NDData, NDDataArray, CCDData]) @pytest.mark.parametrize(('UncertClass'), [VarianceUncertainty, StdDevUncertainty, InverseVariance]) def test_changing_unit_to_value_inconsistent_with_parent_fails(NDClass, UncertClass): ndd1 = NDClass(1, unit='adu') v = UncertClass(1) # Sets the uncertainty unit to whatever makes sense with this data. ndd1.uncertainty = v with pytest.raises(u.UnitConversionError): # Nothing special about 15 except no one would ever use that unit v.unit = ndd1.unit ** 15 @pytest.mark.parametrize('NDClass', [NDData, NDDataArray, CCDData]) @pytest.mark.parametrize(('UncertClass, expected_unit'), [(VarianceUncertainty, u.adu ** 2), (StdDevUncertainty, u.adu), (InverseVariance, 1 / u.adu ** 2)]) def test_assigning_uncertainty_to_parent_gives_correct_unit(NDClass, UncertClass, expected_unit): # Does assigning a unitless uncertainty to an NDData result in the # expected unit? ndd = NDClass([1, 1], unit=u.adu) v = UncertClass([1, 1]) ndd.uncertainty = v assert v.unit == expected_unit @pytest.mark.parametrize('NDClass', [NDData, NDDataArray, CCDData]) @pytest.mark.parametrize(('UncertClass, expected_unit'), [(VarianceUncertainty, u.adu ** 2), (StdDevUncertainty, u.adu), (InverseVariance, 1 / u.adu ** 2)]) def test_assigning_uncertainty_with_unit_to_parent_with_unit(NDClass, UncertClass, expected_unit): # Does assigning an uncertainty with an appropriate unit to an NDData # with a unit work? ndd = NDClass([1, 1], unit=u.adu) v = UncertClass([1, 1], unit=expected_unit) ndd.uncertainty = v assert v.unit == expected_unit @pytest.mark.parametrize('NDClass', [NDData, NDDataArray, CCDData]) @pytest.mark.parametrize(('UncertClass'), [(VarianceUncertainty), (StdDevUncertainty), (InverseVariance)]) def test_assigning_uncertainty_with_bad_unit_to_parent_fails(NDClass, UncertClass): # Does assigning an uncertainty with a non-matching unit to an NDData # with a unit work? ndd = NDClass([1, 1], unit=u.adu) # Set the unit to something inconsistent with ndd's unit v = UncertClass([1, 1], unit=u.second) with pytest.raises(u.UnitConversionError): ndd.uncertainty = v
133458ee7233f6941186d8fdd512fd95d86e88c73b3ac033e42b318ccbdacc64
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest import numpy as np from numpy.testing import assert_array_equal from astropy.nddata import NDData, NDSlicingMixin from astropy.nddata import _testing as nd_testing from astropy.nddata.nduncertainty import NDUncertainty, StdDevUncertainty from astropy import units as u # Just add the Mixin to NDData # TODO: Make this use NDDataRef instead! class NDDataSliceable(NDSlicingMixin, NDData): pass # Just some uncertainty (following the StdDevUncertainty implementation of # storing the uncertainty in a property 'array') with slicing. class SomeUncertainty(NDUncertainty): @property def uncertainty_type(self): return 'fake' def _propagate_add(self, data, final_data): pass def _propagate_subtract(self, data, final_data): pass def _propagate_multiply(self, data, final_data): pass def _propagate_divide(self, data, final_data): pass def test_slicing_only_data(): data = np.arange(10) nd = NDDataSliceable(data) nd2 = nd[2:5] assert_array_equal(data[2:5], nd2.data) def test_slicing_data_scalar_fail(): data = np.array(10) nd = NDDataSliceable(data) with pytest.raises(TypeError): # as exc nd[:] # assert exc.value.args[0] == 'Scalars cannot be sliced.' def test_slicing_1ddata_ndslice(): data = np.array([10, 20]) nd = NDDataSliceable(data) # Standard numpy warning here: with pytest.raises(IndexError): nd[:, :] @pytest.mark.parametrize('prop_name', ['mask', 'uncertainty']) def test_slicing_1dmask_ndslice(prop_name): # Data is 2d but mask/uncertainty only 1d so this should let the IndexError when # slicing the mask rise to the user. data = np.ones((3, 3)) kwarg = {prop_name: np.ones(3)} nd = NDDataSliceable(data, **kwarg) # Standard numpy warning here: with pytest.raises(IndexError): nd[:, :] def test_slicing_all_npndarray_1d(): data = np.arange(10) mask = data > 3 uncertainty = StdDevUncertainty(np.linspace(10, 20, 10)) naxis = 1 wcs = nd_testing._create_wcs_simple(naxis=naxis, ctype=["deg"] * naxis, crpix=[3] * naxis, crval=[10] * naxis, cdelt=[1] * naxis) # Just to have them too unit = u.s meta = {'observer': 'Brian'} nd = NDDataSliceable(data, mask=mask, uncertainty=uncertainty, wcs=wcs, unit=unit, meta=meta) nd2 = nd[2:5] assert_array_equal(data[2:5], nd2.data) assert_array_equal(mask[2:5], nd2.mask) assert_array_equal(uncertainty[2:5].array, nd2.uncertainty.array) assert nd2.wcs.pixel_to_world(1) == nd.wcs.pixel_to_world(3) assert unit is nd2.unit assert meta == nd.meta def test_slicing_all_npndarray_nd(): # See what happens for multidimensional properties data = np.arange(1000).reshape(10, 10, 10) mask = data > 3 uncertainty = np.linspace(10, 20, 1000).reshape(10, 10, 10) naxis = 3 wcs = nd_testing._create_wcs_simple(naxis=naxis, ctype=["deg"] * naxis, crpix=[3] * naxis, crval=[10] * naxis, cdelt=[1] * naxis) nd = NDDataSliceable(data, mask=mask, uncertainty=uncertainty, wcs=wcs) # Slice only 1D nd2 = nd[2:5] assert_array_equal(data[2:5], nd2.data) assert_array_equal(mask[2:5], nd2.mask) assert_array_equal(uncertainty[2:5], nd2.uncertainty.array) # Slice 3D nd2 = nd[2:5, :, 4:7] assert_array_equal(data[2:5, :, 4:7], nd2.data) assert_array_equal(mask[2:5, :, 4:7], nd2.mask) assert_array_equal(uncertainty[2:5, :, 4:7], nd2.uncertainty.array) assert nd2.wcs.pixel_to_world(1, 5, 1) == nd.wcs.pixel_to_world(5, 5, 3) def test_slicing_all_npndarray_shape_diff(): data = np.arange(10) mask = (data > 3)[0:9] uncertainty = np.linspace(10, 20, 15) naxis = 1 wcs = nd_testing._create_wcs_simple(naxis=naxis, ctype=["deg"] * naxis, crpix=[3] * naxis, crval=[10] * naxis, cdelt=[1] * naxis) nd = NDDataSliceable(data, mask=mask, uncertainty=uncertainty, wcs=wcs) nd2 = nd[2:5] assert_array_equal(data[2:5], nd2.data) # All are sliced even if the shapes differ (no Info) assert_array_equal(mask[2:5], nd2.mask) assert_array_equal(uncertainty[2:5], nd2.uncertainty.array) assert nd2.wcs.pixel_to_world(1) == nd.wcs.pixel_to_world(3) def test_slicing_all_something_wrong(): data = np.arange(10) mask = [False] * 10 uncertainty = {'rdnoise': 2.9, 'gain': 1.4} naxis = 1 wcs = nd_testing._create_wcs_simple(naxis=naxis, ctype=["deg"] * naxis, crpix=[3] * naxis, crval=[10] * naxis, cdelt=[1] * naxis) nd = NDDataSliceable(data, mask=mask, uncertainty=uncertainty, wcs=wcs) nd2 = nd[2:5] # Sliced properties: assert_array_equal(data[2:5], nd2.data) assert_array_equal(mask[2:5], nd2.mask) # Not sliced attributes (they will raise a Info nevertheless) uncertainty is nd2.uncertainty assert nd2.wcs.pixel_to_world(1) == nd.wcs.pixel_to_world(3) def test_boolean_slicing(): data = np.arange(10) mask = data.copy() uncertainty = StdDevUncertainty(data.copy()) naxis = 1 wcs = nd_testing._create_wcs_simple(naxis=naxis, ctype=["deg"] * naxis, crpix=[3] * naxis, crval=[10] * naxis, cdelt=[1] * naxis) nd = NDDataSliceable(data, mask=mask, uncertainty=uncertainty, wcs=wcs) with pytest.raises(ValueError): nd2 = nd[(nd.data >= 3) & (nd.data < 8)] nd.wcs = None nd2 = nd[(nd.data >= 3) & (nd.data < 8)] assert_array_equal(data[3:8], nd2.data) assert_array_equal(mask[3:8], nd2.mask)
b1c98332e7957257679e3aaa64851a770310bc3b4b7142b08abca16fdbfb56fd
from astropy.nddata import NDData, NDIOMixin, NDDataRef # Alias NDDataAllMixins in case this will be renamed ... :-) NDDataIO = NDDataRef def test_simple_write_read(tmpdir): ndd = NDDataIO([1, 2, 3]) assert hasattr(ndd, 'read') assert hasattr(ndd, 'write')
326ff94a94ff77e2f1022876909edd59ebb77be89b446316c995da46051f14fc
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest import numpy as np from numpy.testing import assert_array_equal, assert_array_almost_equal from astropy.nddata.nduncertainty import ( StdDevUncertainty, VarianceUncertainty, InverseVariance, UnknownUncertainty, IncompatibleUncertaintiesException) from astropy.nddata import NDDataRef from astropy.nddata import _testing as nd_testing from astropy.units import UnitsError, Quantity from astropy import units as u from astropy.wcs import WCS # Alias NDDataAllMixins in case this will be renamed ... :-) NDDataArithmetic = NDDataRef class StdDevUncertaintyUncorrelated(StdDevUncertainty): @property def supports_correlated(self): return False # Test with Data covers: # scalars, 1D, 2D and 3D # broadcasting between them @pytest.mark.filterwarnings("ignore:divide by zero encountered.*") @pytest.mark.parametrize(('data1', 'data2'), [ (np.array(5), np.array(10)), (np.array(5), np.arange(10)), (np.array(5), np.arange(10).reshape(2, 5)), (np.arange(10), np.ones(10) * 2), (np.arange(10), np.ones((10, 10)) * 2), (np.arange(10).reshape(2, 5), np.ones((2, 5)) * 3), (np.arange(1000).reshape(20, 5, 10), np.ones((20, 5, 10)) * 3) ]) def test_arithmetics_data(data1, data2): nd1 = NDDataArithmetic(data1) nd2 = NDDataArithmetic(data2) # Addition nd3 = nd1.add(nd2) assert_array_equal(data1+data2, nd3.data) # Subtraction nd4 = nd1.subtract(nd2) assert_array_equal(data1-data2, nd4.data) # Multiplication nd5 = nd1.multiply(nd2) assert_array_equal(data1*data2, nd5.data) # Division nd6 = nd1.divide(nd2) assert_array_equal(data1/data2, nd6.data) for nd in [nd3, nd4, nd5, nd6]: # Check that broadcasting worked as expected if data1.ndim > data2.ndim: assert data1.shape == nd.data.shape else: assert data2.shape == nd.data.shape # Check all other attributes are not set assert nd.unit is None assert nd.uncertainty is None assert nd.mask is None assert len(nd.meta) == 0 assert nd.wcs is None # Invalid arithmetic operations for data covering: # not broadcastable data def test_arithmetics_data_invalid(): nd1 = NDDataArithmetic([1, 2, 3]) nd2 = NDDataArithmetic([1, 2]) with pytest.raises(ValueError): nd1.add(nd2) # Test with Data and unit and covers: # identical units (even dimensionless unscaled vs. no unit), # equivalent units (such as meter and kilometer) # equivalent composite units (such as m/s and km/h) @pytest.mark.filterwarnings("ignore:divide by zero encountered.*") @pytest.mark.parametrize(('data1', 'data2'), [ (np.array(5) * u.s, np.array(10) * u.s), (np.array(5) * u.s, np.arange(10) * u.h), (np.array(5) * u.s, np.arange(10).reshape(2, 5) * u.min), (np.arange(10) * u.m / u.s, np.ones(10) * 2 * u.km / u.s), (np.arange(10) * u.m / u.s, np.ones((10, 10)) * 2 * u.m / u.h), (np.arange(10).reshape(2, 5) * u.m / u.s, np.ones((2, 5)) * 3 * u.km / u.h), (np.arange(1000).reshape(20, 5, 10), np.ones((20, 5, 10)) * 3 * u.dimensionless_unscaled), (np.array(5), np.array(10) * u.s / u.h), ]) def test_arithmetics_data_unit_identical(data1, data2): nd1 = NDDataArithmetic(data1) nd2 = NDDataArithmetic(data2) # Addition nd3 = nd1.add(nd2) ref = data1 + data2 ref_unit, ref_data = ref.unit, ref.value assert_array_equal(ref_data, nd3.data) assert nd3.unit == ref_unit # Subtraction nd4 = nd1.subtract(nd2) ref = data1 - data2 ref_unit, ref_data = ref.unit, ref.value assert_array_equal(ref_data, nd4.data) assert nd4.unit == ref_unit # Multiplication nd5 = nd1.multiply(nd2) ref = data1 * data2 ref_unit, ref_data = ref.unit, ref.value assert_array_equal(ref_data, nd5.data) assert nd5.unit == ref_unit # Division nd6 = nd1.divide(nd2) ref = data1 / data2 ref_unit, ref_data = ref.unit, ref.value assert_array_equal(ref_data, nd6.data) assert nd6.unit == ref_unit for nd in [nd3, nd4, nd5, nd6]: # Check that broadcasting worked as expected if data1.ndim > data2.ndim: assert data1.shape == nd.data.shape else: assert data2.shape == nd.data.shape # Check all other attributes are not set assert nd.uncertainty is None assert nd.mask is None assert len(nd.meta) == 0 assert nd.wcs is None # Test with Data and unit and covers: # not identical not convertible units # one with unit (which is not dimensionless) and one without @pytest.mark.parametrize(('data1', 'data2'), [ (np.array(5) * u.s, np.array(10) * u.m), (np.array(5) * u.Mpc, np.array(10) * u.km / u.s), (np.array(5) * u.Mpc, np.array(10)), (np.array(5), np.array(10) * u.s), ]) def test_arithmetics_data_unit_not_identical(data1, data2): nd1 = NDDataArithmetic(data1) nd2 = NDDataArithmetic(data2) # Addition should not be possible with pytest.raises(UnitsError): nd1.add(nd2) # Subtraction should not be possible with pytest.raises(UnitsError): nd1.subtract(nd2) # Multiplication is possible nd3 = nd1.multiply(nd2) ref = data1 * data2 ref_unit, ref_data = ref.unit, ref.value assert_array_equal(ref_data, nd3.data) assert nd3.unit == ref_unit # Division is possible nd4 = nd1.divide(nd2) ref = data1 / data2 ref_unit, ref_data = ref.unit, ref.value assert_array_equal(ref_data, nd4.data) assert nd4.unit == ref_unit for nd in [nd3, nd4]: # Check all other attributes are not set assert nd.uncertainty is None assert nd.mask is None assert len(nd.meta) == 0 assert nd.wcs is None # Tests with wcs (not very sensible because there is no operation between them # covering: # both set and identical/not identical # one set # None set @pytest.mark.parametrize(('wcs1', 'wcs2'), [ (None, None), (None, WCS(naxis=2)), (WCS(naxis=2), None), nd_testing.create_two_equal_wcs(naxis=2), nd_testing.create_two_unequal_wcs(naxis=2), ]) def test_arithmetics_data_wcs(wcs1, wcs2): nd1 = NDDataArithmetic(1, wcs=wcs1) nd2 = NDDataArithmetic(1, wcs=wcs2) if wcs1 is None and wcs2 is None: ref_wcs = None elif wcs1 is None: ref_wcs = wcs2 elif wcs2 is None: ref_wcs = wcs1 else: ref_wcs = wcs1 # Addition nd3 = nd1.add(nd2) nd_testing.assert_wcs_seem_equal(ref_wcs, nd3.wcs) # Subtraction nd4 = nd1.subtract(nd2) nd_testing.assert_wcs_seem_equal(ref_wcs, nd4.wcs) # Multiplication nd5 = nd1.multiply(nd2) nd_testing.assert_wcs_seem_equal(ref_wcs, nd5.wcs) # Division nd6 = nd1.divide(nd2) nd_testing.assert_wcs_seem_equal(ref_wcs, nd6.wcs) for nd in [nd3, nd4, nd5, nd6]: # Check all other attributes are not set assert nd.unit is None assert nd.uncertainty is None assert len(nd.meta) == 0 assert nd.mask is None # Masks are completely separated in the NDArithmetics from the data so we need # no correlated tests but covering: # masks 1D, 2D and mixed cases with broadcasting @pytest.mark.parametrize(('mask1', 'mask2'), [ (None, None), (None, False), (True, None), (False, False), (True, False), (False, True), (True, True), (np.array(False), np.array(True)), (np.array(False), np.array([0, 1, 0, 1, 1], dtype=np.bool_)), (np.array(True), np.array([[0, 1, 0, 1, 1], [1, 1, 0, 1, 1]], dtype=np.bool_)), (np.array([0, 1, 0, 1, 1], dtype=np.bool_), np.array([1, 1, 0, 0, 1], dtype=np.bool_)), (np.array([0, 1, 0, 1, 1], dtype=np.bool_), np.array([[0, 1, 0, 1, 1], [1, 0, 0, 1, 1]], dtype=np.bool_)), (np.array([[0, 1, 0, 1, 1], [1, 0, 0, 1, 1]], dtype=np.bool_), np.array([[0, 1, 0, 1, 1], [1, 1, 0, 1, 1]], dtype=np.bool_)), ]) def test_arithmetics_data_masks(mask1, mask2): nd1 = NDDataArithmetic(1, mask=mask1) nd2 = NDDataArithmetic(1, mask=mask2) if mask1 is None and mask2 is None: ref_mask = None elif mask1 is None: ref_mask = mask2 elif mask2 is None: ref_mask = mask1 else: ref_mask = mask1 | mask2 # Addition nd3 = nd1.add(nd2) assert_array_equal(ref_mask, nd3.mask) # Subtraction nd4 = nd1.subtract(nd2) assert_array_equal(ref_mask, nd4.mask) # Multiplication nd5 = nd1.multiply(nd2) assert_array_equal(ref_mask, nd5.mask) # Division nd6 = nd1.divide(nd2) assert_array_equal(ref_mask, nd6.mask) for nd in [nd3, nd4, nd5, nd6]: # Check all other attributes are not set assert nd.unit is None assert nd.uncertainty is None assert len(nd.meta) == 0 assert nd.wcs is None # One additional case which can not be easily incorporated in the test above # what happens if the masks are numpy ndarrays are not broadcastable def test_arithmetics_data_masks_invalid(): nd1 = NDDataArithmetic(1, mask=np.array([1, 0], dtype=np.bool_)) nd2 = NDDataArithmetic(1, mask=np.array([1, 0, 1], dtype=np.bool_)) with pytest.raises(ValueError): nd1.add(nd2) with pytest.raises(ValueError): nd1.multiply(nd2) with pytest.raises(ValueError): nd1.subtract(nd2) with pytest.raises(ValueError): nd1.divide(nd2) # Covering: # both have uncertainties (data and uncertainty without unit) # tested against manually determined resulting uncertainties to verify the # implemented formulas # this test only works as long as data1 and data2 do not contain any 0 def test_arithmetics_stddevuncertainty_basic(): nd1 = NDDataArithmetic([1, 2, 3], uncertainty=StdDevUncertainty([1, 1, 3])) nd2 = NDDataArithmetic([2, 2, 2], uncertainty=StdDevUncertainty([2, 2, 2])) nd3 = nd1.add(nd2) nd4 = nd2.add(nd1) # Inverse operation should result in the same uncertainty assert_array_equal(nd3.uncertainty.array, nd4.uncertainty.array) # Compare it to the theoretical uncertainty ref_uncertainty = np.sqrt(np.array([1, 1, 3])**2 + np.array([2, 2, 2])**2) assert_array_equal(nd3.uncertainty.array, ref_uncertainty) nd3 = nd1.subtract(nd2) nd4 = nd2.subtract(nd1) # Inverse operation should result in the same uncertainty assert_array_equal(nd3.uncertainty.array, nd4.uncertainty.array) # Compare it to the theoretical uncertainty (same as for add) assert_array_equal(nd3.uncertainty.array, ref_uncertainty) # Multiplication and Division only work with almost equal array comparisons # since the formula implemented and the formula used as reference are # slightly different. nd3 = nd1.multiply(nd2) nd4 = nd2.multiply(nd1) # Inverse operation should result in the same uncertainty assert_array_almost_equal(nd3.uncertainty.array, nd4.uncertainty.array) # Compare it to the theoretical uncertainty ref_uncertainty = np.abs(np.array([2, 4, 6])) * np.sqrt( (np.array([1, 1, 3]) / np.array([1, 2, 3]))**2 + (np.array([2, 2, 2]) / np.array([2, 2, 2]))**2) assert_array_almost_equal(nd3.uncertainty.array, ref_uncertainty) nd3 = nd1.divide(nd2) nd4 = nd2.divide(nd1) # Inverse operation gives a different uncertainty! # Compare it to the theoretical uncertainty ref_uncertainty_1 = np.abs(np.array([1/2, 2/2, 3/2])) * np.sqrt( (np.array([1, 1, 3]) / np.array([1, 2, 3]))**2 + (np.array([2, 2, 2]) / np.array([2, 2, 2]))**2) assert_array_almost_equal(nd3.uncertainty.array, ref_uncertainty_1) ref_uncertainty_2 = np.abs(np.array([2, 1, 2/3])) * np.sqrt( (np.array([1, 1, 3]) / np.array([1, 2, 3]))**2 + (np.array([2, 2, 2]) / np.array([2, 2, 2]))**2) assert_array_almost_equal(nd4.uncertainty.array, ref_uncertainty_2) # Tests for correlation, covering # correlation between -1 and 1 with correlation term being positive / negative # also with one data being once positive and once completely negative # The point of this test is to compare the used formula to the theoretical one. # TODO: Maybe covering units too but I think that should work because of # the next tests. Also this may be reduced somehow. @pytest.mark.parametrize(('cor', 'uncert1', 'data2'), [ (-1, [1, 1, 3], [2, 2, 7]), (-0.5, [1, 1, 3], [2, 2, 7]), (-0.25, [1, 1, 3], [2, 2, 7]), (0, [1, 1, 3], [2, 2, 7]), (0.25, [1, 1, 3], [2, 2, 7]), (0.5, [1, 1, 3], [2, 2, 7]), (1, [1, 1, 3], [2, 2, 7]), (-1, [-1, -1, -3], [2, 2, 7]), (-0.5, [-1, -1, -3], [2, 2, 7]), (-0.25, [-1, -1, -3], [2, 2, 7]), (0, [-1, -1, -3], [2, 2, 7]), (0.25, [-1, -1, -3], [2, 2, 7]), (0.5, [-1, -1, -3], [2, 2, 7]), (1, [-1, -1, -3], [2, 2, 7]), (-1, [1, 1, 3], [-2, -3, -2]), (-0.5, [1, 1, 3], [-2, -3, -2]), (-0.25, [1, 1, 3], [-2, -3, -2]), (0, [1, 1, 3], [-2, -3, -2]), (0.25, [1, 1, 3], [-2, -3, -2]), (0.5, [1, 1, 3], [-2, -3, -2]), (1, [1, 1, 3], [-2, -3, -2]), (-1, [-1, -1, -3], [-2, -3, -2]), (-0.5, [-1, -1, -3], [-2, -3, -2]), (-0.25, [-1, -1, -3], [-2, -3, -2]), (0, [-1, -1, -3], [-2, -3, -2]), (0.25, [-1, -1, -3], [-2, -3, -2]), (0.5, [-1, -1, -3], [-2, -3, -2]), (1, [-1, -1, -3], [-2, -3, -2]), ]) def test_arithmetics_stddevuncertainty_basic_with_correlation( cor, uncert1, data2): data1 = np.array([1, 2, 3]) data2 = np.array(data2) uncert1 = np.array(uncert1) uncert2 = np.array([2, 2, 2]) nd1 = NDDataArithmetic(data1, uncertainty=StdDevUncertainty(uncert1)) nd2 = NDDataArithmetic(data2, uncertainty=StdDevUncertainty(uncert2)) nd3 = nd1.add(nd2, uncertainty_correlation=cor) nd4 = nd2.add(nd1, uncertainty_correlation=cor) # Inverse operation should result in the same uncertainty assert_array_equal(nd3.uncertainty.array, nd4.uncertainty.array) # Compare it to the theoretical uncertainty ref_uncertainty = np.sqrt(uncert1**2 + uncert2**2 + 2 * cor * np.abs(uncert1 * uncert2)) assert_array_equal(nd3.uncertainty.array, ref_uncertainty) nd3 = nd1.subtract(nd2, uncertainty_correlation=cor) nd4 = nd2.subtract(nd1, uncertainty_correlation=cor) # Inverse operation should result in the same uncertainty assert_array_equal(nd3.uncertainty.array, nd4.uncertainty.array) # Compare it to the theoretical uncertainty ref_uncertainty = np.sqrt(uncert1**2 + uncert2**2 - 2 * cor * np.abs(uncert1 * uncert2)) assert_array_equal(nd3.uncertainty.array, ref_uncertainty) # Multiplication and Division only work with almost equal array comparisons # since the formula implemented and the formula used as reference are # slightly different. nd3 = nd1.multiply(nd2, uncertainty_correlation=cor) nd4 = nd2.multiply(nd1, uncertainty_correlation=cor) # Inverse operation should result in the same uncertainty assert_array_almost_equal(nd3.uncertainty.array, nd4.uncertainty.array) # Compare it to the theoretical uncertainty ref_uncertainty = (np.abs(data1 * data2)) * np.sqrt( (uncert1 / data1)**2 + (uncert2 / data2)**2 + (2 * cor * np.abs(uncert1 * uncert2) / (data1 * data2))) assert_array_almost_equal(nd3.uncertainty.array, ref_uncertainty) nd3 = nd1.divide(nd2, uncertainty_correlation=cor) nd4 = nd2.divide(nd1, uncertainty_correlation=cor) # Inverse operation gives a different uncertainty! # Compare it to the theoretical uncertainty ref_uncertainty_1 = (np.abs(data1 / data2)) * np.sqrt( (uncert1 / data1)**2 + (uncert2 / data2)**2 - (2 * cor * np.abs(uncert1 * uncert2) / (data1 * data2))) assert_array_almost_equal(nd3.uncertainty.array, ref_uncertainty_1) ref_uncertainty_2 = (np.abs(data2 / data1)) * np.sqrt( (uncert1 / data1)**2 + (uncert2 / data2)**2 - (2 * cor * np.abs(uncert1 * uncert2) / (data1 * data2))) assert_array_almost_equal(nd4.uncertainty.array, ref_uncertainty_2) # Tests for correlation, covering # correlation between -1 and 1 with correlation term being positive / negative # also with one data being once positive and once completely negative # The point of this test is to compare the used formula to the theoretical one. # TODO: Maybe covering units too but I think that should work because of # the next tests. Also this may be reduced somehow. @pytest.mark.parametrize(('cor', 'uncert1', 'data2'), [ (-1, [1, 1, 3], [2, 2, 7]), (-0.5, [1, 1, 3], [2, 2, 7]), (-0.25, [1, 1, 3], [2, 2, 7]), (0, [1, 1, 3], [2, 2, 7]), (0.25, [1, 1, 3], [2, 2, 7]), (0.5, [1, 1, 3], [2, 2, 7]), (1, [1, 1, 3], [2, 2, 7]), (-1, [-1, -1, -3], [2, 2, 7]), (-0.5, [-1, -1, -3], [2, 2, 7]), (-0.25, [-1, -1, -3], [2, 2, 7]), (0, [-1, -1, -3], [2, 2, 7]), (0.25, [-1, -1, -3], [2, 2, 7]), (0.5, [-1, -1, -3], [2, 2, 7]), (1, [-1, -1, -3], [2, 2, 7]), (-1, [1, 1, 3], [-2, -3, -2]), (-0.5, [1, 1, 3], [-2, -3, -2]), (-0.25, [1, 1, 3], [-2, -3, -2]), (0, [1, 1, 3], [-2, -3, -2]), (0.25, [1, 1, 3], [-2, -3, -2]), (0.5, [1, 1, 3], [-2, -3, -2]), (1, [1, 1, 3], [-2, -3, -2]), (-1, [-1, -1, -3], [-2, -3, -2]), (-0.5, [-1, -1, -3], [-2, -3, -2]), (-0.25, [-1, -1, -3], [-2, -3, -2]), (0, [-1, -1, -3], [-2, -3, -2]), (0.25, [-1, -1, -3], [-2, -3, -2]), (0.5, [-1, -1, -3], [-2, -3, -2]), (1, [-1, -1, -3], [-2, -3, -2]), ]) def test_arithmetics_varianceuncertainty_basic_with_correlation( cor, uncert1, data2): data1 = np.array([1, 2, 3]) data2 = np.array(data2) uncert1 = np.array(uncert1)**2 uncert2 = np.array([2, 2, 2])**2 nd1 = NDDataArithmetic(data1, uncertainty=VarianceUncertainty(uncert1)) nd2 = NDDataArithmetic(data2, uncertainty=VarianceUncertainty(uncert2)) nd3 = nd1.add(nd2, uncertainty_correlation=cor) nd4 = nd2.add(nd1, uncertainty_correlation=cor) # Inverse operation should result in the same uncertainty assert_array_equal(nd3.uncertainty.array, nd4.uncertainty.array) # Compare it to the theoretical uncertainty ref_uncertainty = (uncert1 + uncert2 + 2 * cor * np.sqrt(uncert1 * uncert2)) assert_array_equal(nd3.uncertainty.array, ref_uncertainty) nd3 = nd1.subtract(nd2, uncertainty_correlation=cor) nd4 = nd2.subtract(nd1, uncertainty_correlation=cor) # Inverse operation should result in the same uncertainty assert_array_equal(nd3.uncertainty.array, nd4.uncertainty.array) # Compare it to the theoretical uncertainty ref_uncertainty = (uncert1 + uncert2 - 2 * cor * np.sqrt(uncert1 * uncert2)) assert_array_equal(nd3.uncertainty.array, ref_uncertainty) # Multiplication and Division only work with almost equal array comparisons # since the formula implemented and the formula used as reference are # slightly different. nd3 = nd1.multiply(nd2, uncertainty_correlation=cor) nd4 = nd2.multiply(nd1, uncertainty_correlation=cor) # Inverse operation should result in the same uncertainty assert_array_almost_equal(nd3.uncertainty.array, nd4.uncertainty.array) # Compare it to the theoretical uncertainty ref_uncertainty = (data1 * data2)**2 * ( uncert1 / data1**2 + uncert2 / data2**2 + (2 * cor * np.sqrt(uncert1 * uncert2) / (data1 * data2))) assert_array_almost_equal(nd3.uncertainty.array, ref_uncertainty) nd3 = nd1.divide(nd2, uncertainty_correlation=cor) nd4 = nd2.divide(nd1, uncertainty_correlation=cor) # Inverse operation gives a different uncertainty because of the # prefactor nd1/nd2 vs nd2/nd1. Howeveare, a large chunk is the same. ref_common = ( uncert1 / data1**2 + uncert2 / data2**2 - (2 * cor * np.sqrt(uncert1 * uncert2) / (data1 * data2))) # Compare it to the theoretical uncertainty ref_uncertainty_1 = (data1 / data2)**2 * ref_common assert_array_almost_equal(nd3.uncertainty.array, ref_uncertainty_1) ref_uncertainty_2 = (data2 / data1)**2 * ref_common assert_array_almost_equal(nd4.uncertainty.array, ref_uncertainty_2) # Tests for correlation, covering # correlation between -1 and 1 with correlation term being positive / negative # also with one data being once positive and once completely negative # The point of this test is to compare the used formula to the theoretical one. # TODO: Maybe covering units too but I think that should work because of # the next tests. Also this may be reduced somehow. @pytest.mark.filterwarnings("ignore:divide by zero encountered.*") @pytest.mark.parametrize(('cor', 'uncert1', 'data2'), [ (-1, [1, 1, 3], [2, 2, 7]), (-0.5, [1, 1, 3], [2, 2, 7]), (-0.25, [1, 1, 3], [2, 2, 7]), (0, [1, 1, 3], [2, 2, 7]), (0.25, [1, 1, 3], [2, 2, 7]), (0.5, [1, 1, 3], [2, 2, 7]), (1, [1, 1, 3], [2, 2, 7]), (-1, [-1, -1, -3], [2, 2, 7]), (-0.5, [-1, -1, -3], [2, 2, 7]), (-0.25, [-1, -1, -3], [2, 2, 7]), (0, [-1, -1, -3], [2, 2, 7]), (0.25, [-1, -1, -3], [2, 2, 7]), (0.5, [-1, -1, -3], [2, 2, 7]), (1, [-1, -1, -3], [2, 2, 7]), (-1, [1, 1, 3], [-2, -3, -2]), (-0.5, [1, 1, 3], [-2, -3, -2]), (-0.25, [1, 1, 3], [-2, -3, -2]), (0, [1, 1, 3], [-2, -3, -2]), (0.25, [1, 1, 3], [-2, -3, -2]), (0.5, [1, 1, 3], [-2, -3, -2]), (1, [1, 1, 3], [-2, -3, -2]), (-1, [-1, -1, -3], [-2, -3, -2]), (-0.5, [-1, -1, -3], [-2, -3, -2]), (-0.25, [-1, -1, -3], [-2, -3, -2]), (0, [-1, -1, -3], [-2, -3, -2]), (0.25, [-1, -1, -3], [-2, -3, -2]), (0.5, [-1, -1, -3], [-2, -3, -2]), (1, [-1, -1, -3], [-2, -3, -2]), ]) def test_arithmetics_inversevarianceuncertainty_basic_with_correlation( cor, uncert1, data2): data1 = np.array([1, 2, 3]) data2 = np.array(data2) uncert1 = 1 / np.array(uncert1)**2 uncert2 = 1 / np.array([2, 2, 2])**2 nd1 = NDDataArithmetic(data1, uncertainty=InverseVariance(uncert1)) nd2 = NDDataArithmetic(data2, uncertainty=InverseVariance(uncert2)) nd3 = nd1.add(nd2, uncertainty_correlation=cor) nd4 = nd2.add(nd1, uncertainty_correlation=cor) # Inverse operation should result in the same uncertainty assert_array_equal(nd3.uncertainty.array, nd4.uncertainty.array) # Compare it to the theoretical uncertainty ref_uncertainty = 1/ (1 / uncert1 + 1 / uncert2 + 2 * cor / np.sqrt(uncert1 * uncert2)) assert_array_equal(nd3.uncertainty.array, ref_uncertainty) nd3 = nd1.subtract(nd2, uncertainty_correlation=cor) nd4 = nd2.subtract(nd1, uncertainty_correlation=cor) # Inverse operation should result in the same uncertainty assert_array_equal(nd3.uncertainty.array, nd4.uncertainty.array) # Compare it to the theoretical uncertainty ref_uncertainty = 1 / (1 / uncert1 + 1 / uncert2 - 2 * cor / np.sqrt(uncert1 * uncert2)) assert_array_equal(nd3.uncertainty.array, ref_uncertainty) # Multiplication and Division only work with almost equal array comparisons # since the formula implemented and the formula used as reference are # slightly different. nd3 = nd1.multiply(nd2, uncertainty_correlation=cor) nd4 = nd2.multiply(nd1, uncertainty_correlation=cor) # Inverse operation should result in the same uncertainty assert_array_almost_equal(nd3.uncertainty.array, nd4.uncertainty.array) # Compare it to the theoretical uncertainty ref_uncertainty = 1 / ((data1 * data2)**2 * ( 1 / uncert1 / data1**2 + 1 / uncert2 / data2**2 + (2 * cor / np.sqrt(uncert1 * uncert2) / (data1 * data2)))) assert_array_almost_equal(nd3.uncertainty.array, ref_uncertainty) nd3 = nd1.divide(nd2, uncertainty_correlation=cor) nd4 = nd2.divide(nd1, uncertainty_correlation=cor) # Inverse operation gives a different uncertainty because of the # prefactor nd1/nd2 vs nd2/nd1. Howeveare, a large chunk is the same. ref_common = ( 1 / uncert1 / data1**2 + 1 / uncert2 / data2**2 - (2 * cor / np.sqrt(uncert1 * uncert2) / (data1 * data2))) # Compare it to the theoretical uncertainty ref_uncertainty_1 = 1 / ((data1 / data2)**2 * ref_common) assert_array_almost_equal(nd3.uncertainty.array, ref_uncertainty_1) ref_uncertainty_2 = 1 / ((data2 / data1)**2 * ref_common) assert_array_almost_equal(nd4.uncertainty.array, ref_uncertainty_2) # Covering: # just an example that a np.ndarray works as correlation, no checks for # the right result since these were basically done in the function above. def test_arithmetics_stddevuncertainty_basic_with_correlation_array(): data1 = np.array([1, 2, 3]) data2 = np.array([1, 1, 1]) uncert1 = np.array([1, 1, 1]) uncert2 = np.array([2, 2, 2]) cor = np.array([0, 0.25, 0]) nd1 = NDDataArithmetic(data1, uncertainty=StdDevUncertainty(uncert1)) nd2 = NDDataArithmetic(data2, uncertainty=StdDevUncertainty(uncert2)) nd1.add(nd2, uncertainty_correlation=cor) # Covering: # That propagate throws an exception when correlation is given but the # uncertainty does not support correlation. def test_arithmetics_with_correlation_unsupported(): data1 = np.array([1, 2, 3]) data2 = np.array([1, 1, 1]) uncert1 = np.array([1, 1, 1]) uncert2 = np.array([2, 2, 2]) cor = 3 nd1 = NDDataArithmetic(data1, uncertainty=StdDevUncertaintyUncorrelated(uncert1)) nd2 = NDDataArithmetic(data2, uncertainty=StdDevUncertaintyUncorrelated(uncert2)) with pytest.raises(ValueError): nd1.add(nd2, uncertainty_correlation=cor) # Covering: # only one has an uncertainty (data and uncertainty without unit) # tested against the case where the other one has zero uncertainty. (this case # must be correct because we tested it in the last case) # Also verify that if the result of the data has negative values the resulting # uncertainty has no negative values. def test_arithmetics_stddevuncertainty_one_missing(): nd1 = NDDataArithmetic([1, -2, 3]) nd1_ref = NDDataArithmetic([1, -2, 3], uncertainty=StdDevUncertainty([0, 0, 0])) nd2 = NDDataArithmetic([2, 2, -2], uncertainty=StdDevUncertainty([2, 2, 2])) # Addition nd3 = nd1.add(nd2) nd3_ref = nd1_ref.add(nd2) assert_array_equal(nd3.uncertainty.array, nd3_ref.uncertainty.array) assert_array_equal(np.abs(nd3.uncertainty.array), nd3.uncertainty.array) nd3 = nd2.add(nd1) nd3_ref = nd2.add(nd1_ref) assert_array_equal(nd3.uncertainty.array, nd3_ref.uncertainty.array) assert_array_equal(np.abs(nd3.uncertainty.array), nd3.uncertainty.array) # Subtraction nd3 = nd1.subtract(nd2) nd3_ref = nd1_ref.subtract(nd2) assert_array_equal(nd3.uncertainty.array, nd3_ref.uncertainty.array) assert_array_equal(np.abs(nd3.uncertainty.array), nd3.uncertainty.array) nd3 = nd2.subtract(nd1) nd3_ref = nd2.subtract(nd1_ref) assert_array_equal(nd3.uncertainty.array, nd3_ref.uncertainty.array) assert_array_equal(np.abs(nd3.uncertainty.array), nd3.uncertainty.array) # Multiplication nd3 = nd1.multiply(nd2) nd3_ref = nd1_ref.multiply(nd2) assert_array_equal(nd3.uncertainty.array, nd3_ref.uncertainty.array) assert_array_equal(np.abs(nd3.uncertainty.array), nd3.uncertainty.array) nd3 = nd2.multiply(nd1) nd3_ref = nd2.multiply(nd1_ref) assert_array_equal(nd3.uncertainty.array, nd3_ref.uncertainty.array) assert_array_equal(np.abs(nd3.uncertainty.array), nd3.uncertainty.array) # Division nd3 = nd1.divide(nd2) nd3_ref = nd1_ref.divide(nd2) assert_array_equal(nd3.uncertainty.array, nd3_ref.uncertainty.array) assert_array_equal(np.abs(nd3.uncertainty.array), nd3.uncertainty.array) nd3 = nd2.divide(nd1) nd3_ref = nd2.divide(nd1_ref) assert_array_equal(nd3.uncertainty.array, nd3_ref.uncertainty.array) assert_array_equal(np.abs(nd3.uncertainty.array), nd3.uncertainty.array) # Covering: # data with unit and uncertainty with unit (but equivalent units) # compared against correctly scaled NDDatas @pytest.mark.filterwarnings("ignore:.*encountered in.*divide.*") @pytest.mark.parametrize(('uncert1', 'uncert2'), [ (np.array([1, 2, 3]) * u.m, None), (np.array([1, 2, 3]) * u.cm, None), (None, np.array([1, 2, 3]) * u.m), (None, np.array([1, 2, 3]) * u.cm), (np.array([1, 2, 3]), np.array([2, 3, 4])), (np.array([1, 2, 3]) * u.m, np.array([2, 3, 4])), (np.array([1, 2, 3]), np.array([2, 3, 4])) * u.m, (np.array([1, 2, 3]) * u.m, np.array([2, 3, 4])) * u.m, (np.array([1, 2, 3]) * u.cm, np.array([2, 3, 4])), (np.array([1, 2, 3]), np.array([2, 3, 4])) * u.cm, (np.array([1, 2, 3]) * u.cm, np.array([2, 3, 4])) * u.cm, (np.array([1, 2, 3]) * u.km, np.array([2, 3, 4])) * u.cm, ]) def test_arithmetics_stddevuncertainty_with_units(uncert1, uncert2): # Data has same units data1 = np.array([1, 2, 3]) * u.m data2 = np.array([-4, 7, 0]) * u.m if uncert1 is not None: uncert1 = StdDevUncertainty(uncert1) if isinstance(uncert1, Quantity): uncert1_ref = uncert1.to_value(data1.unit) else: uncert1_ref = uncert1 uncert_ref1 = StdDevUncertainty(uncert1_ref, copy=True) else: uncert1 = None uncert_ref1 = None if uncert2 is not None: uncert2 = StdDevUncertainty(uncert2) if isinstance(uncert2, Quantity): uncert2_ref = uncert2.to_value(data2.unit) else: uncert2_ref = uncert2 uncert_ref2 = StdDevUncertainty(uncert2_ref, copy=True) else: uncert2 = None uncert_ref2 = None nd1 = NDDataArithmetic(data1, uncertainty=uncert1) nd2 = NDDataArithmetic(data2, uncertainty=uncert2) nd1_ref = NDDataArithmetic(data1, uncertainty=uncert_ref1) nd2_ref = NDDataArithmetic(data2, uncertainty=uncert_ref2) # Let's start the tests # Addition nd3 = nd1.add(nd2) nd3_ref = nd1_ref.add(nd2_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) nd3 = nd2.add(nd1) nd3_ref = nd2_ref.add(nd1_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) # Subtraction nd3 = nd1.subtract(nd2) nd3_ref = nd1_ref.subtract(nd2_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) nd3 = nd2.subtract(nd1) nd3_ref = nd2_ref.subtract(nd1_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) # Multiplication nd3 = nd1.multiply(nd2) nd3_ref = nd1_ref.multiply(nd2_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) nd3 = nd2.multiply(nd1) nd3_ref = nd2_ref.multiply(nd1_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) # Division nd3 = nd1.divide(nd2) nd3_ref = nd1_ref.divide(nd2_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) nd3 = nd2.divide(nd1) nd3_ref = nd2_ref.divide(nd1_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) # Covering: # data with unit and uncertainty with unit (but equivalent units) # compared against correctly scaled NDDatas @pytest.mark.filterwarnings("ignore:.*encountered in.*divide.*") @pytest.mark.parametrize(('uncert1', 'uncert2'), [ (np.array([1, 2, 3]) * u.m, None), (np.array([1, 2, 3]) * u.cm, None), (None, np.array([1, 2, 3]) * u.m), (None, np.array([1, 2, 3]) * u.cm), (np.array([1, 2, 3]), np.array([2, 3, 4])), (np.array([1, 2, 3]) * u.m, np.array([2, 3, 4])), (np.array([1, 2, 3]), np.array([2, 3, 4])) * u.m, (np.array([1, 2, 3]) * u.m, np.array([2, 3, 4])) * u.m, (np.array([1, 2, 3]) * u.cm, np.array([2, 3, 4])), (np.array([1, 2, 3]), np.array([2, 3, 4])) * u.cm, (np.array([1, 2, 3]) * u.cm, np.array([2, 3, 4])) * u.cm, (np.array([1, 2, 3]) * u.km, np.array([2, 3, 4])) * u.cm, ]) def test_arithmetics_varianceuncertainty_with_units(uncert1, uncert2): # Data has same units data1 = np.array([1, 2, 3]) * u.m data2 = np.array([-4, 7, 0]) * u.m if uncert1 is not None: uncert1 = VarianceUncertainty(uncert1**2) if isinstance(uncert1, Quantity): uncert1_ref = uncert1.to_value(data1.unit**2) else: uncert1_ref = uncert1 uncert_ref1 = VarianceUncertainty(uncert1_ref, copy=True) else: uncert1 = None uncert_ref1 = None if uncert2 is not None: uncert2 = VarianceUncertainty(uncert2**2) if isinstance(uncert2, Quantity): uncert2_ref = uncert2.to_value(data2.unit**2) else: uncert2_ref = uncert2 uncert_ref2 = VarianceUncertainty(uncert2_ref, copy=True) else: uncert2 = None uncert_ref2 = None nd1 = NDDataArithmetic(data1, uncertainty=uncert1) nd2 = NDDataArithmetic(data2, uncertainty=uncert2) nd1_ref = NDDataArithmetic(data1, uncertainty=uncert_ref1) nd2_ref = NDDataArithmetic(data2, uncertainty=uncert_ref2) # Let's start the tests # Addition nd3 = nd1.add(nd2) nd3_ref = nd1_ref.add(nd2_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) nd3 = nd2.add(nd1) nd3_ref = nd2_ref.add(nd1_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) # Subtraction nd3 = nd1.subtract(nd2) nd3_ref = nd1_ref.subtract(nd2_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) nd3 = nd2.subtract(nd1) nd3_ref = nd2_ref.subtract(nd1_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) # Multiplication nd3 = nd1.multiply(nd2) nd3_ref = nd1_ref.multiply(nd2_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) nd3 = nd2.multiply(nd1) nd3_ref = nd2_ref.multiply(nd1_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) # Division nd3 = nd1.divide(nd2) nd3_ref = nd1_ref.divide(nd2_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) nd3 = nd2.divide(nd1) nd3_ref = nd2_ref.divide(nd1_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) # Covering: # data with unit and uncertainty with unit (but equivalent units) # compared against correctly scaled NDDatas @pytest.mark.filterwarnings("ignore:.*encountered in.*divide.*") @pytest.mark.parametrize(('uncert1', 'uncert2'), [ (np.array([1, 2, 3]) * u.m, None), (np.array([1, 2, 3]) * u.cm, None), (None, np.array([1, 2, 3]) * u.m), (None, np.array([1, 2, 3]) * u.cm), (np.array([1, 2, 3]), np.array([2, 3, 4])), (np.array([1, 2, 3]) * u.m, np.array([2, 3, 4])), (np.array([1, 2, 3]), np.array([2, 3, 4])) * u.m, (np.array([1, 2, 3]) * u.m, np.array([2, 3, 4])) * u.m, (np.array([1, 2, 3]) * u.cm, np.array([2, 3, 4])), (np.array([1, 2, 3]), np.array([2, 3, 4])) * u.cm, (np.array([1, 2, 3]) * u.cm, np.array([2, 3, 4])) * u.cm, (np.array([1, 2, 3]) * u.km, np.array([2, 3, 4])) * u.cm, ]) def test_arithmetics_inversevarianceuncertainty_with_units(uncert1, uncert2): # Data has same units data1 = np.array([1, 2, 3]) * u.m data2 = np.array([-4, 7, 0]) * u.m if uncert1 is not None: uncert1 = InverseVariance(1 / uncert1**2) if isinstance(uncert1, Quantity): uncert1_ref = uncert1.to_value(1 / data1.unit**2) else: uncert1_ref = uncert1 uncert_ref1 = InverseVariance(uncert1_ref, copy=True) else: uncert1 = None uncert_ref1 = None if uncert2 is not None: uncert2 = InverseVariance(1 / uncert2**2) if isinstance(uncert2, Quantity): uncert2_ref = uncert2.to_value(1 / data2.unit**2) else: uncert2_ref = uncert2 uncert_ref2 = InverseVariance(uncert2_ref, copy=True) else: uncert2 = None uncert_ref2 = None nd1 = NDDataArithmetic(data1, uncertainty=uncert1) nd2 = NDDataArithmetic(data2, uncertainty=uncert2) nd1_ref = NDDataArithmetic(data1, uncertainty=uncert_ref1) nd2_ref = NDDataArithmetic(data2, uncertainty=uncert_ref2) # Let's start the tests # Addition nd3 = nd1.add(nd2) nd3_ref = nd1_ref.add(nd2_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) nd3 = nd2.add(nd1) nd3_ref = nd2_ref.add(nd1_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) # Subtraction nd3 = nd1.subtract(nd2) nd3_ref = nd1_ref.subtract(nd2_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) nd3 = nd2.subtract(nd1) nd3_ref = nd2_ref.subtract(nd1_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) # Multiplication nd3 = nd1.multiply(nd2) nd3_ref = nd1_ref.multiply(nd2_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) nd3 = nd2.multiply(nd1) nd3_ref = nd2_ref.multiply(nd1_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) # Division nd3 = nd1.divide(nd2) nd3_ref = nd1_ref.divide(nd2_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) nd3 = nd2.divide(nd1) nd3_ref = nd2_ref.divide(nd1_ref) assert nd3.unit == nd3_ref.unit assert nd3.uncertainty.unit == nd3_ref.uncertainty.unit assert_array_equal(nd3.uncertainty.array, nd3.uncertainty.array) # Test abbreviation and long name for taking the first found meta, mask, wcs @pytest.mark.parametrize(('use_abbreviation'), ['ff', 'first_found']) def test_arithmetics_handle_switches(use_abbreviation): meta1 = {'a': 1} meta2 = {'b': 2} mask1 = True mask2 = False uncertainty1 = StdDevUncertainty([1, 2, 3]) uncertainty2 = StdDevUncertainty([1, 2, 3]) wcs1, wcs2 = nd_testing.create_two_unequal_wcs(naxis=1) data1 = [1, 1, 1] data2 = [1, 1, 1] nd1 = NDDataArithmetic(data1, meta=meta1, mask=mask1, wcs=wcs1, uncertainty=uncertainty1) nd2 = NDDataArithmetic(data2, meta=meta2, mask=mask2, wcs=wcs2, uncertainty=uncertainty2) nd3 = NDDataArithmetic(data1) # Both have the attributes but option None is chosen nd_ = nd1.add(nd2, propagate_uncertainties=None, handle_meta=None, handle_mask=None, compare_wcs=None) assert nd_.wcs is None assert len(nd_.meta) == 0 assert nd_.mask is None assert nd_.uncertainty is None # Only second has attributes and False is chosen nd_ = nd3.add(nd2, propagate_uncertainties=False, handle_meta=use_abbreviation, handle_mask=use_abbreviation, compare_wcs=use_abbreviation) nd_testing.assert_wcs_seem_equal(nd_.wcs, wcs2) assert nd_.meta == meta2 assert nd_.mask == mask2 assert_array_equal(nd_.uncertainty.array, uncertainty2.array) # Only first has attributes and False is chosen nd_ = nd1.add(nd3, propagate_uncertainties=False, handle_meta=use_abbreviation, handle_mask=use_abbreviation, compare_wcs=use_abbreviation) nd_testing.assert_wcs_seem_equal(nd_.wcs, wcs1) assert nd_.meta == meta1 assert nd_.mask == mask1 assert_array_equal(nd_.uncertainty.array, uncertainty1.array) def test_arithmetics_meta_func(): def meta_fun_func(meta1, meta2, take='first'): if take == 'first': return meta1 else: return meta2 meta1 = {'a': 1} meta2 = {'a': 3, 'b': 2} mask1 = True mask2 = False uncertainty1 = StdDevUncertainty([1, 2, 3]) uncertainty2 = StdDevUncertainty([1, 2, 3]) data1 = [1, 1, 1] data2 = [1, 1, 1] nd1 = NDDataArithmetic(data1, meta=meta1, mask=mask1, uncertainty=uncertainty1) nd2 = NDDataArithmetic(data2, meta=meta2, mask=mask2, uncertainty=uncertainty2) nd3 = nd1.add(nd2, handle_meta=meta_fun_func) assert nd3.meta['a'] == 1 assert 'b' not in nd3.meta nd4 = nd1.add(nd2, handle_meta=meta_fun_func, meta_take='second') assert nd4.meta['a'] == 3 assert nd4.meta['b'] == 2 with pytest.raises(KeyError): nd1.add(nd2, handle_meta=meta_fun_func, take='second') def test_arithmetics_wcs_func(): def wcs_comp_func(wcs1, wcs2, tolerance=0.1): if tolerance < 0.01: return False return True meta1 = {'a': 1} meta2 = {'a': 3, 'b': 2} mask1 = True mask2 = False uncertainty1 = StdDevUncertainty([1, 2, 3]) uncertainty2 = StdDevUncertainty([1, 2, 3]) wcs1, wcs2 = nd_testing.create_two_equal_wcs(naxis=1) data1 = [1, 1, 1] data2 = [1, 1, 1] nd1 = NDDataArithmetic(data1, meta=meta1, mask=mask1, wcs=wcs1, uncertainty=uncertainty1) nd2 = NDDataArithmetic(data2, meta=meta2, mask=mask2, wcs=wcs2, uncertainty=uncertainty2) nd3 = nd1.add(nd2, compare_wcs=wcs_comp_func) nd_testing.assert_wcs_seem_equal(nd3.wcs, wcs1) # Fails because the function fails with pytest.raises(ValueError): nd1.add(nd2, compare_wcs=wcs_comp_func, wcs_tolerance=0.00001) # Fails because for a parameter to be passed correctly to the function it # needs the wcs_ prefix with pytest.raises(KeyError): nd1.add(nd2, compare_wcs=wcs_comp_func, tolerance=1) def test_arithmetics_mask_func(): def mask_sad_func(mask1, mask2, fun=0): if fun > 0.5: return mask2 else: return mask1 meta1 = {'a': 1} meta2 = {'a': 3, 'b': 2} mask1 = [True, False, True] mask2 = [True, False, False] uncertainty1 = StdDevUncertainty([1, 2, 3]) uncertainty2 = StdDevUncertainty([1, 2, 3]) data1 = [1, 1, 1] data2 = [1, 1, 1] nd1 = NDDataArithmetic(data1, meta=meta1, mask=mask1, uncertainty=uncertainty1) nd2 = NDDataArithmetic(data2, meta=meta2, mask=mask2, uncertainty=uncertainty2) nd3 = nd1.add(nd2, handle_mask=mask_sad_func) assert_array_equal(nd3.mask, nd1.mask) nd4 = nd1.add(nd2, handle_mask=mask_sad_func, mask_fun=1) assert_array_equal(nd4.mask, nd2.mask) with pytest.raises(KeyError): nd1.add(nd2, handle_mask=mask_sad_func, fun=1) @pytest.mark.parametrize('meth', ['add', 'subtract', 'divide', 'multiply']) def test_two_argument_useage(meth): ndd1 = NDDataArithmetic(np.ones((3, 3))) ndd2 = NDDataArithmetic(np.ones((3, 3))) # Call add on the class (not the instance) and compare it with already # tested useage: ndd3 = getattr(NDDataArithmetic, meth)(ndd1, ndd2) ndd4 = getattr(ndd1, meth)(ndd2) np.testing.assert_array_equal(ndd3.data, ndd4.data) # And the same done on an unrelated instance... ndd3 = getattr(NDDataArithmetic(-100), meth)(ndd1, ndd2) ndd4 = getattr(ndd1, meth)(ndd2) np.testing.assert_array_equal(ndd3.data, ndd4.data) @pytest.mark.parametrize('meth', ['add', 'subtract', 'divide', 'multiply']) def test_two_argument_useage_non_nddata_first_arg(meth): data1 = 50 data2 = 100 # Call add on the class (not the instance) ndd3 = getattr(NDDataArithmetic, meth)(data1, data2) # Compare it with the instance-useage and two identical NDData-like # classes: ndd1 = NDDataArithmetic(data1) ndd2 = NDDataArithmetic(data2) ndd4 = getattr(ndd1, meth)(ndd2) np.testing.assert_array_equal(ndd3.data, ndd4.data) # and check it's also working when called on an instance ndd3 = getattr(NDDataArithmetic(-100), meth)(data1, data2) ndd4 = getattr(ndd1, meth)(ndd2) np.testing.assert_array_equal(ndd3.data, ndd4.data) def test_arithmetics_unknown_uncertainties(): # Not giving any uncertainty class means it is saved as UnknownUncertainty ndd1 = NDDataArithmetic(np.ones((3, 3)), uncertainty=UnknownUncertainty(np.ones((3, 3)))) ndd2 = NDDataArithmetic(np.ones((3, 3)), uncertainty=UnknownUncertainty(np.ones((3, 3))*2)) # There is no way to propagate uncertainties: with pytest.raises(IncompatibleUncertaintiesException): ndd1.add(ndd2) # But it should be possible without propagation ndd3 = ndd1.add(ndd2, propagate_uncertainties=False) np.testing.assert_array_equal(ndd1.uncertainty.array, ndd3.uncertainty.array) ndd4 = ndd1.add(ndd2, propagate_uncertainties=None) assert ndd4.uncertainty is None
de94b1db80ad8429fddb4672df0855272bb5eb80da00b8dafbf0ca63969595cf
from .low_level_api import * # noqa from .high_level_api import * # noqa from .high_level_wcs_wrapper import * # noqa from .utils import * # noqa from .wrappers import * # noqa
a68bd650c3bf50b60a66081b1ee19a33fac50245db1925dd2d2608a3da64d89d
import pytest import numpy as np from astropy.coordinates import SkyCoord from astropy.units import Quantity from astropy.wcs import WCS from astropy.wcs.wcsapi import BaseLowLevelWCS # NOTE: This module is deprecated and is emitting warning. collect_ignore = ['sliced_low_level_wcs.py'] @pytest.fixture def spectral_1d_fitswcs(): wcs = WCS(naxis=1) wcs.wcs.ctype = 'FREQ', wcs.wcs.cunit = 'Hz', wcs.wcs.cdelt = 3.e9, wcs.wcs.crval = 4.e9, wcs.wcs.crpix = 11., wcs.wcs.cname = 'Frequency', return wcs @pytest.fixture def time_1d_fitswcs(): wcs = WCS(naxis=1) wcs.wcs.ctype = 'TIME', wcs.wcs.mjdref = (30042, 0) wcs.wcs.crval = 3., wcs.wcs.crpix = 11., wcs.wcs.cname = 'Time', wcs.wcs.cunit = 's' return wcs @pytest.fixture def celestial_2d_fitswcs(): wcs = WCS(naxis=2) wcs.wcs.ctype = 'RA---CAR', 'DEC--CAR' wcs.wcs.cunit = 'deg', 'deg' wcs.wcs.cdelt = -2., 2. wcs.wcs.crval = 4., 0. wcs.wcs.crpix = 6., 7. wcs.wcs.cname = 'Right Ascension', 'Declination' wcs.pixel_shape = (6, 7) wcs.pixel_bounds = [(-1, 5), (1, 7)] return wcs @pytest.fixture def spectral_cube_3d_fitswcs(): wcs = WCS(naxis=3) wcs.wcs.ctype = 'RA---CAR', 'DEC--CAR', 'FREQ' wcs.wcs.cunit = 'deg', 'deg', 'Hz' wcs.wcs.cdelt = -2., 2., 3.e9 wcs.wcs.crval = 4., 0., 4.e9 wcs.wcs.crpix = 6., 7., 11. wcs.wcs.cname = 'Right Ascension', 'Declination', 'Frequency' wcs.pixel_shape = (6, 7, 3) wcs.pixel_bounds = [(-1, 5), (1, 7), (1, 2.5)] return wcs @pytest.fixture def cube_4d_fitswcs(): wcs = WCS(naxis=4) wcs.wcs.ctype = 'RA---CAR', 'DEC--CAR', 'FREQ', 'TIME' wcs.wcs.cunit = 'deg', 'deg', 'Hz', 's' wcs.wcs.cdelt = -2., 2., 3.e9, 1 wcs.wcs.crval = 4., 0., 4.e9, 3, wcs.wcs.crpix = 6., 7., 11., 11. wcs.wcs.cname = 'Right Ascension', 'Declination', 'Frequency', 'Time' wcs.wcs.mjdref = (30042, 0) return wcs class Spectral1DLowLevelWCS(BaseLowLevelWCS): @property def pixel_n_dim(self): return 1 @property def world_n_dim(self): return 1 @property def world_axis_physical_types(self): return 'em.freq', @property def world_axis_units(self): return 'Hz', @property def world_axis_names(self): return 'Frequency', _pixel_shape = None @property def pixel_shape(self): return self._pixel_shape @pixel_shape.setter def pixel_shape(self, value): self._pixel_shape = value _pixel_bounds = None @property def pixel_bounds(self): return self._pixel_bounds @pixel_bounds.setter def pixel_bounds(self, value): self._pixel_bounds = value def pixel_to_world_values(self, pixel_array): return np.asarray(pixel_array - 10) * 3e9 + 4e9 def world_to_pixel_values(self, world_array): return np.asarray(world_array - 4e9) / 3e9 + 10 @property def world_axis_object_components(self): return ('test', 0, 'value'), @property def world_axis_object_classes(self): return {'test': (Quantity, (), {'unit': 'Hz'})} @pytest.fixture def spectral_1d_ape14_wcs(): return Spectral1DLowLevelWCS() class Celestial2DLowLevelWCS(BaseLowLevelWCS): @property def pixel_n_dim(self): return 2 @property def world_n_dim(self): return 2 @property def world_axis_physical_types(self): return 'pos.eq.ra', 'pos.eq.dec' @property def world_axis_units(self): return 'deg', 'deg' @property def world_axis_names(self): return 'Right Ascension', 'Declination' @property def pixel_shape(self): return (6, 7) @property def pixel_bounds(self): return (-1, 5), (1, 7) def pixel_to_world_values(self, px, py): return (-(np.asarray(px) - 5.) * 2 + 4., (np.asarray(py) - 6.) * 2) def world_to_pixel_values(self, wx, wy): return (-(np.asarray(wx) - 4.) / 2 + 5., np.asarray(wy) / 2 + 6.) @property def world_axis_object_components(self): return [('test', 0, 'spherical.lon.degree'), ('test', 1, 'spherical.lat.degree')] @property def world_axis_object_classes(self): return {'test': (SkyCoord, (), {'unit': 'deg'})} @pytest.fixture def celestial_2d_ape14_wcs(): return Celestial2DLowLevelWCS()
913d096cb94a35d01b4c3d16cc730efa579c0d3d1ef7cf24fd6b2c6bd3627749
from .high_level_api import HighLevelWCSMixin from .low_level_api import BaseLowLevelWCS from .utils import wcs_info_str __all__ = ['HighLevelWCSWrapper'] class HighLevelWCSWrapper(HighLevelWCSMixin): """ Wrapper class that can take any :class:`~astropy.wcs.wcsapi.BaseLowLevelWCS` object and expose the high-level WCS API. """ def __init__(self, low_level_wcs): if not isinstance(low_level_wcs, BaseLowLevelWCS): raise TypeError('Input to a HighLevelWCSWrapper must be a low level WCS object') self._low_level_wcs = low_level_wcs @property def low_level_wcs(self): return self._low_level_wcs @property def pixel_n_dim(self): """ See `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_n_dim` """ return self.low_level_wcs.pixel_n_dim @property def world_n_dim(self): """ See `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_n_dim` """ return self.low_level_wcs.world_n_dim @property def world_axis_physical_types(self): """ See `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_axis_physical_types` """ return self.low_level_wcs.world_axis_physical_types @property def world_axis_units(self): """ See `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_axis_units` """ return self.low_level_wcs.world_axis_units @property def array_shape(self): """ See `~astropy.wcs.wcsapi.BaseLowLevelWCS.array_shape` """ return self.low_level_wcs.array_shape @property def pixel_bounds(self): """ See `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_bounds` """ return self.low_level_wcs.pixel_bounds @property def axis_correlation_matrix(self): """ See `~astropy.wcs.wcsapi.BaseLowLevelWCS.axis_correlation_matrix` """ return self.low_level_wcs.axis_correlation_matrix def _as_mpl_axes(self): """ See `~astropy.wcs.wcsapi.BaseLowLevelWCS._as_mpl_axes` """ return self.low_level_wcs._as_mpl_axes() def __str__(self): return wcs_info_str(self.low_level_wcs) def __repr__(self): return f"{object.__repr__(self)}\n{str(self)}"
edfef4e0c07d4b443660cae5bc56b447395a00c866c3cef966d4697cea73abdd
import os import abc import numpy as np __all__ = ['BaseLowLevelWCS', 'validate_physical_types'] class BaseLowLevelWCS(metaclass=abc.ABCMeta): """ Abstract base class for the low-level WCS interface. This is described in `APE 14: A shared Python interface for World Coordinate Systems <https://doi.org/10.5281/zenodo.1188875>`_. """ @property @abc.abstractmethod def pixel_n_dim(self): """ The number of axes in the pixel coordinate system. """ @property @abc.abstractmethod def world_n_dim(self): """ The number of axes in the world coordinate system. """ @property @abc.abstractmethod def world_axis_physical_types(self): """ An iterable of strings describing the physical type for each world axis. These should be names from the VO UCD1+ controlled Vocabulary (http://www.ivoa.net/documents/latest/UCDlist.html). If no matching UCD type exists, this can instead be ``"custom:xxx"``, where ``xxx`` is an arbitrary string. Alternatively, if the physical type is unknown/undefined, an element can be `None`. """ @property @abc.abstractmethod def world_axis_units(self): """ An iterable of strings given the units of the world coordinates for each axis. The strings should follow the `IVOA VOUnit standard <http://ivoa.net/documents/VOUnits/>`_ (though as noted in the VOUnit specification document, units that do not follow this standard are still allowed, but just not recommended). """ @abc.abstractmethod def pixel_to_world_values(self, *pixel_arrays): """ Convert pixel coordinates to world coordinates. This method takes `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` scalars or arrays as input, and pixel coordinates should be zero-based. Returns `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_n_dim` scalars or arrays in units given by `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_axis_units`. Note that pixel coordinates are assumed to be 0 at the center of the first pixel in each dimension. If a pixel is in a region where the WCS is not defined, NaN can be returned. The coordinates should be specified in the ``(x, y)`` order, where for an image, ``x`` is the horizontal coordinate and ``y`` is the vertical coordinate. If `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_n_dim` is ``1``, this method returns a single scalar or array, otherwise a tuple of scalars or arrays is returned. """ def array_index_to_world_values(self, *index_arrays): """ Convert array indices to world coordinates. This is the same as `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_to_world_values` except that the indices should be given in ``(i, j)`` order, where for an image ``i`` is the row and ``j`` is the column (i.e. the opposite order to `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_to_world_values`). If `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_n_dim` is ``1``, this method returns a single scalar or array, otherwise a tuple of scalars or arrays is returned. """ return self.pixel_to_world_values(*index_arrays[::-1]) @abc.abstractmethod def world_to_pixel_values(self, *world_arrays): """ Convert world coordinates to pixel coordinates. This method takes `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_n_dim` scalars or arrays as input in units given by `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_axis_units`. Returns `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` scalars or arrays. Note that pixel coordinates are assumed to be 0 at the center of the first pixel in each dimension. If a world coordinate does not have a matching pixel coordinate, NaN can be returned. The coordinates should be returned in the ``(x, y)`` order, where for an image, ``x`` is the horizontal coordinate and ``y`` is the vertical coordinate. If `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` is ``1``, this method returns a single scalar or array, otherwise a tuple of scalars or arrays is returned. """ def world_to_array_index_values(self, *world_arrays): """ Convert world coordinates to array indices. This is the same as `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_to_pixel_values` except that the indices should be returned in ``(i, j)`` order, where for an image ``i`` is the row and ``j`` is the column (i.e. the opposite order to `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_to_world_values`). The indices should be returned as rounded integers. If `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` is ``1``, this method returns a single scalar or array, otherwise a tuple of scalars or arrays is returned. """ pixel_arrays = self.world_to_pixel_values(*world_arrays) if self.pixel_n_dim == 1: pixel_arrays = (pixel_arrays,) else: pixel_arrays = pixel_arrays[::-1] array_indices = tuple(np.asarray(np.floor(pixel + 0.5), dtype=np.int_) for pixel in pixel_arrays) return array_indices[0] if self.pixel_n_dim == 1 else array_indices @property @abc.abstractmethod def world_axis_object_components(self): """ A list with `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_n_dim` elements giving information on constructing high-level objects for the world coordinates. Each element of the list is a tuple with three items: * The first is a name for the world object this world array corresponds to, which *must* match the string names used in `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_axis_object_classes`. Note that names might appear twice because two world arrays might correspond to a single world object (e.g. a celestial coordinate might have both “ra” and “dec” arrays, which correspond to a single sky coordinate object). * The second element is either a string keyword argument name or a positional index for the corresponding class from `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_axis_object_classes`. * The third argument is a string giving the name of the property to access on the corresponding class from `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_axis_object_classes` in order to get numerical values. Alternatively, this argument can be a callable Python object that takes a high-level coordinate object and returns the numerical values suitable for passing to the low-level WCS transformation methods. See the document `APE 14: A shared Python interface for World Coordinate Systems <https://doi.org/10.5281/zenodo.1188875>`_ for examples. """ @property @abc.abstractmethod def world_axis_object_classes(self): """ A dictionary giving information on constructing high-level objects for the world coordinates. Each key of the dictionary is a string key from `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_axis_object_components`, and each value is a tuple with three elements or four elements: * The first element of the tuple must be a class or a string specifying the fully-qualified name of a class, which will specify the actual Python object to be created. * The second element, should be a tuple specifying the positional arguments required to initialize the class. If `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_axis_object_components` specifies that the world coordinates should be passed as a positional argument, this this tuple should include `None` placeholders for the world coordinates. * The third tuple element must be a dictionary with the keyword arguments required to initialize the class. * Optionally, for advanced use cases, the fourth element (if present) should be a callable Python object that gets called instead of the class and gets passed the positional and keyword arguments. It should return an object of the type of the first element in the tuple. Note that we don't require the classes to be Astropy classes since there is no guarantee that Astropy will have all the classes to represent all kinds of world coordinates. Furthermore, we recommend that the output be kept as human-readable as possible. The classes used here should have the ability to do conversions by passing an instance as the first argument to the same class with different arguments (e.g. ``Time(Time(...), scale='tai')``). This is a requirement for the implementation of the high-level interface. The second and third tuple elements for each value of this dictionary can in turn contain either instances of classes, or if necessary can contain serialized versions that should take the same form as the main classes described above (a tuple with three elements with the fully qualified name of the class, then the positional arguments and the keyword arguments). For low-level API objects implemented in Python, we recommend simply returning the actual objects (not the serialized form) for optimal performance. Implementations should either always or never use serialized classes to represent Python objects, and should indicate which of these they follow using the `~astropy.wcs.wcsapi.BaseLowLevelWCS.serialized_classes` attribute. See the document `APE 14: A shared Python interface for World Coordinate Systems <https://doi.org/10.5281/zenodo.1188875>`_ for examples . """ # The following three properties have default fallback implementations, so # they are not abstract. @property def array_shape(self): """ The shape of the data that the WCS applies to as a tuple of length `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` in ``(row, column)`` order (the convention for arrays in Python). If the WCS is valid in the context of a dataset with a particular shape, then this property can be used to store the shape of the data. This can be used for example if implementing slicing of WCS objects. This is an optional property, and it should return `None` if a shape is not known or relevant. """ if self.pixel_shape is None: return None else: return self.pixel_shape[::-1] @property def pixel_shape(self): """ The shape of the data that the WCS applies to as a tuple of length `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` in ``(x, y)`` order (where for an image, ``x`` is the horizontal coordinate and ``y`` is the vertical coordinate). If the WCS is valid in the context of a dataset with a particular shape, then this property can be used to store the shape of the data. This can be used for example if implementing slicing of WCS objects. This is an optional property, and it should return `None` if a shape is not known or relevant. If you are interested in getting a shape that is comparable to that of a Numpy array, you should use `~astropy.wcs.wcsapi.BaseLowLevelWCS.array_shape` instead. """ return None @property def pixel_bounds(self): """ The bounds (in pixel coordinates) inside which the WCS is defined, as a list with `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` ``(min, max)`` tuples. The bounds should be given in ``[(xmin, xmax), (ymin, ymax)]`` order. WCS solutions are sometimes only guaranteed to be accurate within a certain range of pixel values, for example when defining a WCS that includes fitted distortions. This is an optional property, and it should return `None` if a shape is not known or relevant. """ return None @property def pixel_axis_names(self): """ An iterable of strings describing the name for each pixel axis. If an axis does not have a name, an empty string should be returned (this is the default behavior for all axes if a subclass does not override this property). Note that these names are just for display purposes and are not standardized. """ return [''] * self.pixel_n_dim @property def world_axis_names(self): """ An iterable of strings describing the name for each world axis. If an axis does not have a name, an empty string should be returned (this is the default behavior for all axes if a subclass does not override this property). Note that these names are just for display purposes and are not standardized. For standardized axis types, see `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_axis_physical_types`. """ return [''] * self.world_n_dim @property def axis_correlation_matrix(self): """ Returns an (`~astropy.wcs.wcsapi.BaseLowLevelWCS.world_n_dim`, `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim`) matrix that indicates using booleans whether a given world coordinate depends on a given pixel coordinate. This defaults to a matrix where all elements are `True` in the absence of any further information. For completely independent axes, the diagonal would be `True` and all other entries `False`. """ return np.ones((self.world_n_dim, self.pixel_n_dim), dtype=bool) @property def serialized_classes(self): """ Indicates whether Python objects are given in serialized form or as actual Python objects. """ return False def _as_mpl_axes(self): """ Compatibility hook for Matplotlib and WCSAxes. With this method, one can do:: from astropy.wcs import WCS import matplotlib.pyplot as plt wcs = WCS('filename.fits') fig = plt.figure() ax = fig.add_axes([0.15, 0.1, 0.8, 0.8], projection=wcs) ... and this will generate a plot with the correct WCS coordinates on the axes. """ from astropy.visualization.wcsaxes import WCSAxes return WCSAxes, {'wcs': self} UCDS_FILE = os.path.join(os.path.dirname(__file__), 'data', 'ucds.txt') with open(UCDS_FILE) as f: VALID_UCDS = set([x.strip() for x in f.read().splitlines()[1:]]) def validate_physical_types(physical_types): """ Validate a list of physical types against the UCD1+ standard """ for physical_type in physical_types: if (physical_type is not None and physical_type not in VALID_UCDS and not physical_type.startswith('custom:')): raise ValueError( f"'{physical_type}' is not a valid IOVA UCD1+ physical type. " "It must be a string specified in the list (http://www.ivoa.net/documents/latest/UCDlist.html) " "or if no matching type exists it can be any string prepended with 'custom:'." )
eed895577ca5b208195b6c6e64ef7507317a8d88dfe2e043a25cf8b4c5fa1f60
# Licensed under a 3-clause BSD style license - see LICENSE.rst import importlib import numpy as np __all__ = ['deserialize_class', 'wcs_info_str'] def deserialize_class(tpl, construct=True): """ Deserialize classes recursively. """ if not isinstance(tpl, tuple) or len(tpl) != 3: raise ValueError("Expected a tuple of three values") module, klass = tpl[0].rsplit('.', 1) module = importlib.import_module(module) klass = getattr(module, klass) args = tuple([deserialize_class(arg) if isinstance(arg, tuple) else arg for arg in tpl[1]]) kwargs = dict((key, deserialize_class(val)) if isinstance(val, tuple) else (key, val) for (key, val) in tpl[2].items()) if construct: return klass(*args, **kwargs) else: return klass, args, kwargs def wcs_info_str(wcs): # Overall header s = f'{wcs.__class__.__name__} Transformation\n\n' s += ('This transformation has {} pixel and {} world dimensions\n\n' .format(wcs.pixel_n_dim, wcs.world_n_dim)) s += f'Array shape (Numpy order): {wcs.array_shape}\n\n' # Pixel dimensions table array_shape = wcs.array_shape or (0,) pixel_shape = wcs.pixel_shape or (None,) * wcs.pixel_n_dim # Find largest between header size and value length pixel_dim_width = max(9, len(str(wcs.pixel_n_dim))) pixel_nam_width = max(9, max(len(x) for x in wcs.pixel_axis_names)) pixel_siz_width = max(9, len(str(max(array_shape)))) s += (('{0:' + str(pixel_dim_width) + 's}').format('Pixel Dim') + ' ' + ('{0:' + str(pixel_nam_width) + 's}').format('Axis Name') + ' ' + ('{0:' + str(pixel_siz_width) + 's}').format('Data size') + ' ' + 'Bounds\n') for ipix in range(wcs.pixel_n_dim): s += (('{0:' + str(pixel_dim_width) + 'g}').format(ipix) + ' ' + ('{0:' + str(pixel_nam_width) + 's}').format(wcs.pixel_axis_names[ipix] or 'None') + ' ' + (" " * 5 + str(None) if pixel_shape[ipix] is None else ('{0:' + str(pixel_siz_width) + 'g}').format(pixel_shape[ipix])) + ' ' + '{:s}'.format(str(None if wcs.pixel_bounds is None else wcs.pixel_bounds[ipix]) + '\n')) s += '\n' # World dimensions table # Find largest between header size and value length world_dim_width = max(9, len(str(wcs.world_n_dim))) world_nam_width = max(9, max(len(x) if x is not None else 0 for x in wcs.world_axis_names)) world_typ_width = max(13, max(len(x) if x is not None else 0 for x in wcs.world_axis_physical_types)) s += (('{0:' + str(world_dim_width) + 's}').format('World Dim') + ' ' + ('{0:' + str(world_nam_width) + 's}').format('Axis Name') + ' ' + ('{0:' + str(world_typ_width) + 's}').format('Physical Type') + ' ' + 'Units\n') for iwrl in range(wcs.world_n_dim): name = wcs.world_axis_names[iwrl] or 'None' typ = wcs.world_axis_physical_types[iwrl] or 'None' unit = wcs.world_axis_units[iwrl] or 'unknown' s += (('{0:' + str(world_dim_width) + 'd}').format(iwrl) + ' ' + ('{0:' + str(world_nam_width) + 's}').format(name) + ' ' + ('{0:' + str(world_typ_width) + 's}').format(typ) + ' ' + '{:s}'.format(unit + '\n')) s += '\n' # Axis correlation matrix pixel_dim_width = max(3, len(str(wcs.world_n_dim))) s += 'Correlation between pixel and world axes:\n\n' s += (' ' * world_dim_width + ' ' + ('{0:^' + str(wcs.pixel_n_dim * 5 - 2) + 's}').format('Pixel Dim') + '\n') s += (('{0:' + str(world_dim_width) + 's}').format('World Dim') + ''.join([' ' + ('{0:' + str(pixel_dim_width) + 'd}').format(ipix) for ipix in range(wcs.pixel_n_dim)]) + '\n') matrix = wcs.axis_correlation_matrix matrix_str = np.empty(matrix.shape, dtype='U3') matrix_str[matrix] = 'yes' matrix_str[~matrix] = 'no' for iwrl in range(wcs.world_n_dim): s += (('{0:' + str(world_dim_width) + 'd}').format(iwrl) + ''.join([' ' + ('{0:>' + str(pixel_dim_width) + 's}').format(matrix_str[iwrl, ipix]) for ipix in range(wcs.pixel_n_dim)]) + '\n') # Make sure we get rid of the extra whitespace at the end of some lines return '\n'.join([l.rstrip() for l in s.splitlines()])
5b41f2fbab9f14086c62046f6e13b67bbaaae35ee91bc55ed0ec2aca939c7daf
import warnings from .wrappers.sliced_wcs import SlicedLowLevelWCS, sanitize_slices from astropy.utils.exceptions import AstropyDeprecationWarning warnings.warn( "SlicedLowLevelWCS has been moved to" " astropy.wcs.wcsapi.wrappers.sliced_wcs.SlicedLowLevelWCS, or can be" " imported from astropy.wcs.wcsapi.", AstropyDeprecationWarning)
ed49b242712792dae1022e300e33f91d24409c7d055c77843bcf42ebe624c5d8
import abc from collections import defaultdict, OrderedDict import numpy as np from .utils import deserialize_class __all__ = ['BaseHighLevelWCS', 'HighLevelWCSMixin'] def rec_getattr(obj, att): for a in att.split('.'): obj = getattr(obj, a) return obj def default_order(components): order = [] for key, _, _ in components: if key not in order: order.append(key) return order def _toindex(value): """ Convert value to an int or an int array. Input coordinates converted to integers corresponding to the center of the pixel. The convention is that the center of the pixel is (0, 0), while the lower left corner is (-0.5, -0.5). The outputs are used to index the mask. Examples -------- >>> _toindex(np.array([-0.5, 0.49999])) array([0, 0]) >>> _toindex(np.array([0.5, 1.49999])) array([1, 1]) >>> _toindex(np.array([1.5, 2.49999])) array([2, 2]) """ indx = np.asarray(np.floor(np.asarray(value) + 0.5), dtype=int) return indx class BaseHighLevelWCS(metaclass=abc.ABCMeta): """ Abstract base class for the high-level WCS interface. This is described in `APE 14: A shared Python interface for World Coordinate Systems <https://doi.org/10.5281/zenodo.1188875>`_. """ @property @abc.abstractmethod def low_level_wcs(self): """ Returns a reference to the underlying low-level WCS object. """ @abc.abstractmethod def pixel_to_world(self, *pixel_arrays): """ Convert pixel coordinates to world coordinates (represented by high-level objects). If a single high-level object is used to represent the world coordinates (i.e., if ``len(wcs.world_axis_object_classes) == 1``), it is returned as-is (not in a tuple/list), otherwise a tuple of high-level objects is returned. See `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_to_world_values` for pixel indexing and ordering conventions. """ def array_index_to_world(self, *index_arrays): """ Convert array indices to world coordinates (represented by Astropy objects). If a single high-level object is used to represent the world coordinates (i.e., if ``len(wcs.world_axis_object_classes) == 1``), it is returned as-is (not in a tuple/list), otherwise a tuple of high-level objects is returned. See `~astropy.wcs.wcsapi.BaseLowLevelWCS.array_index_to_world_values` for pixel indexing and ordering conventions. """ return self.pixel_to_world(*index_arrays[::-1]) @abc.abstractmethod def world_to_pixel(self, *world_objects): """ Convert world coordinates (represented by Astropy objects) to pixel coordinates. If `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` is ``1``, this method returns a single scalar or array, otherwise a tuple of scalars or arrays is returned. See `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_to_pixel_values` for pixel indexing and ordering conventions. """ def world_to_array_index(self, *world_objects): """ Convert world coordinates (represented by Astropy objects) to array indices. If `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` is ``1``, this method returns a single scalar or array, otherwise a tuple of scalars or arrays is returned. See `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_to_array_index_values` for pixel indexing and ordering conventions. The indices should be returned as rounded integers. """ if self.pixel_n_dim == 1: return _toindex(self.world_to_pixel(*world_objects)) else: return tuple(_toindex(self.world_to_pixel(*world_objects)[::-1]).tolist()) def high_level_objects_to_values(*world_objects, low_level_wcs): """ Convert the input high level object to low level values. This function uses the information in ``wcs.world_axis_object_classes`` and ``wcs.world_axis_object_components`` to convert the high level objects (such as `~.SkyCoord`) to low level "values" `~.Quantity` objects. This is used in `.HighLevelWCSMixin.world_to_pixel`, but provided as a separate function for use in other places where needed. Parameters ---------- *world_objects: object High level coordinate objects. low_level_wcs: `.BaseLowLevelWCS` The WCS object to use to interpret the coordinates. """ # Cache the classes and components since this may be expensive serialized_classes = low_level_wcs.world_axis_object_classes components = low_level_wcs.world_axis_object_components # Deserialize world_axis_object_classes using the default order classes = OrderedDict() for key in default_order(components): if low_level_wcs.serialized_classes: classes[key] = deserialize_class(serialized_classes[key], construct=False) else: classes[key] = serialized_classes[key] # Check that the number of classes matches the number of inputs if len(world_objects) != len(classes): raise ValueError("Number of world inputs ({}) does not match " "expected ({})".format(len(world_objects), len(classes))) # Determine whether the classes are uniquely matched, that is we check # whether there is only one of each class. world_by_key = {} unique_match = True for w in world_objects: matches = [] for key, (klass, *_) in classes.items(): if isinstance(w, klass): matches.append(key) if len(matches) == 1: world_by_key[matches[0]] = w else: unique_match = False break # If the match is not unique, the order of the classes needs to match, # whereas if all classes are unique, we can still intelligently match # them even if the order is wrong. objects = {} if unique_match: for key, (klass, args, kwargs, *rest) in classes.items(): if len(rest) == 0: klass_gen = klass elif len(rest) == 1: klass_gen = rest[0] else: raise ValueError("Tuples in world_axis_object_classes should have length 3 or 4") # FIXME: For now SkyCoord won't auto-convert upon initialization # https://github.com/astropy/astropy/issues/7689 from astropy.coordinates import SkyCoord if isinstance(world_by_key[key], SkyCoord): if 'frame' in kwargs: objects[key] = world_by_key[key].transform_to(kwargs['frame']) else: objects[key] = world_by_key[key] else: objects[key] = klass_gen(world_by_key[key], *args, **kwargs) else: for ikey, key in enumerate(classes): klass, args, kwargs, *rest = classes[key] if len(rest) == 0: klass_gen = klass elif len(rest) == 1: klass_gen = rest[0] else: raise ValueError("Tuples in world_axis_object_classes should have length 3 or 4") w = world_objects[ikey] if not isinstance(w, klass): raise ValueError("Expected the following order of world " "arguments: {}".format(', '.join([k.__name__ for (k, _, _) in classes.values()]))) # FIXME: For now SkyCoord won't auto-convert upon initialization # https://github.com/astropy/astropy/issues/7689 from astropy.coordinates import SkyCoord if isinstance(w, SkyCoord): if 'frame' in kwargs: objects[key] = w.transform_to(kwargs['frame']) else: objects[key] = w else: objects[key] = klass_gen(w, *args, **kwargs) # We now extract the attributes needed for the world values world = [] for key, _, attr in components: if callable(attr): world.append(attr(objects[key])) else: world.append(rec_getattr(objects[key], attr)) return world def values_to_high_level_objects(*world_values, low_level_wcs): """ Convert low level values into high level objects. This function uses the information in ``wcs.world_axis_object_classes`` and ``wcs.world_axis_object_components`` to convert low level "values" `~.Quantity` objects, to high level objects (such as `~.SkyCoord). This is used in `.HighLevelWCSMixin.pixel_to_world`, but provided as a separate function for use in other places where needed. Parameters ---------- *world_values: object Low level, "values" representations of the world coordinates. low_level_wcs: `.BaseLowLevelWCS` The WCS object to use to interpret the coordinates. """ # Cache the classes and components since this may be expensive components = low_level_wcs.world_axis_object_components classes = low_level_wcs.world_axis_object_classes # Deserialize classes if low_level_wcs.serialized_classes: classes_new = {} for key, value in classes.items(): classes_new[key] = deserialize_class(value, construct=False) classes = classes_new args = defaultdict(list) kwargs = defaultdict(dict) for i, (key, attr, _) in enumerate(components): if isinstance(attr, str): kwargs[key][attr] = world_values[i] else: while attr > len(args[key]) - 1: args[key].append(None) args[key][attr] = world_values[i] result = [] for key in default_order(components): klass, ar, kw, *rest = classes[key] if len(rest) == 0: klass_gen = klass elif len(rest) == 1: klass_gen = rest[0] else: raise ValueError("Tuples in world_axis_object_classes should have length 3 or 4") result.append(klass_gen(*args[key], *ar, **kwargs[key], **kw)) return result class HighLevelWCSMixin(BaseHighLevelWCS): """ Mix-in class that automatically provides the high-level WCS API for the low-level WCS object given by the `~HighLevelWCSMixin.low_level_wcs` property. """ @property def low_level_wcs(self): return self def world_to_pixel(self, *world_objects): world_values = high_level_objects_to_values(*world_objects, low_level_wcs=self.low_level_wcs) # Finally we convert to pixel coordinates pixel_values = self.low_level_wcs.world_to_pixel_values(*world_values) return pixel_values def pixel_to_world(self, *pixel_arrays): # Compute the world coordinate values world_values = self.low_level_wcs.pixel_to_world_values(*pixel_arrays) if self.world_n_dim == 1: world_values = (world_values,) pixel_values = values_to_high_level_objects(*world_values, low_level_wcs=self.low_level_wcs) if len(pixel_values) == 1: return pixel_values[0] else: return pixel_values
441d936829b78178dce943f5d71870f12d195937ad3ceb6baf5f1c7b4c97889d
# This file includes the definition of a mix-in class that provides the low- # and high-level WCS API to the astropy.wcs.WCS object. We keep this code # isolated in this mix-in class to avoid making the main wcs.py file too # long. import warnings import numpy as np from astropy import units as u from astropy.coordinates import SpectralCoord, Galactic, ICRS from astropy.coordinates.spectral_coordinate import update_differentials_to_match, attach_zero_velocities from astropy.utils.exceptions import AstropyUserWarning from astropy.constants import c from .low_level_api import BaseLowLevelWCS from .high_level_api import HighLevelWCSMixin from .wrappers import SlicedLowLevelWCS __all__ = ['custom_ctype_to_ucd_mapping', 'SlicedFITSWCS', 'FITSWCSAPIMixin'] C_SI = c.si.value VELOCITY_FRAMES = { 'GEOCENT': 'gcrs', 'BARYCENT': 'icrs', 'HELIOCENT': 'hcrs', 'LSRK': 'lsrk', 'LSRD': 'lsrd' } # The spectra velocity frames below are needed for FITS spectral WCS # (see Greisen 06 table 12) but aren't yet defined as real # astropy.coordinates frames, so we instead define them here as instances # of existing coordinate frames with offset velocities. In future we should # make these real frames so that users can more easily recognize these # velocity frames when used in SpectralCoord. # This frame is defined as a velocity of 220 km/s in the # direction of l=90, b=0. The rotation velocity is defined # in: # # Kerr and Lynden-Bell 1986, Review of galactic constants. # # NOTE: this may differ from the assumptions of galcen_v_sun # in the Galactocentric frame - the value used here is # the one adopted by the WCS standard for spectral # transformations. VELOCITY_FRAMES['GALACTOC'] = Galactic(u=0 * u.km, v=0 * u.km, w=0 * u.km, U=0 * u.km / u.s, V=-220 * u.km / u.s, W=0 * u.km / u.s, representation_type='cartesian', differential_type='cartesian') # This frame is defined as a velocity of 300 km/s in the # direction of l=90, b=0. This is defined in: # # Transactions of the IAU Vol. XVI B Proceedings of the # 16th General Assembly, Reports of Meetings of Commissions: # Comptes Rendus Des Séances Des Commissions, Commission 28, # p201. # # Note that these values differ from those used by CASA # (308 km/s towards l=105, b=-7) but we use the above values # since these are the ones defined in Greisen et al (2006). VELOCITY_FRAMES['LOCALGRP'] = Galactic(u=0 * u.km, v=0 * u.km, w=0 * u.km, U=0 * u.km / u.s, V=-300 * u.km / u.s, W=0 * u.km / u.s, representation_type='cartesian', differential_type='cartesian') # This frame is defined as a velocity of 368 km/s in the # direction of l=263.85, b=48.25. This is defined in: # # Bennett et al. (2003), First-Year Wilkinson Microwave # Anisotropy Probe (WMAP) Observations: Preliminary Maps # and Basic Results # # Note that in that paper, the dipole is expressed as a # temperature (T=3.346 +/- 0.017mK) VELOCITY_FRAMES['CMBDIPOL'] = Galactic(l=263.85 * u.deg, b=48.25 * u.deg, distance=0 * u.km, radial_velocity=-(3.346e-3 / 2.725 * c).to(u.km/u.s)) # Mapping from CTYPE axis name to UCD1 CTYPE_TO_UCD1 = { # Celestial coordinates 'RA': 'pos.eq.ra', 'DEC': 'pos.eq.dec', 'GLON': 'pos.galactic.lon', 'GLAT': 'pos.galactic.lat', 'ELON': 'pos.ecliptic.lon', 'ELAT': 'pos.ecliptic.lat', 'TLON': 'pos.bodyrc.lon', 'TLAT': 'pos.bodyrc.lat', 'HPLT': 'custom:pos.helioprojective.lat', 'HPLN': 'custom:pos.helioprojective.lon', 'HPRZ': 'custom:pos.helioprojective.z', 'HGLN': 'custom:pos.heliographic.stonyhurst.lon', 'HGLT': 'custom:pos.heliographic.stonyhurst.lat', 'CRLN': 'custom:pos.heliographic.carrington.lon', 'CRLT': 'custom:pos.heliographic.carrington.lat', 'SOLX': 'custom:pos.heliocentric.x', 'SOLY': 'custom:pos.heliocentric.y', 'SOLZ': 'custom:pos.heliocentric.z', # Spectral coordinates (WCS paper 3) 'FREQ': 'em.freq', # Frequency 'ENER': 'em.energy', # Energy 'WAVN': 'em.wavenumber', # Wavenumber 'WAVE': 'em.wl', # Vacuum wavelength 'VRAD': 'spect.dopplerVeloc.radio', # Radio velocity 'VOPT': 'spect.dopplerVeloc.opt', # Optical velocity 'ZOPT': 'src.redshift', # Redshift 'AWAV': 'em.wl', # Air wavelength 'VELO': 'spect.dopplerVeloc', # Apparent radial velocity 'BETA': 'custom:spect.doplerVeloc.beta', # Beta factor (v/c) 'STOKES': 'phys.polarization.stokes', # STOKES parameters # Time coordinates (https://www.aanda.org/articles/aa/pdf/2015/02/aa24653-14.pdf) 'TIME': 'time', 'TAI': 'time', 'TT': 'time', 'TDT': 'time', 'ET': 'time', 'IAT': 'time', 'UT1': 'time', 'UTC': 'time', 'GMT': 'time', 'GPS': 'time', 'TCG': 'time', 'TCB': 'time', 'TDB': 'time', 'LOCAL': 'time', # Distance coordinates 'DIST': 'pos.distance', 'DSUN': 'custom:pos.distance.sunToObserver' # UT() and TT() are handled separately in world_axis_physical_types } # Keep a list of additional custom mappings that have been registered. This # is kept as a list in case nested context managers are used CTYPE_TO_UCD1_CUSTOM = [] class custom_ctype_to_ucd_mapping: """ A context manager that makes it possible to temporarily add new CTYPE to UCD1+ mapping used by :attr:`FITSWCSAPIMixin.world_axis_physical_types`. Parameters ---------- mapping : dict A dictionary mapping a CTYPE value to a UCD1+ value Examples -------- Consider a WCS with the following CTYPE:: >>> from astropy.wcs import WCS >>> wcs = WCS(naxis=1) >>> wcs.wcs.ctype = ['SPAM'] By default, :attr:`FITSWCSAPIMixin.world_axis_physical_types` returns `None`, but this can be overridden:: >>> wcs.world_axis_physical_types [None] >>> with custom_ctype_to_ucd_mapping({'SPAM': 'food.spam'}): ... wcs.world_axis_physical_types ['food.spam'] """ def __init__(self, mapping): CTYPE_TO_UCD1_CUSTOM.insert(0, mapping) self.mapping = mapping def __enter__(self): pass def __exit__(self, type, value, tb): CTYPE_TO_UCD1_CUSTOM.remove(self.mapping) class SlicedFITSWCS(SlicedLowLevelWCS, HighLevelWCSMixin): pass class FITSWCSAPIMixin(BaseLowLevelWCS, HighLevelWCSMixin): """ A mix-in class that is intended to be inherited by the :class:`~astropy.wcs.WCS` class and provides the low- and high-level WCS API """ @property def pixel_n_dim(self): return self.naxis @property def world_n_dim(self): return len(self.wcs.ctype) @property def array_shape(self): if self.pixel_shape is None: return None else: return self.pixel_shape[::-1] @array_shape.setter def array_shape(self, value): if value is None: self.pixel_shape = None else: self.pixel_shape = value[::-1] @property def pixel_shape(self): if self._naxis == [0, 0]: return None else: return tuple(self._naxis) @pixel_shape.setter def pixel_shape(self, value): if value is None: self._naxis = [0, 0] else: if len(value) != self.naxis: raise ValueError("The number of data axes, " "{}, does not equal the " "shape {}.".format(self.naxis, len(value))) self._naxis = list(value) @property def pixel_bounds(self): return self._pixel_bounds @pixel_bounds.setter def pixel_bounds(self, value): if value is None: self._pixel_bounds = value else: if len(value) != self.naxis: raise ValueError("The number of data axes, " "{}, does not equal the number of " "pixel bounds {}.".format(self.naxis, len(value))) self._pixel_bounds = list(value) @property def world_axis_physical_types(self): types = [] # TODO: need to support e.g. TT(TAI) for ctype in self.wcs.ctype: if ctype.upper().startswith(('UT(', 'TT(')): types.append('time') else: ctype_name = ctype.split('-')[0] for custom_mapping in CTYPE_TO_UCD1_CUSTOM: if ctype_name in custom_mapping: types.append(custom_mapping[ctype_name]) break else: types.append(CTYPE_TO_UCD1.get(ctype_name.upper(), None)) return types @property def world_axis_units(self): units = [] for unit in self.wcs.cunit: if unit is None: unit = '' elif isinstance(unit, u.Unit): unit = unit.to_string(format='vounit') else: try: unit = u.Unit(unit).to_string(format='vounit') except u.UnitsError: unit = '' units.append(unit) return units @property def world_axis_names(self): return list(self.wcs.cname) @property def axis_correlation_matrix(self): # If there are any distortions present, we assume that there may be # correlations between all axes. Maybe if some distortions only apply # to the image plane we can improve this? if self.has_distortion: return np.ones((self.world_n_dim, self.pixel_n_dim), dtype=bool) # Assuming linear world coordinates along each axis, the correlation # matrix would be given by whether or not the PC matrix is zero matrix = self.wcs.get_pc() != 0 # We now need to check specifically for celestial coordinates since # these can assume correlations because of spherical distortions. For # each celestial coordinate we copy over the pixel dependencies from # the other celestial coordinates. celestial = (self.wcs.axis_types // 1000) % 10 == 2 celestial_indices = np.nonzero(celestial)[0] for world1 in celestial_indices: for world2 in celestial_indices: if world1 != world2: matrix[world1] |= matrix[world2] matrix[world2] |= matrix[world1] return matrix def pixel_to_world_values(self, *pixel_arrays): world = self.all_pix2world(*pixel_arrays, 0) return world[0] if self.world_n_dim == 1 else tuple(world) def world_to_pixel_values(self, *world_arrays): pixel = self.all_world2pix(*world_arrays, 0) return pixel[0] if self.pixel_n_dim == 1 else tuple(pixel) @property def world_axis_object_components(self): return self._get_components_and_classes()[0] @property def world_axis_object_classes(self): return self._get_components_and_classes()[1] @property def serialized_classes(self): return False def _get_components_and_classes(self): # The aim of this function is to return whatever is needed for # world_axis_object_components and world_axis_object_classes. It's easier # to figure it out in one go and then return the values and let the # properties return part of it. # Since this method might get called quite a few times, we need to cache # it. We start off by defining a hash based on the attributes of the # WCS that matter here (we can't just use the WCS object as a hash since # it is mutable) wcs_hash = (self.naxis, list(self.wcs.ctype), list(self.wcs.cunit), self.wcs.radesys, self.wcs.specsys, self.wcs.equinox, self.wcs.dateobs, self.wcs.lng, self.wcs.lat) # If the cache is present, we need to check that the 'hash' matches. if getattr(self, '_components_and_classes_cache', None) is not None: cache = self._components_and_classes_cache if cache[0] == wcs_hash: return cache[1] else: self._components_and_classes_cache = None # Avoid circular imports by importing here from astropy.wcs.utils import wcs_to_celestial_frame from astropy.coordinates import SkyCoord, EarthLocation from astropy.time.formats import FITS_DEPRECATED_SCALES from astropy.time import Time, TimeDelta components = [None] * self.naxis classes = {} # Let's start off by checking whether the WCS has a pair of celestial # components if self.has_celestial: try: celestial_frame = wcs_to_celestial_frame(self) except ValueError: # Some WCSes, e.g. solar, can be recognized by WCSLIB as being # celestial but we don't necessarily have frames for them. celestial_frame = None else: kwargs = {} kwargs['frame'] = celestial_frame kwargs['unit'] = u.deg classes['celestial'] = (SkyCoord, (), kwargs) components[self.wcs.lng] = ('celestial', 0, 'spherical.lon.degree') components[self.wcs.lat] = ('celestial', 1, 'spherical.lat.degree') # Next, we check for spectral components if self.has_spectral: # Find index of spectral coordinate ispec = self.wcs.spec ctype = self.wcs.ctype[ispec][:4] ctype = ctype.upper() kwargs = {} # Determine observer location and velocity # TODO: determine how WCS standard would deal with observer on a # spacecraft far from earth. For now assume the obsgeo parameters, # if present, give the geocentric observer location. if np.isnan(self.wcs.obsgeo[0]): observer = None else: earth_location = EarthLocation(*self.wcs.obsgeo[:3], unit=u.m) obstime = Time(self.wcs.mjdobs, format='mjd', scale='utc', location=earth_location) observer_location = SkyCoord(earth_location.get_itrs(obstime=obstime)) if self.wcs.specsys in VELOCITY_FRAMES: frame = VELOCITY_FRAMES[self.wcs.specsys] observer = observer_location.transform_to(frame) if isinstance(frame, str): observer = attach_zero_velocities(observer) else: observer = update_differentials_to_match(observer_location, VELOCITY_FRAMES[self.wcs.specsys], preserve_observer_frame=True) elif self.wcs.specsys == 'TOPOCENT': observer = attach_zero_velocities(observer_location) else: raise NotImplementedError(f'SPECSYS={self.wcs.specsys} not yet supported') # Determine target # This is tricker. In principle the target for each pixel is the # celestial coordinates of the pixel, but we then need to be very # careful about SSYSOBS which is tricky. For now, we set the # target using the reference celestial coordinate in the WCS (if # any). if self.has_celestial and celestial_frame is not None: # NOTE: celestial_frame was defined higher up # NOTE: we set the distance explicitly to avoid warnings in SpectralCoord target = SkyCoord(self.wcs.crval[self.wcs.lng] * self.wcs.cunit[self.wcs.lng], self.wcs.crval[self.wcs.lat] * self.wcs.cunit[self.wcs.lat], frame=celestial_frame, distance=1000 * u.kpc) target = attach_zero_velocities(target) else: target = None # SpectralCoord does not work properly if either observer or target # are not convertible to ICRS, so if this is the case, we (for now) # drop the observer and target from the SpectralCoord and warn the # user. if observer is not None: try: observer.transform_to(ICRS()) except Exception: warnings.warn('observer cannot be converted to ICRS, so will ' 'not be set on SpectralCoord', AstropyUserWarning) observer = None if target is not None: try: target.transform_to(ICRS()) except Exception: warnings.warn('target cannot be converted to ICRS, so will ' 'not be set on SpectralCoord', AstropyUserWarning) target = None # NOTE: below we include Quantity in classes['spectral'] instead # of SpectralCoord - this is because we want to also be able to # accept plain quantities. if ctype == 'ZOPT': def spectralcoord_from_redshift(redshift): if isinstance(redshift, SpectralCoord): return redshift return SpectralCoord((redshift + 1) * self.wcs.restwav, unit=u.m, observer=observer, target=target) def redshift_from_spectralcoord(spectralcoord): # TODO: check target is consistent if observer is None: warnings.warn('No observer defined on WCS, SpectralCoord ' 'will be converted without any velocity ' 'frame change', AstropyUserWarning) return spectralcoord.to_value(u.m) / self.wcs.restwav - 1. else: return spectralcoord.with_observer_stationary_relative_to(observer).to_value(u.m) / self.wcs.restwav - 1. classes['spectral'] = (u.Quantity, (), {}, spectralcoord_from_redshift) components[self.wcs.spec] = ('spectral', 0, redshift_from_spectralcoord) elif ctype == 'BETA': def spectralcoord_from_beta(beta): if isinstance(beta, SpectralCoord): return beta return SpectralCoord(beta * C_SI, unit=u.m / u.s, doppler_convention='relativistic', doppler_rest=self.wcs.restwav * u.m, observer=observer, target=target) def beta_from_spectralcoord(spectralcoord): # TODO: check target is consistent doppler_equiv = u.doppler_relativistic(self.wcs.restwav * u.m) if observer is None: warnings.warn('No observer defined on WCS, SpectralCoord ' 'will be converted without any velocity ' 'frame change', AstropyUserWarning) return spectralcoord.to_value(u.m / u.s, doppler_equiv) / C_SI else: return spectralcoord.with_observer_stationary_relative_to(observer).to_value(u.m / u.s, doppler_equiv) / C_SI classes['spectral'] = (u.Quantity, (), {}, spectralcoord_from_beta) components[self.wcs.spec] = ('spectral', 0, beta_from_spectralcoord) else: kwargs['unit'] = self.wcs.cunit[ispec] if self.wcs.restfrq > 0: if ctype == 'VELO': kwargs['doppler_convention'] = 'relativistic' kwargs['doppler_rest'] = self.wcs.restfrq * u.Hz elif ctype == 'VRAD': kwargs['doppler_convention'] = 'radio' kwargs['doppler_rest'] = self.wcs.restfrq * u.Hz elif ctype == 'VOPT': kwargs['doppler_convention'] = 'optical' kwargs['doppler_rest'] = self.wcs.restwav * u.m def spectralcoord_from_value(value): return SpectralCoord(value, observer=observer, target=target, **kwargs) def value_from_spectralcoord(spectralcoord): # TODO: check target is consistent if observer is None: warnings.warn('No observer defined on WCS, SpectralCoord ' 'will be converted without any velocity ' 'frame change', AstropyUserWarning) return spectralcoord.to_value(**kwargs) else: return spectralcoord.with_observer_stationary_relative_to(observer).to_value(**kwargs) classes['spectral'] = (u.Quantity, (), {}, spectralcoord_from_value) components[self.wcs.spec] = ('spectral', 0, value_from_spectralcoord) # We can then make sure we correctly return Time objects where appropriate # (https://www.aanda.org/articles/aa/pdf/2015/02/aa24653-14.pdf) if 'time' in self.world_axis_physical_types: multiple_time = self.world_axis_physical_types.count('time') > 1 for i in range(self.naxis): if self.world_axis_physical_types[i] == 'time': if multiple_time: name = f'time.{i}' else: name = 'time' # Initialize delta reference_time_delta = None # Extract time scale scale = self.wcs.ctype[i].lower() if scale == 'time': if self.wcs.timesys: scale = self.wcs.timesys.lower() else: scale = 'utc' # Drop sub-scales if '(' in scale: pos = scale.index('(') scale, subscale = scale[:pos], scale[pos+1:-1] warnings.warn(f'Dropping unsupported sub-scale ' f'{subscale.upper()} from scale {scale.upper()}', UserWarning) # TODO: consider having GPS as a scale in Time # For now GPS is not a scale, we approximate this by TAI - 19s if scale == 'gps': reference_time_delta = TimeDelta(19, format='sec') scale = 'tai' elif scale.upper() in FITS_DEPRECATED_SCALES: scale = FITS_DEPRECATED_SCALES[scale.upper()] elif scale not in Time.SCALES: raise ValueError(f'Unrecognized time CTYPE={self.wcs.ctype[i]}') # Determine location trefpos = self.wcs.trefpos.lower() if trefpos.startswith('topocent'): # Note that some headers use TOPOCENT instead of TOPOCENTER if np.any(np.isnan(self.wcs.obsgeo[:3])): warnings.warn('Missing or incomplete observer location ' 'information, setting location in Time to None', UserWarning) location = None else: location = EarthLocation(*self.wcs.obsgeo[:3], unit=u.m) elif trefpos == 'geocenter': location = EarthLocation(0, 0, 0, unit=u.m) elif trefpos == '': location = None else: # TODO: implement support for more locations when Time supports it warnings.warn(f"Observation location '{trefpos}' is not " "supported, setting location in Time to None", UserWarning) location = None reference_time = Time(np.nan_to_num(self.wcs.mjdref[0]), np.nan_to_num(self.wcs.mjdref[1]), format='mjd', scale=scale, location=location) if reference_time_delta is not None: reference_time = reference_time + reference_time_delta def time_from_reference_and_offset(offset): if isinstance(offset, Time): return offset return reference_time + TimeDelta(offset, format='sec') def offset_from_time_and_reference(time): return (time - reference_time).sec classes[name] = (Time, (), {}, time_from_reference_and_offset) components[i] = (name, 0, offset_from_time_and_reference) # Fallback: for any remaining components that haven't been identified, just # return Quantity as the class to use for i in range(self.naxis): if components[i] is None: name = self.wcs.ctype[i].split('-')[0].lower() if name == '': name = 'world' while name in classes: name += "_" classes[name] = (u.Quantity, (), {'unit': self.wcs.cunit[i]}) components[i] = (name, 0, 'value') # Keep a cached version of result self._components_and_classes_cache = wcs_hash, (components, classes) return components, classes
db0a5eac37f04c2acdccd8b31aed3cf21ebecbca0153ac009307f354339e6fa4
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest import numpy as np from astropy import wcs def test_wtbarr_i(tab_wcs_2di): assert tab_wcs_2di.wcs.wtb[0].i == 1 def test_wtbarr_m(tab_wcs_2di): assert tab_wcs_2di.wcs.wtb[0].m == 1 def test_wtbarr_m(tab_wcs_2di): assert tab_wcs_2di.wcs.wtb[0].kind == 'c' def test_wtbarr_extnam(tab_wcs_2di): assert tab_wcs_2di.wcs.wtb[0].extnam == 'WCS-TABLE' def test_wtbarr_extver(tab_wcs_2di): assert tab_wcs_2di.wcs.wtb[0].extver == 1 def test_wtbarr_extlev(tab_wcs_2di): assert tab_wcs_2di.wcs.wtb[0].extlev == 1 def test_wtbarr_ttype(tab_wcs_2di): assert tab_wcs_2di.wcs.wtb[0].ttype == 'wavelength' def test_wtbarr_row(tab_wcs_2di): assert tab_wcs_2di.wcs.wtb[0].row == 1 def test_wtbarr_ndim(tab_wcs_2di): assert tab_wcs_2di.wcs.wtb[0].ndim == 3 def test_wtbarr_print(tab_wcs_2di, capfd): tab_wcs_2di.wcs.wtb[0].print_contents() captured = capfd.readouterr() s = str(tab_wcs_2di.wcs.wtb[0]) lines = s.split('\n') assert captured.out == s assert ' i: 1' == lines[0] assert ' m: 1' == lines[1] assert ' kind: c' == lines[2] assert 'extnam: WCS-TABLE' == lines[3] assert 'extver: 1' == lines[4] assert 'extlev: 1' == lines[5] assert ' ttype: wavelength' == lines[6] assert ' row: 1' == lines[7] assert ' ndim: 3' == lines[8] assert lines[9].startswith('dimlen: ') assert ' 0: 4' == lines[10] assert ' 1: 2' == lines[11] assert lines[12].startswith('arrayp: ')
31fd3e452818004779aa3622a84826e918d34e25d10c53b8cfab2ed603af1f29
# Licensed under a 3-clause BSD style license - see LICENSE.rst import warnings from contextlib import nullcontext import pytest from packaging.version import Version import numpy as np from numpy.testing import assert_almost_equal, assert_equal, assert_allclose from astropy.utils.data import get_pkg_data_contents, get_pkg_data_filename from astropy.utils.exceptions import AstropyUserWarning from astropy.time import Time from astropy import units as u from astropy.utils import unbroadcast from astropy.coordinates import SkyCoord, EarthLocation, ITRS from astropy.units import Quantity from astropy.io import fits from astropy.wcs import _wcs # noqa from astropy.wcs.wcs import (WCS, Sip, WCSSUB_LONGITUDE, WCSSUB_LATITUDE, FITSFixedWarning) from astropy.wcs.wcsapi.fitswcs import SlicedFITSWCS from astropy.wcs.utils import (proj_plane_pixel_scales, is_proj_plane_distorted, non_celestial_pixel_scales, wcs_to_celestial_frame, celestial_frame_to_wcs, skycoord_to_pixel, pixel_to_skycoord, custom_wcs_to_frame_mappings, custom_frame_to_wcs_mappings, add_stokes_axis_to_wcs, pixel_to_pixel, _split_matrix, _pixel_to_pixel_correlation_matrix, _pixel_to_world_correlation_matrix, local_partial_pixel_derivatives, fit_wcs_from_points, obsgeo_to_frame) from astropy.utils.compat.optional_deps import HAS_SCIPY # noqa def test_wcs_dropping(): wcs = WCS(naxis=4) wcs.wcs.pc = np.zeros([4, 4]) np.fill_diagonal(wcs.wcs.pc, np.arange(1, 5)) pc = wcs.wcs.pc # for later use below dropped = wcs.dropaxis(0) assert np.all(dropped.wcs.get_pc().diagonal() == np.array([2, 3, 4])) dropped = wcs.dropaxis(1) assert np.all(dropped.wcs.get_pc().diagonal() == np.array([1, 3, 4])) dropped = wcs.dropaxis(2) assert np.all(dropped.wcs.get_pc().diagonal() == np.array([1, 2, 4])) dropped = wcs.dropaxis(3) assert np.all(dropped.wcs.get_pc().diagonal() == np.array([1, 2, 3])) wcs = WCS(naxis=4) wcs.wcs.cd = pc dropped = wcs.dropaxis(0) assert np.all(dropped.wcs.get_pc().diagonal() == np.array([2, 3, 4])) dropped = wcs.dropaxis(1) assert np.all(dropped.wcs.get_pc().diagonal() == np.array([1, 3, 4])) dropped = wcs.dropaxis(2) assert np.all(dropped.wcs.get_pc().diagonal() == np.array([1, 2, 4])) dropped = wcs.dropaxis(3) assert np.all(dropped.wcs.get_pc().diagonal() == np.array([1, 2, 3])) def test_wcs_swapping(): wcs = WCS(naxis=4) wcs.wcs.pc = np.zeros([4, 4]) np.fill_diagonal(wcs.wcs.pc, np.arange(1, 5)) pc = wcs.wcs.pc # for later use below swapped = wcs.swapaxes(0, 1) assert np.all(swapped.wcs.get_pc().diagonal() == np.array([2, 1, 3, 4])) swapped = wcs.swapaxes(0, 3) assert np.all(swapped.wcs.get_pc().diagonal() == np.array([4, 2, 3, 1])) swapped = wcs.swapaxes(2, 3) assert np.all(swapped.wcs.get_pc().diagonal() == np.array([1, 2, 4, 3])) wcs = WCS(naxis=4) wcs.wcs.cd = pc swapped = wcs.swapaxes(0, 1) assert np.all(swapped.wcs.get_pc().diagonal() == np.array([2, 1, 3, 4])) swapped = wcs.swapaxes(0, 3) assert np.all(swapped.wcs.get_pc().diagonal() == np.array([4, 2, 3, 1])) swapped = wcs.swapaxes(2, 3) assert np.all(swapped.wcs.get_pc().diagonal() == np.array([1, 2, 4, 3])) @pytest.mark.parametrize('ndim', (2, 3)) def test_add_stokes(ndim): wcs = WCS(naxis=ndim) for ii in range(ndim + 1): outwcs = add_stokes_axis_to_wcs(wcs, ii) assert outwcs.wcs.naxis == ndim + 1 assert outwcs.wcs.ctype[ii] == 'STOKES' assert outwcs.wcs.cname[ii] == 'STOKES' def test_slice(): mywcs = WCS(naxis=2) mywcs.wcs.crval = [1, 1] mywcs.wcs.cdelt = [0.1, 0.1] mywcs.wcs.crpix = [1, 1] mywcs._naxis = [1000, 500] pscale = 0.1 # from cdelt slice_wcs = mywcs.slice([slice(1, None), slice(0, None)]) assert np.all(slice_wcs.wcs.crpix == np.array([1, 0])) assert slice_wcs._naxis == [1000, 499] # test that CRPIX maps to CRVAL: assert_allclose( slice_wcs.wcs_pix2world(*slice_wcs.wcs.crpix, 1), slice_wcs.wcs.crval, rtol=0.0, atol=1e-6 * pscale ) slice_wcs = mywcs.slice([slice(1, None, 2), slice(0, None, 4)]) assert np.all(slice_wcs.wcs.crpix == np.array([0.625, 0.25])) assert np.all(slice_wcs.wcs.cdelt == np.array([0.4, 0.2])) assert slice_wcs._naxis == [250, 250] slice_wcs = mywcs.slice([slice(None, None, 2), slice(0, None, 2)]) assert np.all(slice_wcs.wcs.cdelt == np.array([0.2, 0.2])) assert slice_wcs._naxis == [500, 250] # Non-integral values do not alter the naxis attribute with pytest.warns(AstropyUserWarning): slice_wcs = mywcs.slice([slice(50.), slice(20.)]) assert slice_wcs._naxis == [1000, 500] with pytest.warns(AstropyUserWarning): slice_wcs = mywcs.slice([slice(50.), slice(20)]) assert slice_wcs._naxis == [20, 500] with pytest.warns(AstropyUserWarning): slice_wcs = mywcs.slice([slice(50), slice(20.5)]) assert slice_wcs._naxis == [1000, 50] def test_slice_with_sip(): mywcs = WCS(naxis=2) mywcs.wcs.crval = [1, 1] mywcs.wcs.cdelt = [0.1, 0.1] mywcs.wcs.crpix = [1, 1] mywcs._naxis = [1000, 500] mywcs.wcs.ctype = ['RA---TAN-SIP', 'DEC--TAN-SIP'] a = np.array( [[0, 0, 5.33092692e-08, 3.73753773e-11, -2.02111473e-13], [0, 2.44084308e-05, 2.81394789e-11, 5.17856895e-13, 0.0], [-2.41334657e-07, 1.29289255e-10, 2.35753629e-14, 0.0, 0.0], [-2.37162007e-10, 5.43714947e-13, 0.0, 0.0, 0.0], [-2.81029767e-13, 0.0, 0.0, 0.0, 0.0]] ) b = np.array( [[0, 0, 2.99270374e-05, -2.38136074e-10, 7.23205168e-13], [0, -1.71073858e-07, 6.31243431e-11, -5.16744347e-14, 0.0], [6.95458963e-06, -3.08278961e-10, -1.75800917e-13, 0.0, 0.0], [3.51974159e-11, 5.60993016e-14, 0.0, 0.0, 0.0], [-5.92438525e-13, 0.0, 0.0, 0.0, 0.0]] ) mywcs.sip = Sip(a, b, None, None, mywcs.wcs.crpix) mywcs.wcs.set() pscale = 0.1 # from cdelt slice_wcs = mywcs.slice([slice(1, None), slice(0, None)]) # test that CRPIX maps to CRVAL: assert_allclose( slice_wcs.all_pix2world(*slice_wcs.wcs.crpix, 1), slice_wcs.wcs.crval, rtol=0.0, atol=1e-6 * pscale ) slice_wcs = mywcs.slice([slice(1, None, 2), slice(0, None, 4)]) # test that CRPIX maps to CRVAL: assert_allclose( slice_wcs.all_pix2world(*slice_wcs.wcs.crpix, 1), slice_wcs.wcs.crval, rtol=0.0, atol=1e-6 * pscale ) def test_slice_getitem(): mywcs = WCS(naxis=2) mywcs.wcs.crval = [1, 1] mywcs.wcs.cdelt = [0.1, 0.1] mywcs.wcs.crpix = [1, 1] slice_wcs = mywcs[1::2, 0::4] assert np.all(slice_wcs.wcs.crpix == np.array([0.625, 0.25])) assert np.all(slice_wcs.wcs.cdelt == np.array([0.4, 0.2])) mywcs.wcs.crpix = [2, 2] slice_wcs = mywcs[1::2, 0::4] assert np.all(slice_wcs.wcs.crpix == np.array([0.875, 0.75])) assert np.all(slice_wcs.wcs.cdelt == np.array([0.4, 0.2])) # Default: numpy order slice_wcs = mywcs[1::2] assert np.all(slice_wcs.wcs.crpix == np.array([2, 0.75])) assert np.all(slice_wcs.wcs.cdelt == np.array([0.1, 0.2])) def test_slice_fitsorder(): mywcs = WCS(naxis=2) mywcs.wcs.crval = [1, 1] mywcs.wcs.cdelt = [0.1, 0.1] mywcs.wcs.crpix = [1, 1] slice_wcs = mywcs.slice([slice(1, None), slice(0, None)], numpy_order=False) assert np.all(slice_wcs.wcs.crpix == np.array([0, 1])) slice_wcs = mywcs.slice([slice(1, None, 2), slice(0, None, 4)], numpy_order=False) assert np.all(slice_wcs.wcs.crpix == np.array([0.25, 0.625])) assert np.all(slice_wcs.wcs.cdelt == np.array([0.2, 0.4])) slice_wcs = mywcs.slice([slice(1, None, 2)], numpy_order=False) assert np.all(slice_wcs.wcs.crpix == np.array([0.25, 1])) assert np.all(slice_wcs.wcs.cdelt == np.array([0.2, 0.1])) def test_slice_wcs(): mywcs = WCS(naxis=2) sub = mywcs[0] assert isinstance(sub, SlicedFITSWCS) with pytest.raises(IndexError) as exc: mywcs[0, ::2] assert exc.value.args[0] == "Slicing WCS with a step is not supported." def test_axis_names(): mywcs = WCS(naxis=4) mywcs.wcs.ctype = ['RA---TAN', 'DEC--TAN', 'VOPT-LSR', 'STOKES'] assert mywcs.axis_type_names == ['RA', 'DEC', 'VOPT', 'STOKES'] mywcs.wcs.cname = ['RA', 'DEC', 'VOPT', 'STOKES'] assert mywcs.axis_type_names == ['RA', 'DEC', 'VOPT', 'STOKES'] def test_celestial(): mywcs = WCS(naxis=4) mywcs.wcs.ctype = ['RA---TAN', 'DEC--TAN', 'VOPT', 'STOKES'] cel = mywcs.celestial assert tuple(cel.wcs.ctype) == ('RA---TAN', 'DEC--TAN') assert cel.axis_type_names == ['RA', 'DEC'] def test_wcs_to_celestial_frame(): # Import astropy.coordinates here to avoid circular imports from astropy.coordinates.builtin_frames import ICRS, ITRS, FK5, FK4, Galactic mywcs = WCS(naxis=2) mywcs.wcs.set() with pytest.raises(ValueError, match="Could not determine celestial frame " "corresponding to the specified WCS object"): assert wcs_to_celestial_frame(mywcs) is None mywcs = WCS(naxis=2) mywcs.wcs.ctype = ['XOFFSET', 'YOFFSET'] mywcs.wcs.set() with pytest.raises(ValueError): assert wcs_to_celestial_frame(mywcs) is None mywcs = WCS(naxis=2) mywcs.wcs.ctype = ['RA---TAN', 'DEC--TAN'] mywcs.wcs.set() frame = wcs_to_celestial_frame(mywcs) assert isinstance(frame, ICRS) mywcs = WCS(naxis=2) mywcs.wcs.ctype = ['RA---TAN', 'DEC--TAN'] mywcs.wcs.equinox = 1987. mywcs.wcs.set() print(mywcs.to_header()) frame = wcs_to_celestial_frame(mywcs) assert isinstance(frame, FK5) assert frame.equinox == Time(1987., format='jyear') mywcs = WCS(naxis=2) mywcs.wcs.ctype = ['RA---TAN', 'DEC--TAN'] mywcs.wcs.equinox = 1982 mywcs.wcs.set() frame = wcs_to_celestial_frame(mywcs) assert isinstance(frame, FK4) assert frame.equinox == Time(1982., format='byear') mywcs = WCS(naxis=2) mywcs.wcs.ctype = ['GLON-SIN', 'GLAT-SIN'] mywcs.wcs.set() frame = wcs_to_celestial_frame(mywcs) assert isinstance(frame, Galactic) mywcs = WCS(naxis=2) mywcs.wcs.ctype = ['TLON-CAR', 'TLAT-CAR'] mywcs.wcs.dateobs = '2017-08-17T12:41:04.430' mywcs.wcs.set() frame = wcs_to_celestial_frame(mywcs) assert isinstance(frame, ITRS) assert frame.obstime == Time('2017-08-17T12:41:04.430') for equinox in [np.nan, 1987, 1982]: mywcs = WCS(naxis=2) mywcs.wcs.ctype = ['RA---TAN', 'DEC--TAN'] mywcs.wcs.radesys = 'ICRS' mywcs.wcs.equinox = equinox mywcs.wcs.set() frame = wcs_to_celestial_frame(mywcs) assert isinstance(frame, ICRS) # Flipped order mywcs = WCS(naxis=2) mywcs.wcs.ctype = ['DEC--TAN', 'RA---TAN'] mywcs.wcs.set() frame = wcs_to_celestial_frame(mywcs) assert isinstance(frame, ICRS) # More than two dimensions mywcs = WCS(naxis=3) mywcs.wcs.ctype = ['DEC--TAN', 'VELOCITY', 'RA---TAN'] mywcs.wcs.set() frame = wcs_to_celestial_frame(mywcs) assert isinstance(frame, ICRS) mywcs = WCS(naxis=3) mywcs.wcs.ctype = ['GLAT-CAR', 'VELOCITY', 'GLON-CAR'] mywcs.wcs.set() frame = wcs_to_celestial_frame(mywcs) assert isinstance(frame, Galactic) def test_wcs_to_celestial_frame_correlated(): # Regression test for a bug that caused wcs_to_celestial_frame to fail when # the celestial axes were correlated with other axes. # Import astropy.coordinates here to avoid circular imports from astropy.coordinates.builtin_frames import ICRS mywcs = WCS(naxis=3) mywcs.wcs.ctype = 'RA---TAN', 'DEC--TAN', 'FREQ' mywcs.wcs.cd = np.ones((3, 3)) mywcs.wcs.set() frame = wcs_to_celestial_frame(mywcs) assert isinstance(frame, ICRS) def test_wcs_to_celestial_frame_extend(): mywcs = WCS(naxis=2) mywcs.wcs.ctype = ['XOFFSET', 'YOFFSET'] mywcs.wcs.set() with pytest.raises(ValueError): wcs_to_celestial_frame(mywcs) class OffsetFrame: pass def identify_offset(wcs): if wcs.wcs.ctype[0].endswith('OFFSET') and wcs.wcs.ctype[1].endswith('OFFSET'): return OffsetFrame() with custom_wcs_to_frame_mappings(identify_offset): frame = wcs_to_celestial_frame(mywcs) assert isinstance(frame, OffsetFrame) # Check that things are back to normal after the context manager with pytest.raises(ValueError): wcs_to_celestial_frame(mywcs) def test_celestial_frame_to_wcs(): # Import astropy.coordinates here to avoid circular imports from astropy.coordinates import ICRS, ITRS, FK5, FK4, FK4NoETerms, Galactic, BaseCoordinateFrame class FakeFrame(BaseCoordinateFrame): pass frame = FakeFrame() with pytest.raises(ValueError) as exc: celestial_frame_to_wcs(frame) assert exc.value.args[0] == ("Could not determine WCS corresponding to " "the specified coordinate frame.") frame = ICRS() mywcs = celestial_frame_to_wcs(frame) mywcs.wcs.set() assert tuple(mywcs.wcs.ctype) == ('RA---TAN', 'DEC--TAN') assert mywcs.wcs.radesys == 'ICRS' assert np.isnan(mywcs.wcs.equinox) assert mywcs.wcs.lonpole == 180 assert mywcs.wcs.latpole == 0 frame = FK5(equinox='J1987') mywcs = celestial_frame_to_wcs(frame) assert tuple(mywcs.wcs.ctype) == ('RA---TAN', 'DEC--TAN') assert mywcs.wcs.radesys == 'FK5' assert mywcs.wcs.equinox == 1987. frame = FK4(equinox='B1982') mywcs = celestial_frame_to_wcs(frame) assert tuple(mywcs.wcs.ctype) == ('RA---TAN', 'DEC--TAN') assert mywcs.wcs.radesys == 'FK4' assert mywcs.wcs.equinox == 1982. frame = FK4NoETerms(equinox='B1982') mywcs = celestial_frame_to_wcs(frame) assert tuple(mywcs.wcs.ctype) == ('RA---TAN', 'DEC--TAN') assert mywcs.wcs.radesys == 'FK4-NO-E' assert mywcs.wcs.equinox == 1982. frame = Galactic() mywcs = celestial_frame_to_wcs(frame) assert tuple(mywcs.wcs.ctype) == ('GLON-TAN', 'GLAT-TAN') assert mywcs.wcs.radesys == '' assert np.isnan(mywcs.wcs.equinox) frame = Galactic() mywcs = celestial_frame_to_wcs(frame, projection='CAR') assert tuple(mywcs.wcs.ctype) == ('GLON-CAR', 'GLAT-CAR') assert mywcs.wcs.radesys == '' assert np.isnan(mywcs.wcs.equinox) frame = Galactic() mywcs = celestial_frame_to_wcs(frame, projection='CAR') mywcs.wcs.crval = [100, -30] mywcs.wcs.set() assert_allclose((mywcs.wcs.lonpole, mywcs.wcs.latpole), (180, 60)) frame = ITRS(obstime=Time('2017-08-17T12:41:04.43')) mywcs = celestial_frame_to_wcs(frame, projection='CAR') assert tuple(mywcs.wcs.ctype) == ('TLON-CAR', 'TLAT-CAR') assert mywcs.wcs.radesys == 'ITRS' assert mywcs.wcs.dateobs == '2017-08-17T12:41:04.430' frame = ITRS() mywcs = celestial_frame_to_wcs(frame, projection='CAR') assert tuple(mywcs.wcs.ctype) == ('TLON-CAR', 'TLAT-CAR') assert mywcs.wcs.radesys == 'ITRS' assert mywcs.wcs.dateobs == Time('J2000').utc.fits def test_celestial_frame_to_wcs_extend(): class OffsetFrame: pass frame = OffsetFrame() with pytest.raises(ValueError): celestial_frame_to_wcs(frame) def identify_offset(frame, projection=None): if isinstance(frame, OffsetFrame): wcs = WCS(naxis=2) wcs.wcs.ctype = ['XOFFSET', 'YOFFSET'] return wcs with custom_frame_to_wcs_mappings(identify_offset): mywcs = celestial_frame_to_wcs(frame) assert tuple(mywcs.wcs.ctype) == ('XOFFSET', 'YOFFSET') # Check that things are back to normal after the context manager with pytest.raises(ValueError): celestial_frame_to_wcs(frame) def test_pixscale_nodrop(): mywcs = WCS(naxis=2) mywcs.wcs.cdelt = [0.1, 0.2] mywcs.wcs.ctype = ['RA---TAN', 'DEC--TAN'] assert_almost_equal(proj_plane_pixel_scales(mywcs), (0.1, 0.2)) mywcs.wcs.cdelt = [-0.1, 0.2] assert_almost_equal(proj_plane_pixel_scales(mywcs), (0.1, 0.2)) def test_pixscale_withdrop(): mywcs = WCS(naxis=3) mywcs.wcs.cdelt = [0.1, 0.2, 1] mywcs.wcs.ctype = ['RA---TAN', 'DEC--TAN', 'VOPT'] assert_almost_equal(proj_plane_pixel_scales(mywcs.celestial), (0.1, 0.2)) mywcs.wcs.cdelt = [-0.1, 0.2, 1] assert_almost_equal(proj_plane_pixel_scales(mywcs.celestial), (0.1, 0.2)) def test_pixscale_cd(): mywcs = WCS(naxis=2) mywcs.wcs.cd = [[-0.1, 0], [0, 0.2]] mywcs.wcs.ctype = ['RA---TAN', 'DEC--TAN'] assert_almost_equal(proj_plane_pixel_scales(mywcs), (0.1, 0.2)) @pytest.mark.parametrize('angle', (30, 45, 60, 75)) def test_pixscale_cd_rotated(angle): mywcs = WCS(naxis=2) rho = np.radians(angle) scale = 0.1 mywcs.wcs.cd = [[scale * np.cos(rho), -scale * np.sin(rho)], [scale * np.sin(rho), scale * np.cos(rho)]] mywcs.wcs.ctype = ['RA---TAN', 'DEC--TAN'] assert_almost_equal(proj_plane_pixel_scales(mywcs), (0.1, 0.1)) @pytest.mark.parametrize('angle', (30, 45, 60, 75)) def test_pixscale_pc_rotated(angle): mywcs = WCS(naxis=2) rho = np.radians(angle) scale = 0.1 mywcs.wcs.cdelt = [-scale, scale] mywcs.wcs.pc = [[np.cos(rho), -np.sin(rho)], [np.sin(rho), np.cos(rho)]] mywcs.wcs.ctype = ['RA---TAN', 'DEC--TAN'] assert_almost_equal(proj_plane_pixel_scales(mywcs), (0.1, 0.1)) @pytest.mark.parametrize(('cdelt', 'pc', 'pccd'), (([0.1, 0.2], np.eye(2), np.diag([0.1, 0.2])), ([0.1, 0.2, 0.3], np.eye(3), np.diag([0.1, 0.2, 0.3])), ([1, 1, 1], np.diag([0.1, 0.2, 0.3]), np.diag([0.1, 0.2, 0.3])))) def test_pixel_scale_matrix(cdelt, pc, pccd): mywcs = WCS(naxis=(len(cdelt))) mywcs.wcs.cdelt = cdelt mywcs.wcs.pc = pc assert_almost_equal(mywcs.pixel_scale_matrix, pccd) @pytest.mark.parametrize(('ctype', 'cel'), ((['RA---TAN', 'DEC--TAN'], True), (['RA---TAN', 'DEC--TAN', 'FREQ'], False), (['RA---TAN', 'FREQ'], False),)) def test_is_celestial(ctype, cel): mywcs = WCS(naxis=len(ctype)) mywcs.wcs.ctype = ctype assert mywcs.is_celestial == cel @pytest.mark.parametrize(('ctype', 'cel'), ((['RA---TAN', 'DEC--TAN'], True), (['RA---TAN', 'DEC--TAN', 'FREQ'], True), (['RA---TAN', 'FREQ'], False),)) def test_has_celestial(ctype, cel): mywcs = WCS(naxis=len(ctype)) mywcs.wcs.ctype = ctype assert mywcs.has_celestial == cel def test_has_celestial_correlated(): # Regression test for astropy/astropy#8416 - has_celestial failed when # celestial axes were correlated with other axes. mywcs = WCS(naxis=3) mywcs.wcs.ctype = 'RA---TAN', 'DEC--TAN', 'FREQ' mywcs.wcs.cd = np.ones((3, 3)) mywcs.wcs.set() assert mywcs.has_celestial @pytest.mark.parametrize(('cdelt', 'pc', 'cd', 'check_warning'), ((np.array([0.1, 0.2]), np.eye(2), np.eye(2), True), (np.array([1, 1]), np.diag([0.1, 0.2]), np.eye(2), True), (np.array([0.1, 0.2]), np.eye(2), None, False), (np.array([0.1, 0.2]), None, np.eye(2), True), )) def test_noncelestial_scale(cdelt, pc, cd, check_warning): mywcs = WCS(naxis=2) if cd is not None: mywcs.wcs.cd = cd if pc is not None: mywcs.wcs.pc = pc # TODO: Some inputs emit RuntimeWarning from here onwards. # Fix the test data. See @nden's comment in PR 9010. if check_warning: ctx = pytest.warns() else: ctx = nullcontext() with ctx as warning_lines: mywcs.wcs.cdelt = cdelt if check_warning: for w in warning_lines: assert issubclass(w.category, RuntimeWarning) assert 'cdelt will be ignored since cd is present' in str(w.message) mywcs.wcs.ctype = ['RA---TAN', 'FREQ'] ps = non_celestial_pixel_scales(mywcs) assert_almost_equal(ps.to_value(u.deg), np.array([0.1, 0.2])) @pytest.mark.parametrize('mode', ['all', 'wcs']) def test_skycoord_to_pixel(mode): # Import astropy.coordinates here to avoid circular imports from astropy.coordinates import SkyCoord header = get_pkg_data_contents('data/maps/1904-66_TAN.hdr', encoding='binary') wcs = WCS(header) ref = SkyCoord(0.1 * u.deg, -89. * u.deg, frame='icrs') xp, yp = skycoord_to_pixel(ref, wcs, mode=mode) # WCS is in FK5 so we need to transform back to ICRS new = pixel_to_skycoord(xp, yp, wcs, mode=mode).transform_to('icrs') assert_allclose(new.ra.degree, ref.ra.degree) assert_allclose(new.dec.degree, ref.dec.degree) # Make sure you can specify a different class using ``cls`` keyword class SkyCoord2(SkyCoord): pass new2 = pixel_to_skycoord(xp, yp, wcs, mode=mode, cls=SkyCoord2).transform_to('icrs') assert new2.__class__ is SkyCoord2 assert_allclose(new2.ra.degree, ref.ra.degree) assert_allclose(new2.dec.degree, ref.dec.degree) def test_skycoord_to_pixel_swapped(): # Regression test for a bug that caused skycoord_to_pixel and # pixel_to_skycoord to not work correctly if the axes were swapped in the # WCS. # Import astropy.coordinates here to avoid circular imports from astropy.coordinates import SkyCoord header = get_pkg_data_contents('data/maps/1904-66_TAN.hdr', encoding='binary') wcs = WCS(header) wcs_swapped = wcs.sub([WCSSUB_LATITUDE, WCSSUB_LONGITUDE]) ref = SkyCoord(0.1 * u.deg, -89. * u.deg, frame='icrs') xp1, yp1 = skycoord_to_pixel(ref, wcs) xp2, yp2 = skycoord_to_pixel(ref, wcs_swapped) assert_allclose(xp1, xp2) assert_allclose(yp1, yp2) # WCS is in FK5 so we need to transform back to ICRS new1 = pixel_to_skycoord(xp1, yp1, wcs).transform_to('icrs') new2 = pixel_to_skycoord(xp1, yp1, wcs_swapped).transform_to('icrs') assert_allclose(new1.ra.degree, new2.ra.degree) assert_allclose(new1.dec.degree, new2.dec.degree) def test_is_proj_plane_distorted(): # non-orthogonal CD: wcs = WCS(naxis=2) wcs.wcs.cd = [[-0.1, 0], [0, 0.2]] wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN'] assert(is_proj_plane_distorted(wcs)) # almost orthogonal CD: wcs.wcs.cd = [[0.1 + 2.0e-7, 1.7e-7], [1.2e-7, 0.1 - 1.3e-7]] assert(not is_proj_plane_distorted(wcs)) # real case: header = get_pkg_data_filename('data/sip.fits') with pytest.warns(FITSFixedWarning): wcs = WCS(header) assert(is_proj_plane_distorted(wcs)) @pytest.mark.parametrize('mode', ['all', 'wcs']) def test_skycoord_to_pixel_distortions(mode): # Import astropy.coordinates here to avoid circular imports from astropy.coordinates import SkyCoord header = get_pkg_data_filename('data/sip.fits') with pytest.warns(FITSFixedWarning): wcs = WCS(header) ref = SkyCoord(202.50 * u.deg, 47.19 * u.deg, frame='icrs') xp, yp = skycoord_to_pixel(ref, wcs, mode=mode) # WCS is in FK5 so we need to transform back to ICRS new = pixel_to_skycoord(xp, yp, wcs, mode=mode).transform_to('icrs') assert_allclose(new.ra.degree, ref.ra.degree) assert_allclose(new.dec.degree, ref.dec.degree) @pytest.fixture def spatial_wcs_2d_small_angle(): """ This WCS has an almost linear correlation between the pixel and world axes close to the reference pixel. """ wcs = WCS(naxis=2) wcs.wcs.ctype = ['HPLN-TAN', 'HPLT-TAN'] wcs.wcs.crpix = [3.0] * 2 wcs.wcs.cdelt = [0.002] * 2 wcs.wcs.crval = [0] * 2 wcs.wcs.set() return wcs def test_local_pixel_derivatives(spatial_wcs_2d_small_angle): not_diag = np.logical_not(np.diag([1, 1])) # At (or close to) the reference pixel this should equal the cdelt derivs = local_partial_pixel_derivatives(spatial_wcs_2d_small_angle, 3, 3) np.testing.assert_allclose(np.diag(derivs), spatial_wcs_2d_small_angle.wcs.cdelt) np.testing.assert_allclose(derivs[not_diag].flat, [0, 0], atol=1e-10) # Far away from the reference pixel this should not equal the cdelt derivs = local_partial_pixel_derivatives(spatial_wcs_2d_small_angle, 3e4, 3e4) assert not np.allclose(np.diag(derivs), spatial_wcs_2d_small_angle.wcs.cdelt) # At (or close to) the reference pixel this should equal the cdelt derivs = local_partial_pixel_derivatives( spatial_wcs_2d_small_angle, 3, 3, normalize_by_world=True) np.testing.assert_allclose(np.diag(derivs), [1, 1]) np.testing.assert_allclose(derivs[not_diag].flat, [0, 0], atol=1e-8) def test_pixel_to_world_correlation_matrix_celestial(): wcs = WCS(naxis=2) wcs.wcs.ctype = 'RA---TAN', 'DEC--TAN' wcs.wcs.set() assert_equal(wcs.axis_correlation_matrix, [[1, 1], [1, 1]]) matrix, classes = _pixel_to_world_correlation_matrix(wcs) assert_equal(matrix, [[1, 1]]) assert classes == [SkyCoord] def test_pixel_to_world_correlation_matrix_spectral_cube_uncorrelated(): wcs = WCS(naxis=3) wcs.wcs.ctype = 'RA---TAN', 'FREQ', 'DEC--TAN' wcs.wcs.set() assert_equal(wcs.axis_correlation_matrix, [[1, 0, 1], [0, 1, 0], [1, 0, 1]]) matrix, classes = _pixel_to_world_correlation_matrix(wcs) assert_equal(matrix, [[1, 0, 1], [0, 1, 0]]) assert classes == [SkyCoord, Quantity] def test_pixel_to_world_correlation_matrix_spectral_cube_correlated(): wcs = WCS(naxis=3) wcs.wcs.ctype = 'RA---TAN', 'FREQ', 'DEC--TAN' wcs.wcs.cd = np.ones((3, 3)) wcs.wcs.set() assert_equal(wcs.axis_correlation_matrix, [[1, 1, 1], [1, 1, 1], [1, 1, 1]]) matrix, classes = _pixel_to_world_correlation_matrix(wcs) assert_equal(matrix, [[1, 1, 1], [1, 1, 1]]) assert classes == [SkyCoord, Quantity] def test_pixel_to_pixel_correlation_matrix_celestial(): wcs_in = WCS(naxis=2) wcs_in.wcs.ctype = 'RA---TAN', 'DEC--TAN' wcs_in.wcs.set() wcs_out = WCS(naxis=2) wcs_out.wcs.ctype = 'DEC--TAN', 'RA---TAN' wcs_out.wcs.set() matrix = _pixel_to_pixel_correlation_matrix(wcs_in, wcs_out) assert_equal(matrix, [[1, 1], [1, 1]]) def test_pixel_to_pixel_correlation_matrix_spectral_cube_uncorrelated(): wcs_in = WCS(naxis=3) wcs_in.wcs.ctype = 'RA---TAN', 'DEC--TAN', 'FREQ' wcs_in.wcs.set() wcs_out = WCS(naxis=3) wcs_out.wcs.ctype = 'DEC--TAN', 'FREQ', 'RA---TAN' wcs_out.wcs.set() matrix = _pixel_to_pixel_correlation_matrix(wcs_in, wcs_out) assert_equal(matrix, [[1, 1, 0], [0, 0, 1], [1, 1, 0]]) def test_pixel_to_pixel_correlation_matrix_spectral_cube_correlated(): # NOTE: only make one of the WCSes have correlated axes to really test this wcs_in = WCS(naxis=3) wcs_in.wcs.ctype = 'RA---TAN', 'DEC--TAN', 'FREQ' wcs_in.wcs.set() wcs_out = WCS(naxis=3) wcs_out.wcs.ctype = 'DEC--TAN', 'FREQ', 'RA---TAN' wcs_out.wcs.cd = np.ones((3, 3)) wcs_out.wcs.set() matrix = _pixel_to_pixel_correlation_matrix(wcs_in, wcs_out) assert_equal(matrix, [[1, 1, 1], [1, 1, 1], [1, 1, 1]]) def test_pixel_to_pixel_correlation_matrix_mismatch(): wcs_in = WCS(naxis=2) wcs_in.wcs.ctype = 'RA---TAN', 'DEC--TAN' wcs_in.wcs.set() wcs_out = WCS(naxis=3) wcs_out.wcs.ctype = 'DEC--TAN', 'FREQ', 'RA---TAN' wcs_out.wcs.set() with pytest.raises(ValueError) as exc: _pixel_to_pixel_correlation_matrix(wcs_in, wcs_out) assert exc.value.args[0] == "The two WCS return a different number of world coordinates" wcs3 = WCS(naxis=2) wcs3.wcs.ctype = 'FREQ', 'PIXEL' wcs3.wcs.set() with pytest.raises(ValueError) as exc: _pixel_to_pixel_correlation_matrix(wcs_out, wcs3) assert exc.value.args[0] == "The world coordinate types of the two WCS do not match" wcs4 = WCS(naxis=4) wcs4.wcs.ctype = 'RA---TAN', 'DEC--TAN', 'Q1', 'Q2' wcs4.wcs.cunit = ['deg', 'deg', 'm/s', 'm/s'] wcs4.wcs.set() wcs5 = WCS(naxis=4) wcs5.wcs.ctype = 'Q1', 'RA---TAN', 'DEC--TAN', 'Q2' wcs5.wcs.cunit = ['m/s', 'deg', 'deg', 'm/s'] wcs5.wcs.set() with pytest.raises(ValueError, match="World coordinate order doesn't match " "and automatic matching is ambiguous"): _pixel_to_pixel_correlation_matrix(wcs4, wcs5) def test_pixel_to_pixel_correlation_matrix_nonsquare(): # Here we set up an input WCS that maps 3 pixel coordinates to 4 world # coordinates - the idea is to make sure that things work fine in cases # where the number of input and output pixel coordinates do not match. class FakeWCS(object): pass wcs_in = FakeWCS() wcs_in.low_level_wcs = wcs_in wcs_in.pixel_n_dim = 3 wcs_in.world_n_dim = 4 wcs_in.axis_correlation_matrix = [[True, True, False], [True, True, False], [True, True, False], [False, False, True]] wcs_in.world_axis_object_components = [('spat', 'ra', 'ra.degree'), ('spat', 'dec', 'dec.degree'), ('spec', 0, 'value'), ('time', 0, 'utc.value')] wcs_in.world_axis_object_classes = {'spat': ('astropy.coordinates.SkyCoord', (), {'frame': 'icrs'}), 'spec': ('astropy.units.Wavelength', (None,), {}), 'time': ('astropy.time.Time', (None,), {'format': 'mjd', 'scale': 'utc'})} wcs_out = FakeWCS() wcs_out.low_level_wcs = wcs_out wcs_out.pixel_n_dim = 4 wcs_out.world_n_dim = 4 wcs_out.axis_correlation_matrix = [[True, False, False, False], [False, True, True, False], [False, True, True, False], [False, False, False, True]] wcs_out.world_axis_object_components = [('spec', 0, 'value'), ('spat', 'ra', 'ra.degree'), ('spat', 'dec', 'dec.degree'), ('time', 0, 'utc.value')] wcs_out.world_axis_object_classes = wcs_in.world_axis_object_classes matrix = _pixel_to_pixel_correlation_matrix(wcs_in, wcs_out) matrix = matrix.astype(int) # The shape should be (n_pixel_out, n_pixel_in) assert matrix.shape == (4, 3) expected = np.array([[1, 1, 0], [1, 1, 0], [1, 1, 0], [0, 0, 1]]) assert_equal(matrix, expected) def test_split_matrix(): assert _split_matrix(np.array([[1]])) == [([0], [0])] assert _split_matrix(np.array([[1, 1], [1, 1]])) == [([0, 1], [0, 1])] assert _split_matrix(np.array([[1, 1, 0], [1, 1, 0], [0, 0, 1]])) == [([0, 1], [0, 1]), ([2], [2])] assert _split_matrix(np.array([[0, 1, 0], [1, 0, 0], [0, 0, 1]])) == [([0], [1]), ([1], [0]), ([2], [2])] assert _split_matrix(np.array([[0, 1, 1], [1, 0, 0], [1, 0, 1]])) == [([0, 1, 2], [0, 1, 2])] def test_pixel_to_pixel(): wcs_in = WCS(naxis=3) wcs_in.wcs.ctype = 'DEC--TAN', 'FREQ', 'RA---TAN' wcs_in.wcs.set() wcs_out = WCS(naxis=3) wcs_out.wcs.ctype = 'GLON-CAR', 'GLAT-CAR', 'FREQ' wcs_out.wcs.set() # First try with scalars with pytest.warns(AstropyUserWarning, match='No observer defined on WCS'): x, y, z = pixel_to_pixel(wcs_in, wcs_out, 1, 2, 3) assert x.shape == () assert y.shape == () assert z.shape == () # Now try with broadcasted arrays x = np.linspace(10, 20, 10) y = np.linspace(10, 20, 20) z = np.linspace(10, 20, 30) Z1, Y1, X1 = np.meshgrid(z, y, x, indexing='ij', copy=False) with pytest.warns(AstropyUserWarning, match='No observer defined on WCS'): X2, Y2, Z2 = pixel_to_pixel(wcs_in, wcs_out, X1, Y1, Z1) # The final arrays should have the correct shape assert X2.shape == (30, 20, 10) assert Y2.shape == (30, 20, 10) assert Z2.shape == (30, 20, 10) # But behind the scenes should also be broadcasted assert unbroadcast(X2).shape == (30, 1, 10) assert unbroadcast(Y2).shape == (30, 1, 10) assert unbroadcast(Z2).shape == (20, 1) # We can put the values back through the function to ensure round-tripping with pytest.warns(AstropyUserWarning, match='No observer defined on WCS'): X3, Y3, Z3 = pixel_to_pixel(wcs_out, wcs_in, X2, Y2, Z2) # The final arrays should have the correct shape assert X2.shape == (30, 20, 10) assert Y2.shape == (30, 20, 10) assert Z2.shape == (30, 20, 10) # But behind the scenes should also be broadcasted assert unbroadcast(X3).shape == (30, 1, 10) assert unbroadcast(Y3).shape == (20, 1) assert unbroadcast(Z3).shape == (30, 1, 10) # And these arrays should match the input assert_allclose(X1, X3) assert_allclose(Y1, Y3) assert_allclose(Z1, Z3) def test_pixel_to_pixel_correlated(): wcs_in = WCS(naxis=2) wcs_in.wcs.ctype = 'DEC--TAN', 'RA---TAN' wcs_in.wcs.set() wcs_out = WCS(naxis=2) wcs_out.wcs.ctype = 'GLON-CAR', 'GLAT-CAR' wcs_out.wcs.set() # First try with scalars x, y = pixel_to_pixel(wcs_in, wcs_out, 1, 2) assert x.shape == () assert y.shape == () # Now try with broadcasted arrays x = np.linspace(10, 20, 10) y = np.linspace(10, 20, 20) Y1, X1 = np.meshgrid(y, x, indexing='ij', copy=False) Y2, X2 = pixel_to_pixel(wcs_in, wcs_out, X1, Y1) # The final arrays should have the correct shape assert X2.shape == (20, 10) assert Y2.shape == (20, 10) # and there are no efficiency gains here since the celestial axes are correlated assert unbroadcast(X2).shape == (20, 10) def test_pixel_to_pixel_1d(): # Simple test to make sure that when WCS only returns one world coordinate # this still works correctly (since this requires special treatment behind # the scenes). wcs_in = WCS(naxis=1) wcs_in.wcs.ctype = 'COORD1', wcs_in.wcs.cunit = 'nm', wcs_in.wcs.set() wcs_out = WCS(naxis=1) wcs_out.wcs.ctype = 'COORD2', wcs_out.wcs.cunit = 'cm', wcs_out.wcs.set() # First try with a scalar x = pixel_to_pixel(wcs_in, wcs_out, 1) assert x.shape == () # Next with a regular array x = np.linspace(10, 20, 10) x = pixel_to_pixel(wcs_in, wcs_out, x) assert x.shape == (10,) # And now try with a broadcasted array x = np.broadcast_to(np.linspace(10, 20, 10), (4, 10)) x = pixel_to_pixel(wcs_in, wcs_out, x) assert x.shape == (4, 10) # The broadcasting of the input should be retained assert unbroadcast(x).shape == (10,) header_str_linear = """ XTENSION= 'IMAGE ' / Image extension BITPIX = -32 / array data type NAXIS = 2 / number of array dimensions NAXIS1 = 50 NAXIS2 = 50 PCOUNT = 0 / number of parameters GCOUNT = 1 / number of groups RADESYS = 'ICRS ' EQUINOX = 2000.0 WCSAXES = 2 CTYPE1 = 'RA---TAN' CTYPE2 = 'DEC--TAN' CRVAL1 = 250.3497414839765 CRVAL2 = 2.280925599609063 CRPIX1 = 1045.0 CRPIX2 = 1001.0 CD1_1 = -0.005564478186178 CD1_2 = -0.001042099258152 CD2_1 = 0.00118144146585 CD2_2 = -0.005590816683583 """ header_str_sip = """ XTENSION= 'IMAGE ' / Image extension BITPIX = -32 / array data type NAXIS = 2 / number of array dimensions NAXIS1 = 50 NAXIS2 = 50 PCOUNT = 0 / number of parameters GCOUNT = 1 / number of groups RADESYS = 'ICRS ' EQUINOX = 2000.0 WCSAXES = 2 CTYPE1 = 'RA---TAN-SIP' CTYPE2 = 'DEC--TAN-SIP' CRVAL1 = 250.3497414839765 CRVAL2 = 2.280925599609063 CRPIX1 = 1045.0 CRPIX2 = 1001.0 CD1_1 = -0.005564478186178 CD1_2 = -0.001042099258152 CD2_1 = 0.00118144146585 CD2_2 = -0.005590816683583 A_ORDER = 2 B_ORDER = 2 A_2_0 = 2.02451189234E-05 A_0_2 = 3.317603337918E-06 A_1_1 = 1.73456334971071E-05 B_2_0 = 3.331330003472E-06 B_0_2 = 2.04247482482589E-05 B_1_1 = 1.71476710804143E-05 AP_ORDER= 2 BP_ORDER= 2 AP_1_0 = 0.000904700296389636 AP_0_1 = 0.000627660715584716 AP_2_0 = -2.023482905861E-05 AP_0_2 = -3.332285841011E-06 AP_1_1 = -1.731636633824E-05 BP_1_0 = 0.000627960882053211 BP_0_1 = 0.000911222886084808 BP_2_0 = -3.343918167224E-06 BP_0_2 = -2.041598249021E-05 BP_1_1 = -1.711876336719E-05 A_DMAX = 44.72893589844534 B_DMAX = 44.62692873032506 """ header_str_prob = """ NAXIS = 2 / number of array dimensions WCSAXES = 2 / Number of coordinate axes CRPIX1 = 1024.5 / Pixel coordinate of reference point CRPIX2 = 1024.5 / Pixel coordinate of reference point CD1_1 = -1.7445934400771E-05 / Coordinate transformation matrix element CD1_2 = -4.9826985362578E-08 / Coordinate transformation matrix element CD2_1 = -5.0068838822312E-08 / Coordinate transformation matrix element CD2_2 = 1.7530614610951E-05 / Coordinate transformation matrix element CTYPE1 = 'RA---TAN' / Right ascension, gnomonic projection CTYPE2 = 'DEC--TAN' / Declination, gnomonic projection CRVAL1 = 5.8689341666667 / [deg] Coordinate value at reference point CRVAL2 = -71.995508583333 / [deg] Coordinate value at reference point """ @pytest.mark.skipif('not HAS_SCIPY') @pytest.mark.parametrize( 'header_str,crval,sip_degree,user_proj_point,exp_max_dist,exp_std_dist', [ # simple testset no distortions (header_str_linear, 250.3497414839765, None, False, 7e-5*u.deg, 2.5e-5*u.deg), # simple testset with distortions (header_str_sip, 250.3497414839765, 2, False, 7e-6*u.deg, 2.5e-6*u.deg), # testset with problematic WCS header that failed before (header_str_prob, 5.8689341666667, None, False, 7e-6*u.deg, 2.5e-6*u.deg), # simple testset no distortions, user defined center (header_str_linear, 250.3497414839765, None, True, 7e-5*u.deg, 2.5e-5*u.deg), # 360->0 degree crossover, simple testset no distortions (header_str_linear, 352.3497414839765, None, False, 7e-5*u.deg, 2.5e-5*u.deg), # 360->0 degree crossover, simple testset with distortions (header_str_sip, 352.3497414839765, 2, False, 7e-6*u.deg, 2.5e-6*u.deg), # 360->0 degree crossover, testset with problematic WCS header that failed before (header_str_prob, 352.3497414839765, None, False, 7e-6*u.deg, 2.5e-6*u.deg), # 360->0 degree crossover, simple testset no distortions, user defined center (header_str_linear, 352.3497414839765, None, True, 7e-5*u.deg, 2.5e-5*u.deg), ]) def test_fit_wcs_from_points(header_str, crval, sip_degree, user_proj_point, exp_max_dist, exp_std_dist): header = fits.Header.fromstring(header_str, sep='\n') header["CRVAL1"] = crval true_wcs = WCS(header, relax=True) # Getting the pixel coordinates x, y = np.meshgrid(list(range(10)), list(range(10))) x = x.flatten() y = y.flatten() # Calculating the true sky positions world_pix = true_wcs.pixel_to_world(x, y) # which projection point to use if user_proj_point: proj_point = world_pix[0] projlon = proj_point.data.lon.deg projlat = proj_point.data.lat.deg else: proj_point = 'center' # Fitting the wcs fit_wcs = fit_wcs_from_points((x, y), world_pix, proj_point=proj_point, sip_degree=sip_degree) # Validate that the true sky coordinates # match sky coordinates calculated from the wcs fit world_pix_new = fit_wcs.pixel_to_world(x, y) dists = world_pix.separation(world_pix_new) assert dists.max() < exp_max_dist assert np.std(dists) < exp_std_dist if user_proj_point: assert (fit_wcs.wcs.crval == [projlon, projlat]).all() @pytest.mark.skipif('not HAS_SCIPY') def test_fit_wcs_from_points_CRPIX_bounds(): # Test CRPIX bounds requirement wcs_str = """ WCSAXES = 2 / Number of coordinate axes CRPIX1 = 1045.0 / Pixel coordinate of reference point CRPIX2 = 1001.0 / Pixel coordinate of reference point PC1_1 = 0.00056205870415378 / Coordinate transformation matrix element PC1_2 = -0.00569181083243 / Coordinate transformation matrix element PC2_1 = 0.0056776810932466 / Coordinate transformation matrix element PC2_2 = 0.0004208048403273 / Coordinate transformation matrix element CDELT1 = 1.0 / [deg] Coordinate increment at reference point CDELT2 = 1.0 / [deg] Coordinate increment at reference point CUNIT1 = 'deg' / Units of coordinate increment and value CUNIT2 = 'deg' / Units of coordinate increment and value CTYPE1 = 'RA---TAN' / Right ascension, gnomonic projection CTYPE2 = 'DEC--TAN' / Declination, gnomonic projection CRVAL1 = 104.57797893504 / [deg] Coordinate value at reference point CRVAL2 = -74.195502593322 / [deg] Coordinate value at reference point LONPOLE = 180.0 / [deg] Native longitude of celestial pole LATPOLE = -74.195502593322 / [deg] Native latitude of celestial pole TIMESYS = 'TDB' / Time scale TIMEUNIT= 'd' / Time units DATEREF = '1858-11-17' / ISO-8601 fiducial time MJDREFI = 0.0 / [d] MJD of fiducial time, integer part MJDREFF = 0.0 / [d] MJD of fiducial time, fractional part DATE-OBS= '2019-03-27T03:30:13.832Z' / ISO-8601 time of observation MJD-OBS = 58569.145993426 / [d] MJD of observation MJD-OBS = 58569.145993426 / [d] MJD at start of observation TSTART = 1569.6467941661 / [d] Time elapsed since fiducial time at start DATE-END= '2019-03-27T04:00:13.831Z' / ISO-8601 time at end of observation MJD-END = 58569.166826748 / [d] MJD at end of observation TSTOP = 1569.6676274905 / [d] Time elapsed since fiducial time at end TELAPSE = 0.02083332443 / [d] Elapsed time (start to stop) TIMEDEL = 0.020833333333333 / [d] Time resolution TIMEPIXR= 0.5 / Reference position of timestamp in binned data RADESYS = 'ICRS' / Equatorial coordinate system """ wcs_header = fits.Header.fromstring(wcs_str, sep='\n') ffi_wcs = WCS(wcs_header) yi, xi = (1000, 1000) y, x = (10, 200) center_coord = SkyCoord(ffi_wcs.all_pix2world([[xi+x//2, yi+y//2]], 0), unit='deg')[0] ypix, xpix = [arr.flatten() for arr in np.mgrid[xi : xi + x, yi : yi + y]] world_pix = SkyCoord(*ffi_wcs.all_pix2world(xpix, ypix, 0), unit='deg') fit_wcs = fit_wcs_from_points((ypix, xpix), world_pix, proj_point='center') assert (fit_wcs.wcs.crpix.astype(int) == [1100, 1005]).all() assert fit_wcs.pixel_shape == (1199, 1009) @pytest.mark.skipif('not HAS_SCIPY') def test_issue10991(): # test issue #10991 (it just needs to run and set the user defined crval) xy = np.array([[1766.88276168, 662.96432257, 171.50212526, 120.70924648], [1706.69832901, 1788.85480559, 1216.98949653, 1307.41843381]]) world_coords = SkyCoord([(66.3542367, 22.20000162), (67.15416174, 19.18042906), (65.73375432, 17.54251555), (66.02400512, 17.44413253)], frame="icrs", unit="deg") proj_point = SkyCoord(64.67514918, 19.63389538, frame="icrs", unit="deg") fit_wcs = fit_wcs_from_points( xy=xy, world_coords=world_coords, proj_point=proj_point, projection='TAN' ) projlon = proj_point.data.lon.deg projlat = proj_point.data.lat.deg assert (fit_wcs.wcs.crval == [projlon, projlat]).all() @pytest.mark.remote_data @pytest.mark.parametrize('x_in,y_in', [[0, 0], [np.arange(5), np.arange(5)]]) def test_pixel_to_world_itrs(x_in, y_in): """Regression test for https://github.com/astropy/astropy/pull/9609""" if Version(_wcs.__version__) >= Version('7.4'): ctx = pytest.warns( FITSFixedWarning, match=r"'datfix' made the change 'Set MJD-OBS to 57982\.528524 from DATE-OBS'\.") else: ctx = nullcontext() with ctx: wcs = WCS({'NAXIS': 2, 'CTYPE1': 'TLON-CAR', 'CTYPE2': 'TLAT-CAR', 'RADESYS': 'ITRS ', 'DATE-OBS': '2017-08-17T12:41:04.444'}) # This shouldn't raise an exception. coord = wcs.pixel_to_world(x_in, y_in) # Check round trip transformation. x, y = wcs.world_to_pixel(coord) np.testing.assert_almost_equal(x, x_in) np.testing.assert_almost_equal(y, y_in) @pytest.fixture def dkist_location(): return EarthLocation(*(-5466045.25695494, -2404388.73741278, 2242133.88769004) * u.m) def test_obsgeo_cartesian(dkist_location): obstime = Time("2021-05-21T03:00:00") wcs = WCS(naxis=2) wcs.wcs.obsgeo = list(dkist_location.to_value(u.m).tolist()) + [0, 0, 0] wcs.wcs.dateobs = obstime.isot frame = obsgeo_to_frame(wcs.wcs.obsgeo, obstime) assert isinstance(frame, ITRS) assert frame.x == dkist_location.x assert frame.y == dkist_location.y assert frame.z == dkist_location.z def test_obsgeo_spherical(dkist_location): obstime = Time("2021-05-21T03:00:00") dkist_location = dkist_location.get_itrs(obstime) loc_sph = dkist_location.spherical wcs = WCS(naxis=2) wcs.wcs.obsgeo = [0, 0, 0] + [loc_sph.lon.value, loc_sph.lat.value, loc_sph.distance.value] wcs.wcs.dateobs = obstime.isot frame = obsgeo_to_frame(wcs.wcs.obsgeo, obstime) assert isinstance(frame, ITRS) assert u.allclose(frame.x, dkist_location.x) assert u.allclose(frame.y, dkist_location.y) assert u.allclose(frame.z, dkist_location.z) def test_obsgeo_infinite(dkist_location): obstime = Time("2021-05-21T03:00:00") dkist_location = dkist_location.get_itrs(obstime) loc_sph = dkist_location.spherical wcs = WCS(naxis=2) wcs.wcs.obsgeo = [1, 1, np.nan] + [loc_sph.lon.value, loc_sph.lat.value, loc_sph.distance.value] wcs.wcs.dateobs = obstime.isot wcs.wcs.set() frame = obsgeo_to_frame(wcs.wcs.obsgeo, obstime) assert isinstance(frame, ITRS) assert u.allclose(frame.x, dkist_location.x) assert u.allclose(frame.y, dkist_location.y) assert u.allclose(frame.z, dkist_location.z) @pytest.mark.parametrize("obsgeo", ([np.nan] * 6, None, [0] * 6, [54] * 5)) def test_obsgeo_invalid(obsgeo): with pytest.raises(ValueError): obsgeo_to_frame(obsgeo, None)
749230dc96c29f184526671692f7a1759b07ac2334b1d3c557324b56cbb431db
# Licensed under a 3-clause BSD style license - see LICENSE.rst from copy import copy, deepcopy import pytest import numpy as np from astropy import wcs from . helper import SimModelTAB def test_prjprm_init(): # test PyPrjprm_cnew assert wcs.WCS().wcs.cel.prj # test PyPrjprm_new assert wcs.Prjprm() with pytest.raises(wcs.InvalidPrjParametersError): prj = wcs.Prjprm() prj.set() # test deletion does not crash prj = wcs.Prjprm() del prj def test_prjprm_copy(): # shallow copy prj = wcs.Prjprm() prj2 = copy(prj) prj3 = copy(prj2) prj.pv = [0, 6, 8, 18, 3] assert (np.allclose(prj.pv, prj2.pv, atol=1e-12, rtol=0) and np.allclose(prj.pv, prj3.pv, atol=1e-12, rtol=0)) del prj, prj2, prj3 # deep copy prj = wcs.Prjprm() prj2 = deepcopy(prj) prj.pv = [0, 6, 8, 18, 3] assert not np.allclose(prj.pv, prj2.pv, atol=1e-12, rtol=0) del prj, prj2 def test_prjprm_flag(): prj = wcs.Prjprm() assert prj._flag == 0 def test_prjprm_code(): prj = wcs.Prjprm() assert prj.code == ' ' assert prj._flag == 0 prj.code = 'TAN' prj.set() assert prj.code == 'TAN' assert prj._flag prj.code = 'TAN' assert prj._flag prj.code = None assert prj.code == ' ' assert prj._flag == 0 def test_prjprm_phi0(): prj = wcs.Prjprm() assert prj.phi0 == None assert prj._flag == 0 prj.code = 'TAN' prj.phi0 = 2.0 prj.set() assert prj.phi0 == 0 prj.phi0 = 0.0 assert prj._flag prj.phi0 = 2.0 assert prj._flag == 0 prj.phi0 = None assert prj.phi0 == None assert prj._flag == 0 def test_prjprm_theta0(): prj = wcs.Prjprm() assert prj.theta0 == None assert prj._flag == 0 prj.code = 'TAN' prj.phi0 = 2.0 prj.theta0 = 4.0 prj.set() assert prj.theta0 == 4.0 prj.theta0 = 4.0 assert prj._flag prj.theta0 = 8.0 assert prj._flag == 0 prj.theta0 = None assert prj.theta0 == None assert prj._flag == 0 def test_prjprm_pv(): prj = wcs.Prjprm() assert prj.pv.size == wcs.PRJ_PVN assert prj.theta0 == None assert prj._flag == 0 prj.code = 'ZPN' prj.phi0 = 2.0 prj.theta0 = 4.0 pv = [float(i) if (i % 2) else i for i in range(wcs.PRJ_PVN)] prj.pv = pv prj.set() assert prj.phi0 == 2.0 assert prj.theta0 == 4.0 assert np.allclose(prj.pv, pv, atol=1e-6, rtol=0) # test the same with numpy.ndarray (flag not cleared for same values): prj.pv = prj.pv assert prj._flag != 0 prj.set() assert np.allclose(prj.pv, pv, atol=1e-6, rtol=0) # test the same but modify PV values to check that flag is cleared: prj.pv = np.array(pv) + 2e-7 assert prj._flag == 0 prj.set() assert np.allclose(prj.pv, pv, atol=1e-6, rtol=0) # check that None in pv list leave value unchanged and values not set # by the list are left unchanged: prj.code = 'SZP' prj.pv = [0.0, 99.0, None] assert np.allclose(prj.pv[:4], [0.0, 99.0, 2.0, 3.0], atol=1e-6, rtol=0) # check that None resets PV to uninitialized (before prjset()) values: prj.pv = None assert prj.pv[0] == 0.0 assert np.all(np.isnan(prj.pv[1:4])) assert np.allclose(prj.pv[5:], 0, atol=0, rtol=0) # check we can set all PVs to nan: nan_pvs = wcs.PRJ_PVN * [np.nan] prj.code = 'TAN' prj.pv = nan_pvs # set using a list prj.set() assert np.all(np.isnan(prj.pv)) prj.pv = np.array(nan_pvs) # set using a numpy.ndarray prj.set() assert np.all(np.isnan(prj.pv)) def test_prjprm_pvrange(): prj = wcs.Prjprm() prj.code = 'ZPN' prj.phi0 = 2.0 prj.theta0 = 4.0 prj.pv = [0.0, 1.0, 2.0, 3.0] prj.set() assert prj.pvrange == wcs.PRJ_PVN prj.code = 'SZP' prj.set() assert prj.pvrange == 103 def test_prjprm_bounds(prj_TAB): assert prj_TAB.bounds == 7 prj_TAB.bounds = 0 assert prj_TAB.bounds == 0 def test_prjprm_category(prj_TAB): assert prj_TAB.category == wcs.PRJ_ZENITHAL def test_prjprm_name(prj_TAB): assert prj_TAB.name def test_prjprm_w(prj_TAB): assert np.all(np.isfinite(prj_TAB.w)) def test_prjprm_simplezen(prj_TAB): assert prj_TAB.simplezen == 1 def test_prjprm_equiareal(prj_TAB): assert prj_TAB.equiareal == 0 def test_prjprm_conformal(prj_TAB): assert prj_TAB.conformal == 0 def test_prjprm_global_projection(prj_TAB): assert prj_TAB.global_projection == 0 def test_prjprm_divergent(prj_TAB): assert prj_TAB.divergent == 1 def test_prjprm_r0(prj_TAB): assert prj_TAB.r0 > 0.0 def test_prjprm_x0_y0(prj_TAB): assert prj_TAB.x0 == 0.0 assert prj_TAB.y0 == 0.0 def test_prjprm_n_m(prj_TAB): assert prj_TAB.n == 0 assert prj_TAB.m == 0 def test_prjprm_prj_roundtrips(prj_TAB): # some random values: x = [-0.002, 0.014, -0.003, 0.015, -0.047, -0.029, -0.042, 0.027, 0.021] y = [0.022, -0.017, -0.048, -0.049, -0.043, 0.015, 0.046, 0.031, 0.011] xr, yr = prj_TAB.prjs2x(*prj_TAB.prjx2s(x, y)) assert np.allclose(x, xr, atol=1e-12, rtol=0) assert np.allclose(y, yr, atol=1e-12, rtol=0) # same test for a Prjprm that was not previously explicitly "set": prj = wcs.Prjprm() prj.code = 'TAN' xr, yr = prj.prjs2x(*prj.prjx2s(x, y)) assert np.allclose(x, xr, atol=1e-12, rtol=0) assert np.allclose(y, yr, atol=1e-12, rtol=0)
88880d8b9cf6e4979ffe95ad180dcf0eaab847fd1d34ec46dc1c114346845aea
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os import pytest import numpy as np from astropy.utils.data import get_pkg_data_filenames, get_pkg_data_contents from astropy.utils.misc import NumpyRNGContext from astropy import wcs from astropy.wcs.wcs import FITSFixedWarning # use the base name of the file, because everything we yield # will show up in the test name in the pandokia report hdr_map_file_list = [ os.path.basename(fname) for fname in get_pkg_data_filenames("data/maps", pattern="*.hdr")] # Checking the number of files before reading them in. # OLD COMMENTS: # AFTER we tested with every file that we found, check to see that we # actually have the list we expect. If N=0, we will not have performed # any tests at all. If N < n_data_files, we are missing some files, # so we will have skipped some tests. Without this check, both cases # happen silently! def test_read_map_files(): # how many map files we expect to see n_map_files = 28 assert len(hdr_map_file_list) == n_map_files, ( "test_read_map_files has wrong number data files: found {}, expected " " {}".format(len(hdr_map_file_list), n_map_files)) @pytest.mark.parametrize("filename", hdr_map_file_list) def test_map(filename): header = get_pkg_data_contents(os.path.join("data/maps", filename)) wcsobj = wcs.WCS(header) with NumpyRNGContext(123456789): x = np.random.rand(2 ** 12, wcsobj.wcs.naxis) wcsobj.wcs_pix2world(x, 1) wcsobj.wcs_world2pix(x, 1) hdr_spec_file_list = [ os.path.basename(fname) for fname in get_pkg_data_filenames("data/spectra", pattern="*.hdr")] def test_read_spec_files(): # how many spec files expected n_spec_files = 6 assert len(hdr_spec_file_list) == n_spec_files, ( "test_spectra has wrong number data files: found {}, expected " " {}".format(len(hdr_spec_file_list), n_spec_files)) # b.t.w. If this assert happens, pytest reports one more test # than it would have otherwise. @pytest.mark.parametrize("filename", hdr_spec_file_list) def test_spectrum(filename): header = get_pkg_data_contents(os.path.join("data", "spectra", filename)) # Warning only pops up for one of the inputs. with pytest.warns() as warning_lines: wcsobj = wcs.WCS(header) for w in warning_lines: assert issubclass(w.category, FITSFixedWarning) with NumpyRNGContext(123456789): x = np.random.rand(2 ** 16, wcsobj.wcs.naxis) wcsobj.wcs_pix2world(x, 1) wcsobj.wcs_world2pix(x, 1)
71a13c3ec74dc56b431f744cb1a53378348be96dc05effd876962d3ff950c233
# Licensed under a 3-clause BSD style license - see LICENSE.rst import io import os from contextlib import nullcontext from datetime import datetime from packaging.version import Version import pytest import numpy as np from numpy.testing import ( assert_allclose, assert_array_almost_equal, assert_array_almost_equal_nulp, assert_array_equal) from astropy import wcs from astropy.wcs import _wcs # noqa from astropy import units as u from astropy.utils.data import ( get_pkg_data_filenames, get_pkg_data_contents, get_pkg_data_filename) from astropy.utils.misc import NumpyRNGContext from astropy.utils.exceptions import ( AstropyUserWarning, AstropyWarning, AstropyDeprecationWarning) from astropy.tests.helper import assert_quantity_allclose from astropy.io import fits from astropy.coordinates import SkyCoord from astropy.nddata import Cutout2D _WCSLIB_VER = Version(_wcs.__version__) # NOTE: User can choose to use system wcslib instead of bundled. def ctx_for_v71_dateref_warnings(): if _WCSLIB_VER >= Version('7.1') and _WCSLIB_VER < Version('7.3'): ctx = pytest.warns( wcs.FITSFixedWarning, match=r"'datfix' made the change 'Set DATE-REF to '1858-11-17' from MJD-REF'\.") else: ctx = nullcontext() return ctx class TestMaps: def setup(self): # get the list of the hdr files that we want to test self._file_list = list(get_pkg_data_filenames( "data/maps", pattern="*.hdr")) def test_consistency(self): # Check to see that we actually have the list we expect, so that we # do not get in a situation where the list is empty or incomplete and # the tests still seem to pass correctly. # how many do we expect to see? n_data_files = 28 assert len(self._file_list) == n_data_files, ( "test_spectra has wrong number data files: found {}, expected " " {}".format(len(self._file_list), n_data_files)) def test_maps(self): for filename in self._file_list: # use the base name of the file, so we get more useful messages # for failing tests. filename = os.path.basename(filename) # Now find the associated file in the installed wcs test directory. header = get_pkg_data_contents( os.path.join("data", "maps", filename), encoding='binary') # finally run the test. wcsobj = wcs.WCS(header) world = wcsobj.wcs_pix2world([[97, 97]], 1) assert_array_almost_equal(world, [[285.0, -66.25]], decimal=1) pix = wcsobj.wcs_world2pix([[285.0, -66.25]], 1) assert_array_almost_equal(pix, [[97, 97]], decimal=0) class TestSpectra: def setup(self): self._file_list = list(get_pkg_data_filenames("data/spectra", pattern="*.hdr")) def test_consistency(self): # Check to see that we actually have the list we expect, so that we # do not get in a situation where the list is empty or incomplete and # the tests still seem to pass correctly. # how many do we expect to see? n_data_files = 6 assert len(self._file_list) == n_data_files, ( "test_spectra has wrong number data files: found {}, expected " " {}".format(len(self._file_list), n_data_files)) def test_spectra(self): for filename in self._file_list: # use the base name of the file, so we get more useful messages # for failing tests. filename = os.path.basename(filename) # Now find the associated file in the installed wcs test directory. header = get_pkg_data_contents( os.path.join("data", "spectra", filename), encoding='binary') # finally run the test. if _WCSLIB_VER >= Version('7.4'): ctx = pytest.warns( wcs.FITSFixedWarning, match=r"'datfix' made the change 'Set MJD-OBS to 53925\.853472 from DATE-OBS'\.") # noqa else: ctx = nullcontext() with ctx: all_wcs = wcs.find_all_wcs(header) assert len(all_wcs) == 9 def test_fixes(): """ From github issue #36 """ header = get_pkg_data_contents('data/nonstandard_units.hdr', encoding='binary') with pytest.raises(wcs.InvalidTransformError), pytest.warns(wcs.FITSFixedWarning) as w: wcs.WCS(header, translate_units='dhs') if Version('7.4') <= _WCSLIB_VER < Version('7.6'): assert len(w) == 3 assert "'datfix' made the change 'Success'." in str(w.pop().message) else: assert len(w) == 2 first_wmsg = str(w[0].message) assert 'unitfix' in first_wmsg and 'Hz' in first_wmsg and 'M/S' in first_wmsg assert 'plane angle' in str(w[1].message) and 'm/s' in str(w[1].message) # Ignore "PV2_2 = 0.209028857410973 invalid keyvalue" warning seen on Windows. @pytest.mark.filterwarnings(r'ignore:PV2_2') def test_outside_sky(): """ From github issue #107 """ header = get_pkg_data_contents( 'data/outside_sky.hdr', encoding='binary') w = wcs.WCS(header) assert np.all(np.isnan(w.wcs_pix2world([[100., 500.]], 0))) # outside sky assert np.all(np.isnan(w.wcs_pix2world([[200., 200.]], 0))) # outside sky assert not np.any(np.isnan(w.wcs_pix2world([[1000., 1000.]], 0))) def test_pix2world(): """ From github issue #1463 """ # TODO: write this to test the expected output behavior of pix2world, # currently this just makes sure it doesn't error out in unexpected ways # (and compares `wcs.pc` and `result` values?) filename = get_pkg_data_filename('data/sip2.fits') with pytest.warns(wcs.FITSFixedWarning) as caught_warnings: # this raises a warning unimportant for this testing the pix2world # FITSFixedWarning(u'The WCS transformation has more axes (2) than # the image it is associated with (0)') ww = wcs.WCS(filename) # might as well monitor for changing behavior if Version('7.4') <= _WCSLIB_VER < Version('7.6'): assert len(caught_warnings) == 2 else: assert len(caught_warnings) == 1 n = 3 pixels = (np.arange(n) * np.ones((2, n))).T result = ww.wcs_pix2world(pixels, 0, ra_dec_order=True) # Catch #2791 ww.wcs_pix2world(pixels[..., 0], pixels[..., 1], 0, ra_dec_order=True) # assuming that the data of sip2.fits doesn't change answer = np.array([[0.00024976, 0.00023018], [0.00023043, -0.00024997]]) assert np.allclose(ww.wcs.pc, answer, atol=1.e-8) answer = np.array([[202.39265216, 47.17756518], [202.39335826, 47.17754619], [202.39406436, 47.1775272]]) assert np.allclose(result, answer, atol=1.e-8, rtol=1.e-10) def test_load_fits_path(): fits_name = get_pkg_data_filename('data/sip.fits') with pytest.warns(wcs.FITSFixedWarning): wcs.WCS(fits_name) def test_dict_init(): """ Test that WCS can be initialized with a dict-like object """ # Dictionary with no actual WCS, returns identity transform with ctx_for_v71_dateref_warnings(): w = wcs.WCS({}) xp, yp = w.wcs_world2pix(41., 2., 1) assert_array_almost_equal_nulp(xp, 41., 10) assert_array_almost_equal_nulp(yp, 2., 10) # Valid WCS hdr = { 'CTYPE1': 'GLON-CAR', 'CTYPE2': 'GLAT-CAR', 'CUNIT1': 'deg', 'CUNIT2': 'deg', 'CRPIX1': 1, 'CRPIX2': 1, 'CRVAL1': 40., 'CRVAL2': 0., 'CDELT1': -0.1, 'CDELT2': 0.1 } if _WCSLIB_VER >= Version('7.1'): hdr['DATEREF'] = '1858-11-17' if _WCSLIB_VER >= Version('7.4'): ctx = pytest.warns( wcs.wcs.FITSFixedWarning, match=r"'datfix' made the change 'Set MJDREF to 0\.000000 from DATEREF'\.") else: ctx = nullcontext() with ctx: w = wcs.WCS(hdr) xp, yp = w.wcs_world2pix(41., 2., 0) assert_array_almost_equal_nulp(xp, -10., 10) assert_array_almost_equal_nulp(yp, 20., 10) def test_extra_kwarg(): """ Issue #444 """ w = wcs.WCS() with NumpyRNGContext(123456789): data = np.random.rand(100, 2) with pytest.raises(TypeError): w.wcs_pix2world(data, origin=1) def test_3d_shapes(): """ Issue #444 """ w = wcs.WCS(naxis=3) with NumpyRNGContext(123456789): data = np.random.rand(100, 3) result = w.wcs_pix2world(data, 1) assert result.shape == (100, 3) result = w.wcs_pix2world( data[..., 0], data[..., 1], data[..., 2], 1) assert len(result) == 3 def test_preserve_shape(): w = wcs.WCS(naxis=2) x = np.random.random((2, 3, 4)) y = np.random.random((2, 3, 4)) xw, yw = w.wcs_pix2world(x, y, 1) assert xw.shape == (2, 3, 4) assert yw.shape == (2, 3, 4) xp, yp = w.wcs_world2pix(x, y, 1) assert xp.shape == (2, 3, 4) assert yp.shape == (2, 3, 4) def test_broadcasting(): w = wcs.WCS(naxis=2) x = np.random.random((2, 3, 4)) y = 1 xp, yp = w.wcs_world2pix(x, y, 1) assert xp.shape == (2, 3, 4) assert yp.shape == (2, 3, 4) def test_shape_mismatch(): w = wcs.WCS(naxis=2) x = np.random.random((2, 3, 4)) y = np.random.random((3, 2, 4)) with pytest.raises(ValueError) as exc: xw, yw = w.wcs_pix2world(x, y, 1) assert exc.value.args[0] == "Coordinate arrays are not broadcastable to each other" with pytest.raises(ValueError) as exc: xp, yp = w.wcs_world2pix(x, y, 1) assert exc.value.args[0] == "Coordinate arrays are not broadcastable to each other" # There are some ambiguities that need to be worked around when # naxis == 1 w = wcs.WCS(naxis=1) x = np.random.random((42, 1)) xw = w.wcs_pix2world(x, 1) assert xw.shape == (42, 1) x = np.random.random((42,)) xw, = w.wcs_pix2world(x, 1) assert xw.shape == (42,) def test_invalid_shape(): # Issue #1395 w = wcs.WCS(naxis=2) xy = np.random.random((2, 3)) with pytest.raises(ValueError) as exc: w.wcs_pix2world(xy, 1) assert exc.value.args[0] == 'When providing two arguments, the array must be of shape (N, 2)' xy = np.random.random((2, 1)) with pytest.raises(ValueError) as exc: w.wcs_pix2world(xy, 1) assert exc.value.args[0] == 'When providing two arguments, the array must be of shape (N, 2)' def test_warning_about_defunct_keywords(): header = get_pkg_data_contents('data/defunct_keywords.hdr', encoding='binary') if Version('7.4') <= _WCSLIB_VER < Version('7.6'): n_warn = 5 else: n_warn = 4 # Make sure the warnings come out every time... for _ in range(2): with pytest.warns(wcs.FITSFixedWarning) as w: wcs.WCS(header) assert len(w) == n_warn # 7.4 adds a fifth warning "'datfix' made the change 'Success'." for item in w[:4]: assert 'PCi_ja' in str(item.message) def test_warning_about_defunct_keywords_exception(): header = get_pkg_data_contents('data/defunct_keywords.hdr', encoding='binary') with pytest.warns(wcs.FITSFixedWarning): wcs.WCS(header) def test_to_header_string(): hdrstr = ( "WCSAXES = 2 / Number of coordinate axes ", "CRPIX1 = 0.0 / Pixel coordinate of reference point ", "CRPIX2 = 0.0 / Pixel coordinate of reference point ", "CDELT1 = 1.0 / Coordinate increment at reference point ", "CDELT2 = 1.0 / Coordinate increment at reference point ", "CRVAL1 = 0.0 / Coordinate value at reference point ", "CRVAL2 = 0.0 / Coordinate value at reference point ", "LATPOLE = 90.0 / [deg] Native latitude of celestial pole ", ) if _WCSLIB_VER >= Version('7.3'): hdrstr += ( "MJDREF = 0.0 / [d] MJD of fiducial time ", ) elif _WCSLIB_VER >= Version('7.1'): hdrstr += ( "DATEREF = '1858-11-17' / ISO-8601 fiducial time ", "MJDREFI = 0.0 / [d] MJD of fiducial time, integer part ", "MJDREFF = 0.0 / [d] MJD of fiducial time, fractional part " ) hdrstr += ("END", ) header_string = ''.join(hdrstr) w = wcs.WCS() h0 = fits.Header.fromstring(w.to_header_string().strip()) if 'COMMENT' in h0: del h0['COMMENT'] if '' in h0: del h0[''] h1 = fits.Header.fromstring(header_string.strip()) assert dict(h0) == dict(h1) def test_to_fits(): nrec = 11 if _WCSLIB_VER >= Version('7.1') else 8 if _WCSLIB_VER < Version('7.1'): nrec = 8 elif _WCSLIB_VER < Version('7.3'): nrec = 11 else: nrec = 9 w = wcs.WCS() header_string = w.to_header() wfits = w.to_fits() assert isinstance(wfits, fits.HDUList) assert isinstance(wfits[0], fits.PrimaryHDU) assert header_string == wfits[0].header[-nrec:] def test_to_header_warning(): fits_name = get_pkg_data_filename('data/sip.fits') with pytest.warns(wcs.FITSFixedWarning): x = wcs.WCS(fits_name) with pytest.warns(AstropyWarning, match='A_ORDER') as w: x.to_header() assert len(w) == 1 def test_no_comments_in_header(): w = wcs.WCS() header = w.to_header() assert w.wcs.alt not in header assert 'COMMENT' + w.wcs.alt.strip() not in header assert 'COMMENT' not in header wkey = 'P' header = w.to_header(key=wkey) assert wkey not in header assert 'COMMENT' not in header assert 'COMMENT' + w.wcs.alt.strip() not in header def test_find_all_wcs_crash(): """ Causes a double free without a recent fix in wcslib_wrap.C """ with open(get_pkg_data_filename("data/too_many_pv.hdr")) as fd: header = fd.read() # We have to set fix=False here, because one of the fixing tasks is to # remove redundant SCAMP distortion parameters when SIP distortion # parameters are also present. with pytest.raises(wcs.InvalidTransformError), pytest.warns(wcs.FITSFixedWarning): wcs.find_all_wcs(header, fix=False) # NOTE: Warning bubbles up from C layer during wcs.validate() and # is hard to catch, so we just ignore it. @pytest.mark.filterwarnings("ignore") def test_validate(): results = wcs.validate(get_pkg_data_filename("data/validate.fits")) results_txt = sorted(set([x.strip() for x in repr(results).splitlines()])) if _WCSLIB_VER >= Version('7.6'): filename = 'data/validate.7.6.txt' elif _WCSLIB_VER >= Version('7.4'): filename = 'data/validate.7.4.txt' elif _WCSLIB_VER >= Version('6.0'): filename = 'data/validate.6.txt' elif _WCSLIB_VER >= Version('5.13'): filename = 'data/validate.5.13.txt' elif _WCSLIB_VER >= Version('5.0'): filename = 'data/validate.5.0.txt' else: filename = 'data/validate.txt' with open(get_pkg_data_filename(filename), "r") as fd: lines = fd.readlines() assert sorted(set([x.strip() for x in lines])) == results_txt def test_validate_with_2_wcses(): # From Issue #2053 with pytest.warns(AstropyUserWarning): results = wcs.validate(get_pkg_data_filename("data/2wcses.hdr")) assert "WCS key 'A':" in str(results) def test_crpix_maps_to_crval(): twcs = wcs.WCS(naxis=2) twcs.wcs.crval = [251.29, 57.58] twcs.wcs.cdelt = [1, 1] twcs.wcs.crpix = [507, 507] twcs.wcs.pc = np.array([[7.7e-6, 3.3e-5], [3.7e-5, -6.8e-6]]) twcs._naxis = [1014, 1014] twcs.wcs.ctype = ['RA---TAN-SIP', 'DEC--TAN-SIP'] a = np.array( [[0, 0, 5.33092692e-08, 3.73753773e-11, -2.02111473e-13], [0, 2.44084308e-05, 2.81394789e-11, 5.17856895e-13, 0.0], [-2.41334657e-07, 1.29289255e-10, 2.35753629e-14, 0.0, 0.0], [-2.37162007e-10, 5.43714947e-13, 0.0, 0.0, 0.0], [-2.81029767e-13, 0.0, 0.0, 0.0, 0.0]] ) b = np.array( [[0, 0, 2.99270374e-05, -2.38136074e-10, 7.23205168e-13], [0, -1.71073858e-07, 6.31243431e-11, -5.16744347e-14, 0.0], [6.95458963e-06, -3.08278961e-10, -1.75800917e-13, 0.0, 0.0], [3.51974159e-11, 5.60993016e-14, 0.0, 0.0, 0.0], [-5.92438525e-13, 0.0, 0.0, 0.0, 0.0]] ) twcs.sip = wcs.Sip(a, b, None, None, twcs.wcs.crpix) twcs.wcs.set() pscale = np.sqrt(wcs.utils.proj_plane_pixel_area(twcs)) # test that CRPIX maps to CRVAL: assert_allclose( twcs.wcs_pix2world(*twcs.wcs.crpix, 1), twcs.wcs.crval, rtol=0.0, atol=1e-6 * pscale ) # test that CRPIX maps to CRVAL: assert_allclose( twcs.all_pix2world(*twcs.wcs.crpix, 1), twcs.wcs.crval, rtol=0.0, atol=1e-6 * pscale ) def test_all_world2pix(fname=None, ext=0, tolerance=1.0e-4, origin=0, random_npts=25000, adaptive=False, maxiter=20, detect_divergence=True): """Test all_world2pix, iterative inverse of all_pix2world""" # Open test FITS file: if fname is None: fname = get_pkg_data_filename('data/j94f05bgq_flt.fits') ext = ('SCI', 1) if not os.path.isfile(fname): raise OSError(f"Input file '{fname:s}' to 'test_all_world2pix' not found.") h = fits.open(fname) w = wcs.WCS(h[ext].header, h) h.close() del h crpix = w.wcs.crpix ncoord = crpix.shape[0] # Assume that CRPIX is at the center of the image and that the image has # a power-of-2 number of pixels along each axis. Only use the central # 1/64 for this testing purpose: naxesi_l = list((7. / 16 * crpix).astype(int)) naxesi_u = list((9. / 16 * crpix).astype(int)) # Generate integer indices of pixels (image grid): img_pix = np.dstack([i.flatten() for i in np.meshgrid(*map(range, naxesi_l, naxesi_u))])[0] # Generage random data (in image coordinates): with NumpyRNGContext(123456789): rnd_pix = np.random.rand(random_npts, ncoord) # Scale random data to cover the central part of the image mwidth = 2 * (crpix * 1. / 8) rnd_pix = crpix - 0.5 * mwidth + (mwidth - 1) * rnd_pix # Reference pixel coordinates in image coordinate system (CS): test_pix = np.append(img_pix, rnd_pix, axis=0) # Reference pixel coordinates in sky CS using forward transformation: all_world = w.all_pix2world(test_pix, origin) try: runtime_begin = datetime.now() # Apply the inverse iterative process to pixels in world coordinates # to recover the pixel coordinates in image space. all_pix = w.all_world2pix( all_world, origin, tolerance=tolerance, adaptive=adaptive, maxiter=maxiter, detect_divergence=detect_divergence) runtime_end = datetime.now() except wcs.wcs.NoConvergence as e: runtime_end = datetime.now() ndiv = 0 if e.divergent is not None: ndiv = e.divergent.shape[0] print(f"There are {ndiv} diverging solutions.") print(f"Indices of diverging solutions:\n{e.divergent}") print(f"Diverging solutions:\n{e.best_solution[e.divergent]}\n") print("Mean radius of the diverging solutions: {}" .format(np.mean( np.linalg.norm(e.best_solution[e.divergent], axis=1)))) print("Mean accuracy of the diverging solutions: {}\n" .format(np.mean( np.linalg.norm(e.accuracy[e.divergent], axis=1)))) else: print("There are no diverging solutions.") nslow = 0 if e.slow_conv is not None: nslow = e.slow_conv.shape[0] print(f"There are {nslow} slowly converging solutions.") print(f"Indices of slowly converging solutions:\n{e.slow_conv}") print(f"Slowly converging solutions:\n{e.best_solution[e.slow_conv]}\n") else: print("There are no slowly converging solutions.\n") print("There are {} converged solutions." .format(e.best_solution.shape[0] - ndiv - nslow)) print(f"Best solutions (all points):\n{e.best_solution}") print(f"Accuracy:\n{e.accuracy}\n") print("\nFinished running 'test_all_world2pix' with errors.\n" "ERROR: {}\nRun time: {}\n" .format(e.args[0], runtime_end - runtime_begin)) raise e # Compute differences between reference pixel coordinates and # pixel coordinates (in image space) recovered from reference # pixels in world coordinates: errors = np.sqrt(np.sum(np.power(all_pix - test_pix, 2), axis=1)) meanerr = np.mean(errors) maxerr = np.amax(errors) print("\nFinished running 'test_all_world2pix'.\n" "Mean error = {:e} (Max error = {:e})\n" "Run time: {}\n" .format(meanerr, maxerr, runtime_end - runtime_begin)) assert(maxerr < 2.0 * tolerance) def test_scamp_sip_distortion_parameters(): """ Test parsing of WCS parameters with redundant SIP and SCAMP distortion parameters. """ header = get_pkg_data_contents('data/validate.fits', encoding='binary') with pytest.warns(wcs.FITSFixedWarning): w = wcs.WCS(header) # Just check that this doesn't raise an exception. w.all_pix2world(0, 0, 0) def test_fixes2(): """ From github issue #1854 """ header = get_pkg_data_contents( 'data/nonstandard_units.hdr', encoding='binary') with pytest.raises(wcs.InvalidTransformError): wcs.WCS(header, fix=False) def test_unit_normalization(): """ From github issue #1918 """ header = get_pkg_data_contents( 'data/unit.hdr', encoding='binary') w = wcs.WCS(header) assert w.wcs.cunit[2] == 'm/s' def test_footprint_to_file(tmpdir): """ From github issue #1912 """ # Arbitrary keywords from real data hdr = {'CTYPE1': 'RA---ZPN', 'CRUNIT1': 'deg', 'CRPIX1': -3.3495999e+02, 'CRVAL1': 3.185790700000e+02, 'CTYPE2': 'DEC--ZPN', 'CRUNIT2': 'deg', 'CRPIX2': 3.0453999e+03, 'CRVAL2': 4.388538000000e+01, 'PV2_1': 1., 'PV2_3': 220., 'NAXIS1': 2048, 'NAXIS2': 1024} w = wcs.WCS(hdr) testfile = str(tmpdir.join('test.txt')) w.footprint_to_file(testfile) with open(testfile, 'r') as f: lines = f.readlines() assert len(lines) == 4 assert lines[2] == 'ICRS\n' assert 'color=green' in lines[3] w.footprint_to_file(testfile, coordsys='FK5', color='red') with open(testfile, 'r') as f: lines = f.readlines() assert len(lines) == 4 assert lines[2] == 'FK5\n' assert 'color=red' in lines[3] with pytest.raises(ValueError): w.footprint_to_file(testfile, coordsys='FOO') del hdr['NAXIS1'] del hdr['NAXIS2'] w = wcs.WCS(hdr) with pytest.warns(AstropyUserWarning): w.footprint_to_file(testfile) # Ignore FITSFixedWarning about keyrecords following the END keyrecord were # ignored, which comes from src/astropy_wcs.c . Only a blind catch like this # seems to work when pytest warnings are turned into exceptions. @pytest.mark.filterwarnings('ignore') def test_validate_faulty_wcs(): """ From github issue #2053 """ h = fits.Header() # Illegal WCS: h['RADESYSA'] = 'ICRS' h['PV2_1'] = 1.0 hdu = fits.PrimaryHDU([[0]], header=h) hdulist = fits.HDUList([hdu]) # Check that this doesn't raise a NameError exception wcs.validate(hdulist) def test_error_message(): header = get_pkg_data_contents( 'data/invalid_header.hdr', encoding='binary') with pytest.raises(wcs.InvalidTransformError): # Both lines are in here, because 0.4 calls .set within WCS.__init__, # whereas 0.3 and earlier did not. with pytest.warns(wcs.FITSFixedWarning): w = wcs.WCS(header, _do_set=False) w.all_pix2world([[536.0, 894.0]], 0) def test_out_of_bounds(): # See #2107 header = get_pkg_data_contents('data/zpn-hole.hdr', encoding='binary') w = wcs.WCS(header) ra, dec = w.wcs_pix2world(110, 110, 0) assert np.isnan(ra) assert np.isnan(dec) ra, dec = w.wcs_pix2world(0, 0, 0) assert not np.isnan(ra) assert not np.isnan(dec) def test_calc_footprint_1(): fits = get_pkg_data_filename('data/sip.fits') with pytest.warns(wcs.FITSFixedWarning): w = wcs.WCS(fits) axes = (1000, 1051) ref = np.array([[202.39314493, 47.17753352], [202.71885939, 46.94630488], [202.94631893, 47.15855022], [202.72053428, 47.37893142]]) footprint = w.calc_footprint(axes=axes) assert_allclose(footprint, ref) def test_calc_footprint_2(): """ Test calc_footprint without distortion. """ fits = get_pkg_data_filename('data/sip.fits') with pytest.warns(wcs.FITSFixedWarning): w = wcs.WCS(fits) axes = (1000, 1051) ref = np.array([[202.39265216, 47.17756518], [202.7469062, 46.91483312], [203.11487481, 47.14359319], [202.76092671, 47.40745948]]) footprint = w.calc_footprint(axes=axes, undistort=False) assert_allclose(footprint, ref) def test_calc_footprint_3(): """ Test calc_footprint with corner of the pixel.""" w = wcs.WCS() w.wcs.ctype = ["GLON-CAR", "GLAT-CAR"] w.wcs.crpix = [1.5, 5.5] w.wcs.cdelt = [-0.1, 0.1] axes = (2, 10) ref = np.array([[0.1, -0.5], [0.1, 0.5], [359.9, 0.5], [359.9, -0.5]]) footprint = w.calc_footprint(axes=axes, undistort=False, center=False) assert_allclose(footprint, ref) def test_sip(): # See #2107 header = get_pkg_data_contents('data/irac_sip.hdr', encoding='binary') w = wcs.WCS(header) x0, y0 = w.sip_pix2foc(200, 200, 0) assert_allclose(72, x0, 1e-3) assert_allclose(72, y0, 1e-3) x1, y1 = w.sip_foc2pix(x0, y0, 0) assert_allclose(200, x1, 1e-3) assert_allclose(200, y1, 1e-3) def test_sub_3d_with_sip(): # See #10527 header = get_pkg_data_contents('data/irac_sip.hdr', encoding='binary') header = fits.Header.fromstring(header) header['NAXIS'] = 3 header.set('NAXIS3', 64, after=header.index('NAXIS2')) w = wcs.WCS(header, naxis=2) assert w.naxis == 2 def test_printwcs(capsys): """ Just make sure that it runs """ h = get_pkg_data_contents( 'data/spectra/orion-freq-1.hdr', encoding='binary') with pytest.warns(wcs.FITSFixedWarning): w = wcs.WCS(h) w.printwcs() captured = capsys.readouterr() assert 'WCS Keywords' in captured.out h = get_pkg_data_contents('data/3d_cd.hdr', encoding='binary') w = wcs.WCS(h) w.printwcs() captured = capsys.readouterr() assert 'WCS Keywords' in captured.out def test_invalid_spherical(): header = """ SIMPLE = T / conforms to FITS standard BITPIX = 8 / array data type WCSAXES = 2 / no comment CTYPE1 = 'RA---TAN' / TAN (gnomic) projection CTYPE2 = 'DEC--TAN' / TAN (gnomic) projection EQUINOX = 2000.0 / Equatorial coordinates definition (yr) LONPOLE = 180.0 / no comment LATPOLE = 0.0 / no comment CRVAL1 = 16.0531567459 / RA of reference point CRVAL2 = 23.1148929108 / DEC of reference point CRPIX1 = 2129 / X reference pixel CRPIX2 = 1417 / Y reference pixel CUNIT1 = 'deg ' / X pixel scale units CUNIT2 = 'deg ' / Y pixel scale units CD1_1 = -0.00912247310646 / Transformation matrix CD1_2 = -0.00250608809647 / no comment CD2_1 = 0.00250608809647 / no comment CD2_2 = -0.00912247310646 / no comment IMAGEW = 4256 / Image width, in pixels. IMAGEH = 2832 / Image height, in pixels. """ f = io.StringIO(header) header = fits.Header.fromtextfile(f) w = wcs.WCS(header) x, y = w.wcs_world2pix(211, -26, 0) assert np.isnan(x) and np.isnan(y) def test_no_iteration(): # Regression test for #3066 w = wcs.WCS(naxis=2) with pytest.raises(TypeError) as exc: iter(w) assert exc.value.args[0] == "'WCS' object is not iterable" class NewWCS(wcs.WCS): pass w = NewWCS(naxis=2) with pytest.raises(TypeError) as exc: iter(w) assert exc.value.args[0] == "'NewWCS' object is not iterable" @pytest.mark.skipif('_wcs.__version__[0] < "5"', reason="TPV only works with wcslib 5.x or later") def test_sip_tpv_agreement(): sip_header = get_pkg_data_contents( os.path.join("data", "siponly.hdr"), encoding='binary') tpv_header = get_pkg_data_contents( os.path.join("data", "tpvonly.hdr"), encoding='binary') with pytest.warns(wcs.FITSFixedWarning): w_sip = wcs.WCS(sip_header) w_tpv = wcs.WCS(tpv_header) assert_array_almost_equal( w_sip.all_pix2world([w_sip.wcs.crpix], 1), w_tpv.all_pix2world([w_tpv.wcs.crpix], 1)) w_sip2 = wcs.WCS(w_sip.to_header()) w_tpv2 = wcs.WCS(w_tpv.to_header()) assert_array_almost_equal( w_sip.all_pix2world([w_sip.wcs.crpix], 1), w_sip2.all_pix2world([w_sip.wcs.crpix], 1)) assert_array_almost_equal( w_tpv.all_pix2world([w_sip.wcs.crpix], 1), w_tpv2.all_pix2world([w_sip.wcs.crpix], 1)) assert_array_almost_equal( w_sip2.all_pix2world([w_sip.wcs.crpix], 1), w_tpv2.all_pix2world([w_tpv.wcs.crpix], 1)) @pytest.mark.skipif('_wcs.__version__[0] < "5"', reason="TPV only works with wcslib 5.x or later") def test_tpv_copy(): # See #3904 tpv_header = get_pkg_data_contents( os.path.join("data", "tpvonly.hdr"), encoding='binary') with pytest.warns(wcs.FITSFixedWarning): w_tpv = wcs.WCS(tpv_header) ra, dec = w_tpv.wcs_pix2world([0, 100, 200], [0, -100, 200], 0) assert ra[0] != ra[1] and ra[1] != ra[2] assert dec[0] != dec[1] and dec[1] != dec[2] def test_hst_wcs(): path = get_pkg_data_filename("data/dist_lookup.fits.gz") with fits.open(path) as hdulist: # wcslib will complain about the distortion parameters if they # weren't correctly deleted from the header w = wcs.WCS(hdulist[1].header, hdulist) # Check pixel scale and area assert_quantity_allclose( w.proj_plane_pixel_scales(), [1.38484378e-05, 1.39758488e-05] * u.deg) assert_quantity_allclose( w.proj_plane_pixel_area(), 1.93085492e-10 * (u.deg * u.deg)) # Exercise the main transformation functions, mainly just for # coverage w.p4_pix2foc([0, 100, 200], [0, -100, 200], 0) w.det2im([0, 100, 200], [0, -100, 200], 0) w.cpdis1 = w.cpdis1 w.cpdis2 = w.cpdis2 w.det2im1 = w.det2im1 w.det2im2 = w.det2im2 w.sip = w.sip w.cpdis1.cdelt = w.cpdis1.cdelt w.cpdis1.crpix = w.cpdis1.crpix w.cpdis1.crval = w.cpdis1.crval w.cpdis1.data = w.cpdis1.data assert w.sip.a_order == 4 assert w.sip.b_order == 4 assert w.sip.ap_order == 0 assert w.sip.bp_order == 0 assert_array_equal(w.sip.crpix, [2048., 1024.]) wcs.WCS(hdulist[1].header, hdulist) def test_cpdis_comments(): path = get_pkg_data_filename("data/dist_lookup.fits.gz") f = fits.open(path) w = wcs.WCS(f[1].header, f) hdr = w.to_fits()[0].header f.close() wcscards = list(hdr['CPDIS*'].cards) + list(hdr['DP*'].cards) wcsdict = {k: (v, c) for k, v, c in wcscards} refcards = [ ('CPDIS1', 'LOOKUP', 'Prior distortion function type'), ('DP1.EXTVER', 1.0, 'Version number of WCSDVARR extension'), ('DP1.NAXES', 2.0, 'Number of independent variables in CPDIS function'), ('DP1.AXIS.1', 1.0, 'Axis number of the 1st variable in a CPDIS function'), ('DP1.AXIS.2', 2.0, 'Axis number of the 2nd variable in a CPDIS function'), ('CPDIS2', 'LOOKUP', 'Prior distortion function type'), ('DP2.EXTVER', 2.0, 'Version number of WCSDVARR extension'), ('DP2.NAXES', 2.0, 'Number of independent variables in CPDIS function'), ('DP2.AXIS.1', 1.0, 'Axis number of the 1st variable in a CPDIS function'), ('DP2.AXIS.2', 2.0, 'Axis number of the 2nd variable in a CPDIS function'), ] assert len(wcsdict) == len(refcards) for k, v, c in refcards: assert wcsdict[k] == (v, c) def test_d2im_comments(): path = get_pkg_data_filename("data/ie6d07ujq_wcs.fits") f = fits.open(path) with pytest.warns(wcs.FITSFixedWarning): w = wcs.WCS(f[0].header, f) f.close() wcscards = list(w.to_fits()[0].header['D2IM*'].cards) wcsdict = {k: (v, c) for k, v, c in wcscards} refcards = [ ('D2IMDIS1', 'LOOKUP', 'Detector to image correction type'), ('D2IM1.EXTVER', 1.0, 'Version number of WCSDVARR extension'), ('D2IM1.NAXES', 2.0, 'Number of independent variables in D2IM function'), ('D2IM1.AXIS.1', 1.0, 'Axis number of the 1st variable in a D2IM function'), ('D2IM1.AXIS.2', 2.0, 'Axis number of the 2nd variable in a D2IM function'), ('D2IMDIS2', 'LOOKUP', 'Detector to image correction type'), ('D2IM2.EXTVER', 2.0, 'Version number of WCSDVARR extension'), ('D2IM2.NAXES', 2.0, 'Number of independent variables in D2IM function'), ('D2IM2.AXIS.1', 1.0, 'Axis number of the 1st variable in a D2IM function'), ('D2IM2.AXIS.2', 2.0, 'Axis number of the 2nd variable in a D2IM function'), # ('D2IMERR1', 0.049, 'Maximum error of D2IM correction for axis 1'), # ('D2IMERR2', 0.035, 'Maximum error of D2IM correction for axis 2'), # ('D2IMEXT', 'iref$y7b1516hi_d2i.fits', ''), ] assert len(wcsdict) == len(refcards) for k, v, c in refcards: assert wcsdict[k] == (v, c) def test_sip_broken(): # This header caused wcslib to segfault because it has a SIP # specification in a non-default keyword hdr = get_pkg_data_contents("data/sip-broken.hdr") wcs.WCS(hdr) def test_no_truncate_crval(): """ Regression test for https://github.com/astropy/astropy/issues/4612 """ w = wcs.WCS(naxis=3) w.wcs.crval = [50, 50, 2.12345678e11] w.wcs.cdelt = [1e-3, 1e-3, 1e8] w.wcs.ctype = ['RA---TAN', 'DEC--TAN', 'FREQ'] w.wcs.set() header = w.to_header() for ii in range(3): assert header[f'CRVAL{ii + 1}'] == w.wcs.crval[ii] assert header[f'CDELT{ii + 1}'] == w.wcs.cdelt[ii] def test_no_truncate_crval_try2(): """ Regression test for https://github.com/astropy/astropy/issues/4612 """ w = wcs.WCS(naxis=3) w.wcs.crval = [50, 50, 2.12345678e11] w.wcs.cdelt = [1e-5, 1e-5, 1e5] w.wcs.ctype = ['RA---SIN', 'DEC--SIN', 'FREQ'] w.wcs.cunit = ['deg', 'deg', 'Hz'] w.wcs.crpix = [1, 1, 1] w.wcs.restfrq = 2.34e11 w.wcs.set() header = w.to_header() for ii in range(3): assert header[f'CRVAL{ii + 1}'] == w.wcs.crval[ii] assert header[f'CDELT{ii + 1}'] == w.wcs.cdelt[ii] def test_no_truncate_crval_p17(): """ Regression test for https://github.com/astropy/astropy/issues/5162 """ w = wcs.WCS(naxis=2) w.wcs.crval = [50.1234567890123456, 50.1234567890123456] w.wcs.cdelt = [1e-3, 1e-3] w.wcs.ctype = ['RA---TAN', 'DEC--TAN'] w.wcs.set() header = w.to_header() assert header['CRVAL1'] != w.wcs.crval[0] assert header['CRVAL2'] != w.wcs.crval[1] header = w.to_header(relax=wcs.WCSHDO_P17) assert header['CRVAL1'] == w.wcs.crval[0] assert header['CRVAL2'] == w.wcs.crval[1] def test_no_truncate_using_compare(): """ Regression test for https://github.com/astropy/astropy/issues/4612 This one uses WCS.wcs.compare and some slightly different values """ w = wcs.WCS(naxis=3) w.wcs.crval = [2.409303333333E+02, 50, 2.12345678e11] w.wcs.cdelt = [1e-3, 1e-3, 1e8] w.wcs.ctype = ['RA---TAN', 'DEC--TAN', 'FREQ'] w.wcs.set() w2 = wcs.WCS(w.to_header()) w.wcs.compare(w2.wcs) def test_passing_ImageHDU(): """ Passing ImageHDU or PrimaryHDU and comparing it with wcs initialized from header. For #4493. """ path = get_pkg_data_filename('data/validate.fits') with fits.open(path) as hdulist: with pytest.warns(wcs.FITSFixedWarning): wcs_hdu = wcs.WCS(hdulist[0]) wcs_header = wcs.WCS(hdulist[0].header) assert wcs_hdu.wcs.compare(wcs_header.wcs) wcs_hdu = wcs.WCS(hdulist[1]) wcs_header = wcs.WCS(hdulist[1].header) assert wcs_hdu.wcs.compare(wcs_header.wcs) def test_inconsistent_sip(): """ Test for #4814 """ hdr = get_pkg_data_contents("data/sip-broken.hdr") ctx = ctx_for_v71_dateref_warnings() with ctx: w = wcs.WCS(hdr) with pytest.warns(AstropyWarning): newhdr = w.to_header(relax=None) # CTYPE should not include "-SIP" if relax is None with ctx: wnew = wcs.WCS(newhdr) assert all(not ctyp.endswith('-SIP') for ctyp in wnew.wcs.ctype) newhdr = w.to_header(relax=False) assert 'A_0_2' not in newhdr # CTYPE should not include "-SIP" if relax is False with ctx: wnew = wcs.WCS(newhdr) assert all(not ctyp.endswith('-SIP') for ctyp in wnew.wcs.ctype) with pytest.warns(AstropyWarning): newhdr = w.to_header(key="C") assert 'A_0_2' not in newhdr # Test writing header with a different key with ctx: wnew = wcs.WCS(newhdr, key='C') assert all(not ctyp.endswith('-SIP') for ctyp in wnew.wcs.ctype) with pytest.warns(AstropyWarning): newhdr = w.to_header(key=" ") # Test writing a primary WCS to header with ctx: wnew = wcs.WCS(newhdr) assert all(not ctyp.endswith('-SIP') for ctyp in wnew.wcs.ctype) # Test that "-SIP" is kept into CTYPE if relax=True and # "-SIP" was in the original header newhdr = w.to_header(relax=True) with ctx: wnew = wcs.WCS(newhdr) assert all(ctyp.endswith('-SIP') for ctyp in wnew.wcs.ctype) assert 'A_0_2' in newhdr # Test that SIP coefficients are also written out. assert wnew.sip is not None # ######### broken header ########### # Test that "-SIP" is added to CTYPE if relax=True and # "-SIP" was not in the original header but SIP coefficients # are present. with ctx: w = wcs.WCS(hdr) w.wcs.ctype = ['RA---TAN', 'DEC--TAN'] newhdr = w.to_header(relax=True) with ctx: wnew = wcs.WCS(newhdr) assert all(ctyp.endswith('-SIP') for ctyp in wnew.wcs.ctype) def test_bounds_check(): """Test for #4957""" w = wcs.WCS(naxis=2) w.wcs.ctype = ["RA---CAR", "DEC--CAR"] w.wcs.cdelt = [10, 10] w.wcs.crval = [-90, 90] w.wcs.crpix = [1, 1] w.wcs.bounds_check(False, False) ra, dec = w.wcs_pix2world(300, 0, 0) assert_allclose(ra, -180) assert_allclose(dec, -30) def test_naxis(): w = wcs.WCS(naxis=2) w.wcs.crval = [1, 1] w.wcs.cdelt = [0.1, 0.1] w.wcs.crpix = [1, 1] w._naxis = [1000, 500] assert w.pixel_shape == (1000, 500) assert w.array_shape == (500, 1000) w.pixel_shape = (99, 59) assert w._naxis == [99, 59] w.array_shape = (45, 23) assert w._naxis == [23, 45] assert w.pixel_shape == (23, 45) w.pixel_shape = None assert w.pixel_bounds is None def test_sip_with_altkey(): """ Test that when creating a WCS object using a key, CTYPE with that key is looked at and not the primary CTYPE. fix for #5443. """ with fits.open(get_pkg_data_filename('data/sip.fits')) as f: with pytest.warns(wcs.FITSFixedWarning): w = wcs.WCS(f[0].header) # create a header with two WCSs. h1 = w.to_header(relax=True, key='A') h2 = w.to_header(relax=False) h1['CTYPE1A'] = "RA---SIN-SIP" h1['CTYPE2A'] = "DEC--SIN-SIP" h1.update(h2) with ctx_for_v71_dateref_warnings(): w = wcs.WCS(h1, key='A') assert (w.wcs.ctype == np.array(['RA---SIN-SIP', 'DEC--SIN-SIP'])).all() def test_to_fits_1(): """ Test to_fits() with LookupTable distortion. """ fits_name = get_pkg_data_filename('data/dist.fits') with pytest.warns(AstropyDeprecationWarning): w = wcs.WCS(fits_name) wfits = w.to_fits() assert isinstance(wfits, fits.HDUList) assert isinstance(wfits[0], fits.PrimaryHDU) assert isinstance(wfits[1], fits.ImageHDU) def test_keyedsip(): """ Test sip reading with extra key. """ hdr_name = get_pkg_data_filename('data/sip-broken.hdr') header = fits.Header.fromfile(hdr_name) del header["CRPIX1"] del header["CRPIX2"] w = wcs.WCS(header=header, key="A") assert isinstance(w.sip, wcs.Sip) assert w.sip.crpix[0] == 2048 assert w.sip.crpix[1] == 1026 def test_zero_size_input(): with fits.open(get_pkg_data_filename('data/sip.fits')) as f: with pytest.warns(wcs.FITSFixedWarning): w = wcs.WCS(f[0].header) inp = np.zeros((0, 2)) assert_array_equal(inp, w.all_pix2world(inp, 0)) assert_array_equal(inp, w.all_world2pix(inp, 0)) inp = [], [1] result = w.all_pix2world([], [1], 0) assert_array_equal(inp[0], result[0]) assert_array_equal(inp[1], result[1]) result = w.all_world2pix([], [1], 0) assert_array_equal(inp[0], result[0]) assert_array_equal(inp[1], result[1]) def test_scalar_inputs(): """ Issue #7845 """ wcsobj = wcs.WCS(naxis=1) result = wcsobj.all_pix2world(2, 1) assert_array_equal(result, [np.array(2.)]) assert result[0].shape == () result = wcsobj.all_pix2world([2], 1) assert_array_equal(result, [np.array([2.])]) assert result[0].shape == (1,) # Ignore RuntimeWarning raised on s390. @pytest.mark.filterwarnings('ignore:.*invalid value encountered in.*') def test_footprint_contains(): """ Test WCS.footprint_contains(skycoord) """ header = """ WCSAXES = 2 / Number of coordinate axes CRPIX1 = 1045.0 / Pixel coordinate of reference point CRPIX2 = 1001.0 / Pixel coordinate of reference point PC1_1 = -0.00556448550786 / Coordinate transformation matrix element PC1_2 = -0.001042120133257 / Coordinate transformation matrix element PC2_1 = 0.001181477028705 / Coordinate transformation matrix element PC2_2 = -0.005590809742987 / Coordinate transformation matrix element CDELT1 = 1.0 / [deg] Coordinate increment at reference point CDELT2 = 1.0 / [deg] Coordinate increment at reference point CUNIT1 = 'deg' / Units of coordinate increment and value CUNIT2 = 'deg' / Units of coordinate increment and value CTYPE1 = 'RA---TAN' / TAN (gnomonic) projection + SIP distortions CTYPE2 = 'DEC--TAN' / TAN (gnomonic) projection + SIP distortions CRVAL1 = 250.34971683647 / [deg] Coordinate value at reference point CRVAL2 = 2.2808772582495 / [deg] Coordinate value at reference point LONPOLE = 180.0 / [deg] Native longitude of celestial pole LATPOLE = 2.2808772582495 / [deg] Native latitude of celestial pole RADESYS = 'ICRS' / Equatorial coordinate system MJD-OBS = 58612.339199259 / [d] MJD of observation matching DATE-OBS DATE-OBS= '2019-05-09T08:08:26.816Z' / ISO-8601 observation date matching MJD-OB NAXIS = 2 / NAXIS NAXIS1 = 2136 / length of first array dimension NAXIS2 = 2078 / length of second array dimension """ # noqa header = fits.Header.fromstring(header.strip(), '\n') test_wcs = wcs.WCS(header) hasCoord = test_wcs.footprint_contains(SkyCoord(254, 2, unit='deg')) assert hasCoord hasCoord = test_wcs.footprint_contains(SkyCoord(240, 2, unit='deg')) assert not hasCoord hasCoord = test_wcs.footprint_contains(SkyCoord(24, 2, unit='deg')) assert not hasCoord def test_cunit(): # Initializing WCS w1 = wcs.WCS(naxis=2) w2 = wcs.WCS(naxis=2) w3 = wcs.WCS(naxis=2) w4 = wcs.WCS(naxis=2) # Initializing the values of cunit w1.wcs.cunit = ['deg', 'm/s'] w2.wcs.cunit = ['km/h', 'km/h'] w3.wcs.cunit = ['deg', 'm/s'] w4.wcs.cunit = ['deg', 'deg'] # Equality checking a cunit with itself assert w1.wcs.cunit == w1.wcs.cunit assert not w1.wcs.cunit != w1.wcs.cunit # Equality checking of two different cunit object having same values assert w1.wcs.cunit == w3.wcs.cunit assert not w1.wcs.cunit != w3.wcs.cunit # Equality checking of two different cunit object having the same first unit # but different second unit (see #9154) assert not w1.wcs.cunit == w4.wcs.cunit assert w1.wcs.cunit != w4.wcs.cunit # Inequality checking of two different cunit object having different values assert not w1.wcs.cunit == w2.wcs.cunit assert w1.wcs.cunit != w2.wcs.cunit # Inequality checking of cunit with a list of literals assert not w1.wcs.cunit == [1, 2, 3] assert w1.wcs.cunit != [1, 2, 3] # Inequality checking with some characters assert not w1.wcs.cunit == ['a', 'b', 'c'] assert w1.wcs.cunit != ['a', 'b', 'c'] # Comparison is not implemented TypeError will raise with pytest.raises(TypeError): w1.wcs.cunit < w2.wcs.cunit class TestWcsWithTime: def setup(self): if _WCSLIB_VER >= Version('7.1'): fname = get_pkg_data_filename('data/header_with_time_wcslib71.fits') else: fname = get_pkg_data_filename('data/header_with_time.fits') self.header = fits.Header.fromfile(fname) with pytest.warns(wcs.FITSFixedWarning): self.w = wcs.WCS(self.header, key='A') def test_keywods2wcsprm(self): """ Make sure Wcsprm is populated correctly from the header.""" ctype = [self.header[val] for val in self.header["CTYPE*"]] crval = [self.header[val] for val in self.header["CRVAL*"]] crpix = [self.header[val] for val in self.header["CRPIX*"]] cdelt = [self.header[val] for val in self.header["CDELT*"]] cunit = [self.header[val] for val in self.header["CUNIT*"]] assert list(self.w.wcs.ctype) == ctype assert list(self.w.wcs.axis_types) == [2200, 2201, 3300, 0] assert_allclose(self.w.wcs.crval, crval) assert_allclose(self.w.wcs.crpix, crpix) assert_allclose(self.w.wcs.cdelt, cdelt) assert list(self.w.wcs.cunit) == cunit naxis = self.w.naxis assert naxis == 4 pc = np.zeros((naxis, naxis), dtype=np.float64) for i in range(1, 5): for j in range(1, 5): if i == j: pc[i-1, j-1] = self.header.get(f'PC{i}_{j}A', 1) else: pc[i-1, j-1] = self.header.get(f'PC{i}_{j}A', 0) assert_allclose(self.w.wcs.pc, pc) char_keys = ['timesys', 'trefpos', 'trefdir', 'plephem', 'timeunit', 'dateref', 'dateobs', 'datebeg', 'dateavg', 'dateend'] for key in char_keys: assert getattr(self.w.wcs, key) == self.header.get(key, "") num_keys = ['mjdref', 'mjdobs', 'mjdbeg', 'mjdend', 'jepoch', 'bepoch', 'tstart', 'tstop', 'xposure', 'timsyer', 'timrder', 'timedel', 'timepixr', 'timeoffs', 'telapse', 'czphs', 'cperi'] for key in num_keys: if key.upper() == 'MJDREF': hdrv = [self.header.get('MJDREFIA', np.nan), self.header.get('MJDREFFA', np.nan)] else: hdrv = self.header.get(key, np.nan) assert_allclose(getattr(self.w.wcs, key), hdrv) def test_transforms(self): assert_allclose(self.w.all_pix2world(*self.w.wcs.crpix, 1), self.w.wcs.crval) def test_invalid_coordinate_masking(): # Regression test for an issue which caused all coordinates to be set to NaN # after a transformation rather than just the invalid ones as reported by # WCSLIB. A specific example of this is that when considering an all-sky # spectral cube with a spectral axis that is not correlated with the sky # axes, if transforming pixel coordinates that did not fall 'in' the sky, # the spectral world value was also masked even though that coordinate # was valid. w = wcs.WCS(naxis=3) w.wcs.ctype = 'VELO_LSR', 'GLON-CAR', 'GLAT-CAR' w.wcs.crval = -20, 0, 0 w.wcs.crpix = 1, 1441, 241 w.wcs.cdelt = 1.3, -0.125, 0.125 px = [-10, -10, 20] py = [-10, 10, 20] pz = [-10, 10, 20] wx, wy, wz = w.wcs_pix2world(px, py, pz, 0) # Before fixing this, wx used to return np.nan for the first element assert_allclose(wx, [-33, -33, 6]) assert_allclose(wy, [np.nan, 178.75, 177.5]) assert_allclose(wz, [np.nan, -28.75, -27.5]) def test_no_pixel_area(): w = wcs.WCS(naxis=3) # Pixel area cannot be computed with pytest.raises(ValueError, match='Pixel area is defined only for 2D pixels'): w.proj_plane_pixel_area() # Pixel scales still possible assert_quantity_allclose(w.proj_plane_pixel_scales(), 1) def test_distortion_header(tmpdir): """ Test that plate distortion model is correctly described by `wcs.to_header()` and preserved when creating a Cutout2D from the image, writing it to FITS, and reading it back from the file. """ path = get_pkg_data_filename("data/dss.14.29.56-62.41.05.fits.gz") cen = np.array((50, 50)) siz = np.array((20, 20)) with fits.open(path) as hdulist: with pytest.warns(wcs.FITSFixedWarning): w = wcs.WCS(hdulist[0].header) cut = Cutout2D(hdulist[0].data, position=cen, size=siz, wcs=w) # This converts the DSS plate solution model with AMD[XY]n coefficients into a # Template Polynomial Distortion model (TPD.FWD.n coefficients); # not testing explicitly for the header keywords here. if _WCSLIB_VER < Version("7.4"): with pytest.warns(AstropyWarning, match="WCS contains a TPD distortion model in CQDIS"): w0 = wcs.WCS(w.to_header_string()) with pytest.warns(AstropyWarning, match="WCS contains a TPD distortion model in CQDIS"): w1 = wcs.WCS(cut.wcs.to_header_string()) if _WCSLIB_VER >= Version("7.1"): pytest.xfail("TPD coefficients incomplete with WCSLIB >= 7.1 < 7.4") else: w0 = wcs.WCS(w.to_header_string()) w1 = wcs.WCS(cut.wcs.to_header_string()) assert w.pixel_to_world(0, 0).separation(w0.pixel_to_world(0, 0)) < 1.e-3 * u.mas assert w.pixel_to_world(*cen).separation(w0.pixel_to_world(*cen)) < 1.e-3 * u.mas assert w.pixel_to_world(*cen).separation(w1.pixel_to_world(*(siz / 2))) < 1.e-3 * u.mas cutfile = str(tmpdir.join('cutout.fits')) fits.writeto(cutfile, cut.data, cut.wcs.to_header()) with fits.open(cutfile) as hdulist: w2 = wcs.WCS(hdulist[0].header) assert w.pixel_to_world(*cen).separation(w2.pixel_to_world(*(siz / 2))) < 1.e-3 * u.mas def test_pixlist_wcs_colsel(): """ Test selection of a specific pixel list WCS using ``colsel``. See #11412. """ hdr_file = get_pkg_data_filename('data/chandra-pixlist-wcs.hdr') hdr = fits.Header.fromtextfile(hdr_file) with pytest.warns(wcs.FITSFixedWarning): w = wcs.WCS(hdr, keysel=['image', 'pixel'], colsel=[11, 12]) assert w.naxis == 2 assert list(w.wcs.ctype) == ['RA---TAN', 'DEC--TAN'] assert np.allclose(w.wcs.crval, [229.38051931869, -58.81108068885]) assert np.allclose(w.wcs.pc, [[1, 0], [0, 1]]) assert np.allclose(w.wcs.cdelt, [-0.00013666666666666, 0.00013666666666666]) assert np.allclose(w.wcs.lonpole, 180.)
3656d992f8c047385bb138dc0fb5169dab71eba42790b0712ab14136a1dd4fe7
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os import pickle import numpy as np import pytest from numpy.testing import assert_array_almost_equal from astropy.utils.data import (get_pkg_data_contents, get_pkg_data_fileobj, get_pkg_data_filename) from astropy.utils.exceptions import AstropyDeprecationWarning from astropy.utils.misc import NumpyRNGContext from astropy.io import fits from astropy.io.fits.verify import VerifyWarning from astropy import wcs from astropy.wcs.wcs import FITSFixedWarning def test_basic(): wcs1 = wcs.WCS() s = pickle.dumps(wcs1) pickle.loads(s) def test_dist(): with get_pkg_data_fileobj( os.path.join("data", "dist.fits"), encoding='binary') as test_file: hdulist = fits.open(test_file) # The use of ``AXISCORR`` for D2IM correction has been deprecated with pytest.warns(AstropyDeprecationWarning): wcs1 = wcs.WCS(hdulist[0].header, hdulist) assert wcs1.det2im2 is not None s = pickle.dumps(wcs1) wcs2 = pickle.loads(s) with NumpyRNGContext(123456789): x = np.random.rand(2 ** 16, wcs1.wcs.naxis) world1 = wcs1.all_pix2world(x, 1) world2 = wcs2.all_pix2world(x, 1) assert_array_almost_equal(world1, world2) def test_sip(): with get_pkg_data_fileobj( os.path.join("data", "sip.fits"), encoding='binary') as test_file: hdulist = fits.open(test_file, ignore_missing_end=True) with pytest.warns(FITSFixedWarning): wcs1 = wcs.WCS(hdulist[0].header) assert wcs1.sip is not None s = pickle.dumps(wcs1) wcs2 = pickle.loads(s) with NumpyRNGContext(123456789): x = np.random.rand(2 ** 16, wcs1.wcs.naxis) world1 = wcs1.all_pix2world(x, 1) world2 = wcs2.all_pix2world(x, 1) assert_array_almost_equal(world1, world2) def test_sip2(): with get_pkg_data_fileobj( os.path.join("data", "sip2.fits"), encoding='binary') as test_file: hdulist = fits.open(test_file, ignore_missing_end=True) with pytest.warns(FITSFixedWarning): wcs1 = wcs.WCS(hdulist[0].header) assert wcs1.sip is not None s = pickle.dumps(wcs1) wcs2 = pickle.loads(s) with NumpyRNGContext(123456789): x = np.random.rand(2 ** 16, wcs1.wcs.naxis) world1 = wcs1.all_pix2world(x, 1) world2 = wcs2.all_pix2world(x, 1) assert_array_almost_equal(world1, world2) # Ignore "PV2_2 = 0.209028857410973 invalid keyvalue" warning seen on Windows. @pytest.mark.filterwarnings(r'ignore:PV2_2') def test_wcs(): header = get_pkg_data_contents( os.path.join("data", "outside_sky.hdr"), encoding='binary') wcs1 = wcs.WCS(header) s = pickle.dumps(wcs1) wcs2 = pickle.loads(s) with NumpyRNGContext(123456789): x = np.random.rand(2 ** 16, wcs1.wcs.naxis) world1 = wcs1.all_pix2world(x, 1) world2 = wcs2.all_pix2world(x, 1) assert_array_almost_equal(world1, world2) class Sub(wcs.WCS): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.foo = 42 def test_subclass(): wcs1 = Sub() wcs1.foo = 45 s = pickle.dumps(wcs1) wcs2 = pickle.loads(s) assert isinstance(wcs2, Sub) assert wcs1.foo == 45 assert wcs2.foo == 45 assert wcs2.wcs is not None def test_axes_info(): w = wcs.WCS(naxis=3) w.pixel_shape = [100, 200, 300] w.pixel_bounds = ((11, 22), (33, 45), (55, 67)) w.extra = 111 w2 = pickle.loads(pickle.dumps(w)) # explicitly test naxis-related info assert w.naxis == w2.naxis assert w.pixel_shape == w2.pixel_shape assert w.pixel_bounds == w2.pixel_bounds # test all attributes for k, v in w.__dict__.items(): assert getattr(w2, k) == v def test_pixlist_wcs_colsel(): """ Test selection of a specific pixel list WCS using ``colsel``. See #11412. """ hdr_file = get_pkg_data_filename('data/chandra-pixlist-wcs.hdr') hdr = fits.Header.fromtextfile(hdr_file) with pytest.warns(wcs.FITSFixedWarning): w0 = wcs.WCS(hdr, keysel=['image', 'pixel'], colsel=[11, 12]) with pytest.warns(wcs.FITSFixedWarning): w = pickle.loads(pickle.dumps(w0)) assert w.naxis == 2 assert list(w.wcs.ctype) == ['RA---TAN', 'DEC--TAN'] assert np.allclose(w.wcs.crval, [229.38051931869, -58.81108068885]) assert np.allclose(w.wcs.pc, [[1, 0], [0, 1]]) assert np.allclose(w.wcs.cdelt, [-0.00013666666666666, 0.00013666666666666]) assert np.allclose(w.wcs.lonpole, 180.) def test_alt_wcskey(): w = wcs.WCS(key='A') w2 = pickle.loads(pickle.dumps(w)) assert w2.wcs.alt == 'A'
bb692d3368e95de20591246fca173267bb5781f1333eb6bc8189fb7bfc2457d2
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest from astropy import wcs from . helper import SimModelTAB @pytest.fixture(scope='module') def tab_wcs_2di(): model = SimModelTAB(nx=150, ny=200) # generate FITS HDU list: hdulist = model.hdulist # create WCS object: w = wcs.WCS(hdulist[0].header, hdulist) return w @pytest.fixture(scope='module') def tab_wcsh_2di(): model = SimModelTAB(nx=150, ny=200) # generate FITS HDU list: hdulist = model.hdulist # create WCS object: w = wcs.WCS(hdulist[0].header, hdulist) return w, hdulist @pytest.fixture(scope='function') def tab_wcs_2di_f(): model = SimModelTAB(nx=150, ny=200) # generate FITS HDU list: hdulist = model.hdulist # create WCS object: w = wcs.WCS(hdulist[0].header, hdulist) return w @pytest.fixture(scope='function') def prj_TAB(): prj = wcs.Prjprm() prj.code = 'TAN' prj.set() return prj
195b355914f32da44dee4ce806ff4e43366b7efdd04fcd04646c0676558afca5
# Licensed under a 3-clause BSD style license - see LICENSE.rst from copy import deepcopy import pytest import numpy as np from astropy import wcs from . helper import SimModelTAB def test_wcsprm_tab_basic(tab_wcs_2di): assert len(tab_wcs_2di.wcs.tab) == 1 t = tab_wcs_2di.wcs.tab[0] assert tab_wcs_2di.wcs.tab[0] is not t def test_tabprm_coord(tab_wcs_2di_f): t = tab_wcs_2di_f.wcs.tab[0] c0 = t.coord c1 = np.ones_like(c0) t.coord = c1 assert np.allclose(tab_wcs_2di_f.wcs.tab[0].coord, c1) def test_tabprm_crval_and_deepcopy(tab_wcs_2di_f): w = deepcopy(tab_wcs_2di_f) t = tab_wcs_2di_f.wcs.tab[0] pix = np.array([[2, 3]], dtype=np.float32) rd1 = tab_wcs_2di_f.wcs_pix2world(pix, 1) c = t.crval.copy() d = 0.5 * np.ones_like(c) t.crval += d assert np.allclose(tab_wcs_2di_f.wcs.tab[0].crval, c + d) rd2 = tab_wcs_2di_f.wcs_pix2world(pix - d, 1) assert np.allclose(rd1, rd2) rd3 = w.wcs_pix2world(pix, 1) assert np.allclose(rd1, rd3) def test_tabprm_delta(tab_wcs_2di): t = tab_wcs_2di.wcs.tab[0] assert np.allclose([0.0, 0.0], t.delta) def test_tabprm_K(tab_wcs_2di): t = tab_wcs_2di.wcs.tab[0] assert np.all(t.K == [4, 2]) def test_tabprm_M(tab_wcs_2di): t = tab_wcs_2di.wcs.tab[0] assert t.M == 2 def test_tabprm_nc(tab_wcs_2di): t = tab_wcs_2di.wcs.tab[0] assert t.nc == 8 def test_tabprm_extrema(tab_wcs_2di): t = tab_wcs_2di.wcs.tab[0] extrema = np.array( [[[-0.0026, -0.5], [1.001, -0.5]], [[-0.0026, 0.5], [1.001, 0.5]]] ) assert np.allclose(t.extrema, extrema) def test_tabprm_map(tab_wcs_2di_f): t = tab_wcs_2di_f.wcs.tab[0] assert np.allclose(t.map, [0, 1]) t.map[1] = 5 assert np.all(tab_wcs_2di_f.wcs.tab[0].map == [0, 5]) t.map = [1, 4] assert np.all(tab_wcs_2di_f.wcs.tab[0].map == [1, 4]) def test_tabprm_sense(tab_wcs_2di): t = tab_wcs_2di.wcs.tab[0] assert np.all(t.sense == [1, 1]) def test_tabprm_p0(tab_wcs_2di): t = tab_wcs_2di.wcs.tab[0] assert np.all(t.p0 == [0, 0]) def test_tabprm_print(tab_wcs_2di_f, capfd): tab_wcs_2di_f.wcs.tab[0].print_contents() captured = capfd.readouterr() s = str(tab_wcs_2di_f.wcs.tab[0]) out = str(captured.out) lout= out.split('\n') assert out == s assert lout[0] == ' flag: 137' assert lout[1] == ' M: 2' def test_wcstab_copy(tab_wcs_2di_f): t = tab_wcs_2di_f.wcs.tab[0] c0 = t.coord c1 = np.ones_like(c0) t.coord = c1 assert np.allclose(tab_wcs_2di_f.wcs.tab[0].coord, c1) def test_tabprm_crval(tab_wcs_2di_f): w = deepcopy(tab_wcs_2di_f) t = tab_wcs_2di_f.wcs.tab[0] pix = np.array([[2, 3]], dtype=np.float32) rd1 = tab_wcs_2di_f.wcs_pix2world(pix, 1) c = t.crval.copy() d = 0.5 * np.ones_like(c) t.crval += d assert np.allclose(tab_wcs_2di_f.wcs.tab[0].crval, c + d) rd2 = tab_wcs_2di_f.wcs_pix2world(pix - d, 1) assert np.allclose(rd1, rd2) rd3 = w.wcs_pix2world(pix, 1) assert np.allclose(rd1, rd3)
af898037a9f7b78151d3b480a913cb61d183020a890fe2eb95d5d2d1d8d80d93
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst # Tests for the auxiliary parameters contained in wcsaux from numpy.testing import assert_allclose from astropy.io import fits from astropy.wcs import WCS STR_EXPECTED_EMPTY = """ rsun_ref: dsun_obs: crln_obs: hgln_obs: hglt_obs:""".lstrip() def test_empty(): w = WCS(naxis=1) assert w.wcs.aux.rsun_ref is None assert w.wcs.aux.dsun_obs is None assert w.wcs.aux.crln_obs is None assert w.wcs.aux.hgln_obs is None assert w.wcs.aux.hglt_obs is None assert str(w.wcs.aux) == STR_EXPECTED_EMPTY HEADER_SOLAR = fits.Header.fromstring(""" WCSAXES = 2 / Number of coordinate axes CRPIX1 = 64.5 / Pixel coordinate of reference point CRPIX2 = 64.5 / Pixel coordinate of reference point PC1_1 = 0.99999994260024 / Coordinate transformation matrix element PC1_2 = -0.00033882076120692 / Coordinate transformation matrix element PC2_1 = 0.00033882076120692 / Coordinate transformation matrix element PC2_2 = 0.99999994260024 / Coordinate transformation matrix element CDELT1 = 0.0053287911111111 / [deg] Coordinate increment at reference point CDELT2 = 0.0053287911111111 / [deg] Coordinate increment at reference point CUNIT1 = 'deg' / Units of coordinate increment and value CUNIT2 = 'deg' / Units of coordinate increment and value CTYPE1 = 'HPLN-TAN' / Coordinate type codegnomonic projection CTYPE2 = 'HPLT-TAN' / Coordinate type codegnomonic projection CRVAL1 = -0.0012589367249586 / [deg] Coordinate value at reference point CRVAL2 = 0.00079599300143911 / [deg] Coordinate value at reference point LONPOLE = 180.0 / [deg] Native longitude of celestial pole LATPOLE = 0.00079599300143911 / [deg] Native latitude of celestial pole DATE-OBS= '2011-02-15T00:00:00.34' / ISO-8601 time of observation MJD-OBS = 55607.000003935 / [d] MJD at start of observation RSUN_REF= 696000000.0 / [m] Solar radius DSUN_OBS= 147724815128.0 / [m] Distance from centre of Sun to observer CRLN_OBS= 22.814522 / [deg] Carrington heliographic lng of observer CRLT_OBS= -6.820544 / [deg] Heliographic latitude of observer HGLN_OBS= 8.431123 / [deg] Stonyhurst heliographic lng of observer HGLT_OBS= -6.820544 / [deg] Heliographic latitude of observer """.lstrip(), sep='\n') STR_EXPECTED_GET = """ rsun_ref: 696000000.000000 dsun_obs: 147724815128.000000 crln_obs: 22.814522 hgln_obs: 8.431123 hglt_obs: -6.820544""".lstrip() def test_solar_aux_get(): w = WCS(HEADER_SOLAR) assert_allclose(w.wcs.aux.rsun_ref, 696000000) assert_allclose(w.wcs.aux.dsun_obs, 147724815128) assert_allclose(w.wcs.aux.crln_obs, 22.814522) assert_allclose(w.wcs.aux.hgln_obs, 8.431123) assert_allclose(w.wcs.aux.hglt_obs, -6.820544) assert str(w.wcs.aux) == STR_EXPECTED_GET STR_EXPECTED_SET = """ rsun_ref: 698000000.000000 dsun_obs: 140000000000.000000 crln_obs: 10.000000 hgln_obs: 30.000000 hglt_obs: 40.000000""".lstrip() def test_solar_aux_set(): w = WCS(HEADER_SOLAR) w.wcs.aux.rsun_ref = 698000000 assert_allclose(w.wcs.aux.rsun_ref, 698000000) w.wcs.aux.dsun_obs = 140000000000 assert_allclose(w.wcs.aux.dsun_obs, 140000000000) w.wcs.aux.crln_obs = 10. assert_allclose(w.wcs.aux.crln_obs, 10.) w.wcs.aux.hgln_obs = 30. assert_allclose(w.wcs.aux.hgln_obs, 30.) w.wcs.aux.hglt_obs = 40. assert_allclose(w.wcs.aux.hglt_obs, 40.) assert str(w.wcs.aux) == STR_EXPECTED_SET header = w.to_header() assert_allclose(header['RSUN_REF'], 698000000) assert_allclose(header['DSUN_OBS'], 140000000000) assert_allclose(header['CRLN_OBS'], 10.) assert_allclose(header['HGLN_OBS'], 30.) assert_allclose(header['HGLT_OBS'], 40.) def test_set_aux_on_empty(): w = WCS(naxis=2) w.wcs.aux.rsun_ref = 698000000 assert_allclose(w.wcs.aux.rsun_ref, 698000000) w.wcs.aux.dsun_obs = 140000000000 assert_allclose(w.wcs.aux.dsun_obs, 140000000000) w.wcs.aux.crln_obs = 10. assert_allclose(w.wcs.aux.crln_obs, 10.) w.wcs.aux.hgln_obs = 30. assert_allclose(w.wcs.aux.hgln_obs, 30.) w.wcs.aux.hglt_obs = 40. assert_allclose(w.wcs.aux.hglt_obs, 40.) assert str(w.wcs.aux) == STR_EXPECTED_SET header = w.to_header() assert_allclose(header['RSUN_REF'], 698000000) assert_allclose(header['DSUN_OBS'], 140000000000) assert_allclose(header['CRLN_OBS'], 10.) assert_allclose(header['HGLN_OBS'], 30.) assert_allclose(header['HGLT_OBS'], 40.) def test_unset_aux(): w = WCS(HEADER_SOLAR) assert w.wcs.aux.rsun_ref is not None w.wcs.aux.rsun_ref = None assert w.wcs.aux.rsun_ref is None assert w.wcs.aux.dsun_obs is not None w.wcs.aux.dsun_obs = None assert w.wcs.aux.dsun_obs is None assert w.wcs.aux.crln_obs is not None w.wcs.aux.crln_obs = None assert w.wcs.aux.crln_obs is None assert w.wcs.aux.hgln_obs is not None w.wcs.aux.hgln_obs = None assert w.wcs.aux.hgln_obs is None assert w.wcs.aux.hglt_obs is not None w.wcs.aux.hglt_obs = None assert w.wcs.aux.hglt_obs is None assert str(w.wcs.aux) == 'rsun_ref:\ndsun_obs:\ncrln_obs:\nhgln_obs:\nhglt_obs:' header = w.to_header() assert 'RSUN_REF' not in header assert 'DSUN_OBS' not in header assert 'CRLN_OBS' not in header assert 'HGLN_OBS' not in header assert 'HGLT_OBS' not in header
d459895dbeeacb4a1cadc02d1aaa6cfe528c47d563fc554b410dae800a315146
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np import pytest from packaging.version import Version from astropy import wcs from astropy.wcs import _wcs # noqa from astropy.io import fits from astropy.utils.data import get_pkg_data_filename from . helper import SimModelTAB _WCSLIB_VER = Version(_wcs.__version__) def test_2d_spatial_tab_roundtrip(tab_wcs_2di): nx, ny = tab_wcs_2di.pixel_shape # generate "random" test coordinates: np.random.seed(1) xy = 0.51 + [nx + 0.99, ny + 0.99] * np.random.random((100, 2)) rd = tab_wcs_2di.wcs_pix2world(xy, 1) xy_roundtripped = tab_wcs_2di.wcs_world2pix(rd, 1) m = np.logical_and(*(np.isfinite(xy_roundtripped).T)) assert np.allclose(xy[m], xy_roundtripped[m], rtol=0, atol=1e-7) def test_2d_spatial_tab_vs_model(): nx = 150 ny = 200 model = SimModelTAB(nx=nx, ny=ny) # generate FITS HDU list: hdulist = model.hdulist # create WCS object: w = wcs.WCS(hdulist[0].header, hdulist) # generate "random" test coordinates: np.random.seed(1) xy = 0.51 + [nx + 0.99, ny + 0.99] * np.random.random((100, 2)) rd = w.wcs_pix2world(xy, 1) rd_model = model.fwd_eval(xy) assert np.allclose(rd, rd_model, rtol=0, atol=1e-7) @pytest.mark.skipif( _WCSLIB_VER < Version('7.6'), reason="Only in WCSLIB 7.6 a 1D -TAB axis roundtrips unless first axis" ) def test_mixed_celest_and_1d_tab_roundtrip(): # Tests WCS roundtripping for the case when there is one -TAB axis and # this axis is not the first axis. This tests a bug fixed in WCSLIB 7.6. filename = get_pkg_data_filename('data/tab-time-last-axis.fits') hdul = fits.open(filename) w = wcs.WCS(hdul[0].header, hdul) hdul.close() pts = np.random.random((10, 3)) * [[2047, 2047, 127]] assert np.allclose(pts, w.wcs_world2pix(w.wcs_pix2world(pts, 0), 0))
81a7e6576e7c56e0c7d589c2f470a07886936d2c31d03feb0c265702274e63fb
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst import gc import locale import re from packaging.version import Version import pytest import numpy as np from numpy.testing import assert_array_equal, assert_array_almost_equal from astropy.io import fits from astropy.wcs import wcs from astropy.wcs import _wcs from astropy.wcs.wcs import FITSFixedWarning from astropy.utils.data import ( get_pkg_data_contents, get_pkg_data_fileobj, get_pkg_data_filename) from astropy.utils.misc import _set_locale from astropy import units as u from astropy.units.core import UnitsWarning ###################################################################### def test_alt(): w = _wcs.Wcsprm() assert w.alt == " " w.alt = "X" assert w.alt == "X" del w.alt assert w.alt == " " def test_alt_invalid1(): w = _wcs.Wcsprm() with pytest.raises(ValueError): w.alt = "$" def test_alt_invalid2(): w = _wcs.Wcsprm() with pytest.raises(ValueError): w.alt = " " def test_axis_types(): w = _wcs.Wcsprm() assert_array_equal(w.axis_types, [0, 0]) def test_cd(): w = _wcs.Wcsprm() w.cd = [[1, 0], [0, 1]] assert w.cd.dtype == float assert w.has_cd() is True assert_array_equal(w.cd, [[1, 0], [0, 1]]) del w.cd assert w.has_cd() is False def test_cd_missing(): w = _wcs.Wcsprm() assert w.has_cd() is False with pytest.raises(AttributeError): w.cd def test_cd_missing2(): w = _wcs.Wcsprm() w.cd = [[1, 0], [0, 1]] assert w.has_cd() is True del w.cd assert w.has_cd() is False with pytest.raises(AttributeError): w.cd def test_cd_invalid(): w = _wcs.Wcsprm() with pytest.raises(ValueError): w.cd = [1, 0, 0, 1] def test_cdfix(): w = _wcs.Wcsprm() w.cdfix() def test_cdelt(): w = _wcs.Wcsprm() assert_array_equal(w.cdelt, [1, 1]) w.cdelt = [42, 54] assert_array_equal(w.cdelt, [42, 54]) def test_cdelt_delete(): w = _wcs.Wcsprm() with pytest.raises(TypeError): del w.cdelt def test_cel_offset(): w = _wcs.Wcsprm() assert w.cel_offset is False w.cel_offset = 'foo' assert w.cel_offset is True w.cel_offset = 0 assert w.cel_offset is False def test_celfix(): # TODO: We need some data with -NCP or -GLS projections to test # with. For now, this is just a smoke test w = _wcs.Wcsprm() assert w.celfix() == -1 def test_cname(): w = _wcs.Wcsprm() # Test that this works as an iterator for x in w.cname: assert x == '' assert list(w.cname) == ['', ''] w.cname = [b'foo', 'bar'] assert list(w.cname) == ['foo', 'bar'] def test_cname_invalid(): w = _wcs.Wcsprm() with pytest.raises(TypeError): w.cname = [42, 54] def test_colax(): w = _wcs.Wcsprm() assert w.colax.dtype == np.intc assert_array_equal(w.colax, [0, 0]) w.colax = [42, 54] assert_array_equal(w.colax, [42, 54]) w.colax[0] = 0 assert_array_equal(w.colax, [0, 54]) with pytest.raises(ValueError): w.colax = [1, 2, 3] def test_colnum(): w = _wcs.Wcsprm() assert w.colnum == 0 w.colnum = 42 assert w.colnum == 42 with pytest.raises(OverflowError): w.colnum = 0xffffffffffffffffffff with pytest.raises(OverflowError): w.colnum = 0xffffffff with pytest.raises(TypeError): del w.colnum def test_colnum_invalid(): w = _wcs.Wcsprm() with pytest.raises(TypeError): w.colnum = 'foo' def test_crder(): w = _wcs.Wcsprm() assert w.crder.dtype == float assert np.all(np.isnan(w.crder)) w.crder[0] = 0 assert np.isnan(w.crder[1]) assert w.crder[0] == 0 w.crder = w.crder def test_crota(): w = _wcs.Wcsprm() w.crota = [1, 0] assert w.crota.dtype == float assert w.has_crota() is True assert_array_equal(w.crota, [1, 0]) del w.crota assert w.has_crota() is False def test_crota_missing(): w = _wcs.Wcsprm() assert w.has_crota() is False with pytest.raises(AttributeError): w.crota def test_crota_missing2(): w = _wcs.Wcsprm() w.crota = [1, 0] assert w.has_crota() is True del w.crota assert w.has_crota() is False with pytest.raises(AttributeError): w.crota def test_crpix(): w = _wcs.Wcsprm() assert w.crpix.dtype == float assert_array_equal(w.crpix, [0, 0]) w.crpix = [42, 54] assert_array_equal(w.crpix, [42, 54]) w.crpix[0] = 0 assert_array_equal(w.crpix, [0, 54]) with pytest.raises(ValueError): w.crpix = [1, 2, 3] def test_crval(): w = _wcs.Wcsprm() assert w.crval.dtype == float assert_array_equal(w.crval, [0, 0]) w.crval = [42, 54] assert_array_equal(w.crval, [42, 54]) w.crval[0] = 0 assert_array_equal(w.crval, [0, 54]) def test_csyer(): w = _wcs.Wcsprm() assert w.csyer.dtype == float assert np.all(np.isnan(w.csyer)) w.csyer[0] = 0 assert np.isnan(w.csyer[1]) assert w.csyer[0] == 0 w.csyer = w.csyer def test_ctype(): w = _wcs.Wcsprm() assert list(w.ctype) == ['', ''] w.ctype = [b'RA---TAN', 'DEC--TAN'] assert_array_equal(w.axis_types, [2200, 2201]) assert w.lat == 1 assert w.lng == 0 assert w.lattyp == 'DEC' assert w.lngtyp == 'RA' assert list(w.ctype) == ['RA---TAN', 'DEC--TAN'] w.ctype = ['foo', 'bar'] assert_array_equal(w.axis_types, [0, 0]) assert list(w.ctype) == ['foo', 'bar'] assert w.lat == -1 assert w.lng == -1 assert w.lattyp == 'DEC' assert w.lngtyp == 'RA' def test_ctype_repr(): w = _wcs.Wcsprm() assert list(w.ctype) == ['', ''] w.ctype = [b'RA-\t--TAN', 'DEC-\n-TAN'] assert repr(w.ctype == '["RA-\t--TAN", "DEC-\n-TAN"]') def test_ctype_index_error(): w = _wcs.Wcsprm() assert list(w.ctype) == ['', ''] for idx in (2, -3): with pytest.raises(IndexError): w.ctype[idx] with pytest.raises(IndexError): w.ctype[idx] = 'FOO' def test_ctype_invalid_error(): w = _wcs.Wcsprm() assert list(w.ctype) == ['', ''] with pytest.raises(ValueError): w.ctype[0] = 'X' * 100 with pytest.raises(TypeError): w.ctype[0] = True with pytest.raises(TypeError): w.ctype = ['a', 0] with pytest.raises(TypeError): w.ctype = None with pytest.raises(ValueError): w.ctype = ['a', 'b', 'c'] with pytest.raises(ValueError): w.ctype = ['FOO', 'A' * 100] def test_cubeface(): w = _wcs.Wcsprm() assert w.cubeface == -1 w.cubeface = 0 with pytest.raises(OverflowError): w.cubeface = -1 def test_cunit(): w = _wcs.Wcsprm() assert list(w.cunit) == [u.Unit(''), u.Unit('')] w.cunit = [u.m, 'km'] assert w.cunit[0] == u.m assert w.cunit[1] == u.km def test_cunit_invalid(): w = _wcs.Wcsprm() with pytest.warns(u.UnitsWarning, match='foo') as warns: w.cunit[0] = 'foo' assert len(warns) == 1 def test_cunit_invalid2(): w = _wcs.Wcsprm() with pytest.warns(u.UnitsWarning) as warns: w.cunit = ['foo', 'bar'] assert len(warns) == 2 assert 'foo' in str(warns[0].message) assert 'bar' in str(warns[1].message) def test_unit(): w = wcs.WCS() w.wcs.cunit[0] = u.erg assert w.wcs.cunit[0] == u.erg assert repr(w.wcs.cunit) == "['erg', '']" def test_unit2(): w = wcs.WCS() with pytest.warns(UnitsWarning): myunit = u.Unit("FOOBAR", parse_strict="warn") w.wcs.cunit[0] = myunit def test_unit3(): w = wcs.WCS() for idx in (2, -3): with pytest.raises(IndexError): w.wcs.cunit[idx] with pytest.raises(IndexError): w.wcs.cunit[idx] = u.m with pytest.raises(ValueError): w.wcs.cunit = [u.m, u.m, u.m] def test_unitfix(): w = _wcs.Wcsprm() w.unitfix() def test_cylfix(): # TODO: We need some data with broken cylindrical projections to # test with. For now, this is just a smoke test. w = _wcs.Wcsprm() assert w.cylfix() == -1 assert w.cylfix([0, 1]) == -1 with pytest.raises(ValueError): w.cylfix([0, 1, 2]) def test_dateavg(): w = _wcs.Wcsprm() assert w.dateavg == '' # TODO: When dateavg is verified, check that it works def test_dateobs(): w = _wcs.Wcsprm() assert w.dateobs == '' # TODO: When dateavg is verified, check that it works def test_datfix(): w = _wcs.Wcsprm() w.dateobs = '31/12/99' assert w.datfix() == 0 assert w.dateobs == '1999-12-31' assert w.mjdobs == 51543.0 def test_equinox(): w = _wcs.Wcsprm() assert np.isnan(w.equinox) w.equinox = 0 assert w.equinox == 0 del w.equinox assert np.isnan(w.equinox) with pytest.raises(TypeError): w.equinox = None def test_fix(): w = _wcs.Wcsprm() fix_ref = { 'cdfix': 'No change', 'cylfix': 'No change', 'obsfix': 'No change', 'datfix': 'No change', 'spcfix': 'No change', 'unitfix': 'No change', 'celfix': 'No change', 'obsfix': 'No change'} version = wcs._wcs.__version__ if Version(version) <= Version('5'): del fix_ref['obsfix'] if Version(version) >= Version('7.1'): w.dateref = '1858-11-17' if Version('7.4') <= Version(version) < Version('7.6'): fix_ref['datfix'] = 'Success' assert w.fix() == fix_ref def test_fix2(): w = _wcs.Wcsprm() w.dateobs = '31/12/99' fix_ref = { 'cdfix': 'No change', 'cylfix': 'No change', 'obsfix': 'No change', 'datfix': "Set MJD-OBS to 51543.000000 from DATE-OBS.\nChanged DATE-OBS from '31/12/99' to '1999-12-31'", # noqa 'spcfix': 'No change', 'unitfix': 'No change', 'celfix': 'No change'} version = wcs._wcs.__version__ if Version(version) <= Version("5"): del fix_ref['obsfix'] fix_ref['datfix'] = "Changed '31/12/99' to '1999-12-31'" if Version(version) >= Version('7.3'): fix_ref['datfix'] = "Set DATEREF to '1858-11-17' from MJDREF.\n" + fix_ref['datfix'] elif Version(version) >= Version('7.1'): fix_ref['datfix'] = "Set DATE-REF to '1858-11-17' from MJD-REF.\n" + fix_ref['datfix'] assert w.fix() == fix_ref assert w.dateobs == '1999-12-31' assert w.mjdobs == 51543.0 def test_fix3(): w = _wcs.Wcsprm() w.dateobs = '31/12/F9' fix_ref = { 'cdfix': 'No change', 'cylfix': 'No change', 'obsfix': 'No change', 'datfix': "Invalid DATE-OBS format '31/12/F9'", 'spcfix': 'No change', 'unitfix': 'No change', 'celfix': 'No change' } version = wcs._wcs.__version__ if Version(version) <= Version("5"): del fix_ref['obsfix'] fix_ref['datfix'] = "Invalid parameter value: invalid date '31/12/F9'" if Version(version) >= Version('7.3'): fix_ref['datfix'] = "Set DATEREF to '1858-11-17' from MJDREF.\n" + fix_ref['datfix'] elif Version(version) >= Version('7.1'): fix_ref['datfix'] = "Set DATE-REF to '1858-11-17' from MJD-REF.\n" + fix_ref['datfix'] assert w.fix() == fix_ref assert w.dateobs == '31/12/F9' assert np.isnan(w.mjdobs) def test_fix4(): w = _wcs.Wcsprm() with pytest.raises(ValueError): w.fix('X') def test_fix5(): w = _wcs.Wcsprm() with pytest.raises(ValueError): w.fix(naxis=[0, 1, 2]) def test_get_ps(): # TODO: We need some data with PSi_ma keywords w = _wcs.Wcsprm() assert len(w.get_ps()) == 0 def test_get_pv(): # TODO: We need some data with PVi_ma keywords w = _wcs.Wcsprm() assert len(w.get_pv()) == 0 def test_imgpix_matrix(): w = _wcs.Wcsprm() with pytest.raises(AssertionError): w.imgpix_matrix def test_imgpix_matrix2(): w = _wcs.Wcsprm() with pytest.raises(AttributeError): w.imgpix_matrix = None def test_isunity(): w = _wcs.Wcsprm() assert(w.is_unity()) def test_lat(): w = _wcs.Wcsprm() assert w.lat == -1 def test_lat_set(): w = _wcs.Wcsprm() with pytest.raises(AttributeError): w.lat = 0 def test_latpole(): w = _wcs.Wcsprm() assert w.latpole == 90.0 w.latpole = 45.0 assert w.latpole == 45.0 del w.latpole assert w.latpole == 90.0 def test_lattyp(): w = _wcs.Wcsprm() assert w.lattyp == " " def test_lattyp_set(): w = _wcs.Wcsprm() with pytest.raises(AttributeError): w.lattyp = 0 def test_lng(): w = _wcs.Wcsprm() assert w.lng == -1 def test_lng_set(): w = _wcs.Wcsprm() with pytest.raises(AttributeError): w.lng = 0 def test_lngtyp(): w = _wcs.Wcsprm() assert w.lngtyp == " " def test_lngtyp_set(): w = _wcs.Wcsprm() with pytest.raises(AttributeError): w.lngtyp = 0 def test_lonpole(): w = _wcs.Wcsprm() assert np.isnan(w.lonpole) w.lonpole = 45.0 assert w.lonpole == 45.0 del w.lonpole assert np.isnan(w.lonpole) def test_mix(): w = _wcs.Wcsprm() w.ctype = [b'RA---TAN', 'DEC--TAN'] with pytest.raises(_wcs.InvalidCoordinateError): w.mix(1, 1, [240, 480], 1, 5, [0, 2], [54, 32], 1) def test_mjdavg(): w = _wcs.Wcsprm() assert np.isnan(w.mjdavg) w.mjdavg = 45.0 assert w.mjdavg == 45.0 del w.mjdavg assert np.isnan(w.mjdavg) def test_mjdobs(): w = _wcs.Wcsprm() assert np.isnan(w.mjdobs) w.mjdobs = 45.0 assert w.mjdobs == 45.0 del w.mjdobs assert np.isnan(w.mjdobs) def test_name(): w = _wcs.Wcsprm() assert w.name == '' w.name = 'foo' assert w.name == 'foo' def test_naxis(): w = _wcs.Wcsprm() assert w.naxis == 2 def test_naxis_set(): w = _wcs.Wcsprm() with pytest.raises(AttributeError): w.naxis = 4 def test_obsgeo(): w = _wcs.Wcsprm() assert np.all(np.isnan(w.obsgeo)) w.obsgeo = [1, 2, 3, 4, 5, 6] assert_array_equal(w.obsgeo, [1, 2, 3, 4, 5, 6]) del w.obsgeo assert np.all(np.isnan(w.obsgeo)) def test_pc(): w = _wcs.Wcsprm() assert w.has_pc() assert_array_equal(w.pc, [[1, 0], [0, 1]]) w.cd = [[1, 0], [0, 1]] assert not w.has_pc() del w.cd assert w.has_pc() assert_array_equal(w.pc, [[1, 0], [0, 1]]) w.pc = w.pc def test_pc_missing(): w = _wcs.Wcsprm() w.cd = [[1, 0], [0, 1]] assert not w.has_pc() with pytest.raises(AttributeError): w.pc def test_phi0(): w = _wcs.Wcsprm() assert np.isnan(w.phi0) w.phi0 = 42.0 assert w.phi0 == 42.0 del w.phi0 assert np.isnan(w.phi0) def test_piximg_matrix(): w = _wcs.Wcsprm() with pytest.raises(AssertionError): w.piximg_matrix def test_piximg_matrix2(): w = _wcs.Wcsprm() with pytest.raises(AttributeError): w.piximg_matrix = None def test_print_contents(): # In general, this is human-consumable, so we don't care if the # content changes, just check the type w = _wcs.Wcsprm() assert isinstance(str(w), str) def test_radesys(): w = _wcs.Wcsprm() assert w.radesys == '' w.radesys = 'foo' assert w.radesys == 'foo' def test_restfrq(): w = _wcs.Wcsprm() assert w.restfrq == 0.0 w.restfrq = np.nan assert np.isnan(w.restfrq) del w.restfrq def test_restwav(): w = _wcs.Wcsprm() assert w.restwav == 0.0 w.restwav = np.nan assert np.isnan(w.restwav) del w.restwav def test_set_ps(): w = _wcs.Wcsprm() data = [(0, 0, "param1"), (1, 1, "param2")] w.set_ps(data) assert w.get_ps() == data def test_set_ps_realloc(): w = _wcs.Wcsprm() w.set_ps([(0, 0, "param1")] * 16) def test_set_pv(): w = _wcs.Wcsprm() data = [(0, 0, 42.), (1, 1, 54.)] w.set_pv(data) assert w.get_pv() == data def test_set_pv_realloc(): w = _wcs.Wcsprm() w.set_pv([(0, 0, 42.)] * 16) def test_spcfix(): # TODO: We need some data with broken spectral headers here to # really test header = get_pkg_data_contents( 'data/spectra/orion-velo-1.hdr', encoding='binary') w = _wcs.Wcsprm(header) assert w.spcfix() == -1 def test_spec(): w = _wcs.Wcsprm() assert w.spec == -1 def test_spec_set(): w = _wcs.Wcsprm() with pytest.raises(AttributeError): w.spec = 0 def test_specsys(): w = _wcs.Wcsprm() assert w.specsys == '' w.specsys = 'foo' assert w.specsys == 'foo' def test_sptr(): # TODO: Write me pass def test_ssysobs(): w = _wcs.Wcsprm() assert w.ssysobs == '' w.ssysobs = 'foo' assert w.ssysobs == 'foo' def test_ssyssrc(): w = _wcs.Wcsprm() assert w.ssyssrc == '' w.ssyssrc = 'foo' assert w.ssyssrc == 'foo' def test_tab(): w = _wcs.Wcsprm() assert len(w.tab) == 0 # TODO: Inject some headers that have tables and test def test_theta0(): w = _wcs.Wcsprm() assert np.isnan(w.theta0) w.theta0 = 42.0 assert w.theta0 == 42.0 del w.theta0 assert np.isnan(w.theta0) def test_toheader(): w = _wcs.Wcsprm() assert isinstance(w.to_header(), str) def test_velangl(): w = _wcs.Wcsprm() assert np.isnan(w.velangl) w.velangl = 42.0 assert w.velangl == 42.0 del w.velangl assert np.isnan(w.velangl) def test_velosys(): w = _wcs.Wcsprm() assert np.isnan(w.velosys) w.velosys = 42.0 assert w.velosys == 42.0 del w.velosys assert np.isnan(w.velosys) def test_velref(): w = _wcs.Wcsprm() assert w.velref == 0.0 w.velref = 42 assert w.velref == 42.0 del w.velref assert w.velref == 0.0 def test_zsource(): w = _wcs.Wcsprm() assert np.isnan(w.zsource) w.zsource = 42.0 assert w.zsource == 42.0 del w.zsource assert np.isnan(w.zsource) def test_cd_3d(): header = get_pkg_data_contents('data/3d_cd.hdr', encoding='binary') w = _wcs.Wcsprm(header) assert w.cd.shape == (3, 3) assert w.get_pc().shape == (3, 3) assert w.get_cdelt().shape == (3,) def test_get_pc(): header = get_pkg_data_contents('data/3d_cd.hdr', encoding='binary') w = _wcs.Wcsprm(header) pc = w.get_pc() try: pc[0, 0] = 42 except (RuntimeError, ValueError): pass else: raise AssertionError() def test_detailed_err(): w = _wcs.Wcsprm() w.pc = [[0, 0], [0, 0]] with pytest.raises(_wcs.SingularMatrixError): w.set() def test_header_parse(): from astropy.io import fits with get_pkg_data_fileobj( 'data/header_newlines.fits', encoding='binary') as test_file: hdulist = fits.open(test_file) with pytest.warns(FITSFixedWarning): w = wcs.WCS(hdulist[0].header) assert w.wcs.ctype[0] == 'RA---TAN-SIP' def test_locale(): try: with _set_locale('fr_FR'): header = get_pkg_data_contents('data/locale.hdr', encoding='binary') with pytest.warns(FITSFixedWarning): w = _wcs.Wcsprm(header) assert re.search("[0-9]+,[0-9]*", w.to_header()) is None except locale.Error: pytest.xfail( "Can't set to 'fr_FR' locale, perhaps because it is not installed " "on this system") def test_unicode(): w = _wcs.Wcsprm() with pytest.raises(UnicodeEncodeError): w.alt = "‰" def test_sub_segfault(): # Issue #1960 header = fits.Header.fromtextfile( get_pkg_data_filename('data/sub-segfault.hdr')) w = wcs.WCS(header) w.sub([wcs.WCSSUB_CELESTIAL]) gc.collect() def test_bounds_check(): w = _wcs.Wcsprm() w.bounds_check(False) def test_wcs_sub_error_message(): # Issue #1587 w = _wcs.Wcsprm() with pytest.raises(TypeError) as e: w.sub('latitude') assert e.match("axes must None, a sequence or an integer$") def test_wcs_sub(): # Issue #3356 w = _wcs.Wcsprm() w.sub(['latitude']) w = _wcs.Wcsprm() w.sub([b'latitude']) def test_compare(): header = get_pkg_data_contents('data/3d_cd.hdr', encoding='binary') w = _wcs.Wcsprm(header) w2 = _wcs.Wcsprm(header) assert w == w2 w.equinox = 42 assert w == w2 assert not w.compare(w2) assert w.compare(w2, _wcs.WCSCOMPARE_ANCILLARY) w = _wcs.Wcsprm(header) w2 = _wcs.Wcsprm(header) with pytest.warns(RuntimeWarning): w.cdelt[0] = np.float32(0.00416666666666666666666666) w2.cdelt[0] = np.float64(0.00416666666666666666666666) assert not w.compare(w2) assert w.compare(w2, tolerance=1e-6) def test_radesys_defaults(): w = _wcs.Wcsprm() w.ctype = ['RA---TAN', 'DEC--TAN'] w.set() assert w.radesys == "ICRS" def test_radesys_defaults_full(): # As described in Section 3.1 of the FITS standard "Equatorial and ecliptic # coordinates", for those systems the RADESYS keyword can be used to # indicate the equatorial/ecliptic frame to use. From the standard: # "For RADESYSa values of FK4 and FK4-NO-E, any stated equinox is Besselian # and, if neither EQUINOXa nor EPOCH are given, a default of 1950.0 is to # be taken. For FK5, any stated equinox is Julian and, if neither keyword # is given, it defaults to 2000.0. # "If the EQUINOXa keyword is given it should always be accompanied by # RADESYS a. However, if it should happen to ap- pear by itself then # RADESYSa defaults to FK4 if EQUINOXa < 1984.0, or to FK5 if EQUINOXa # 1984.0. Note that these defaults, while probably true of older files # using the EPOCH keyword, are not required of them. # By default RADESYS is empty w = _wcs.Wcsprm(naxis=2) assert w.radesys == '' assert np.isnan(w.equinox) # For non-ecliptic or equatorial systems it is still empty w = _wcs.Wcsprm(naxis=2) for ctype in [('GLON-CAR', 'GLAT-CAR'), ('SLON-SIN', 'SLAT-SIN')]: w.ctype = ctype w.set() assert w.radesys == '' assert np.isnan(w.equinox) for ctype in [('RA---TAN', 'DEC--TAN'), ('ELON-TAN', 'ELAT-TAN'), ('DEC--TAN', 'RA---TAN'), ('ELAT-TAN', 'ELON-TAN')]: # Check defaults for RADESYS w = _wcs.Wcsprm(naxis=2) w.ctype = ctype w.set() assert w.radesys == 'ICRS' w = _wcs.Wcsprm(naxis=2) w.ctype = ctype w.equinox = 1980 w.set() assert w.radesys == 'FK4' w = _wcs.Wcsprm(naxis=2) w.ctype = ctype w.equinox = 1984 w.set() assert w.radesys == 'FK5' w = _wcs.Wcsprm(naxis=2) w.ctype = ctype w.radesys = 'foo' w.set() assert w.radesys == 'foo' # Check defaults for EQUINOX w = _wcs.Wcsprm(naxis=2) w.ctype = ctype w.set() assert np.isnan(w.equinox) # frame is ICRS, no equinox w = _wcs.Wcsprm(naxis=2) w.ctype = ctype w.radesys = 'ICRS' w.set() assert np.isnan(w.equinox) w = _wcs.Wcsprm(naxis=2) w.ctype = ctype w.radesys = 'FK5' w.set() assert w.equinox == 2000. w = _wcs.Wcsprm(naxis=2) w.ctype = ctype w.radesys = 'FK4' w.set() assert w.equinox == 1950 w = _wcs.Wcsprm(naxis=2) w.ctype = ctype w.radesys = 'FK4-NO-E' w.set() assert w.equinox == 1950 def test_iteration(): world = np.array( [[-0.58995335, -0.5], [0.00664326, -0.5], [-0.58995335, -0.25], [0.00664326, -0.25], [-0.58995335, 0.], [0.00664326, 0.], [-0.58995335, 0.25], [0.00664326, 0.25], [-0.58995335, 0.5], [0.00664326, 0.5]], float ) w = wcs.WCS() w.wcs.ctype = ['GLON-CAR', 'GLAT-CAR'] w.wcs.cdelt = [-0.006666666828, 0.006666666828] w.wcs.crpix = [75.907, 74.8485] x = w.wcs_world2pix(world, 1) expected = np.array( [[1.64400000e+02, -1.51498185e-01], [7.49105110e+01, -1.51498185e-01], [1.64400000e+02, 3.73485009e+01], [7.49105110e+01, 3.73485009e+01], [1.64400000e+02, 7.48485000e+01], [7.49105110e+01, 7.48485000e+01], [1.64400000e+02, 1.12348499e+02], [7.49105110e+01, 1.12348499e+02], [1.64400000e+02, 1.49848498e+02], [7.49105110e+01, 1.49848498e+02]], float) assert_array_almost_equal(x, expected) w2 = w.wcs_pix2world(x, 1) world[:, 0] %= 360. assert_array_almost_equal(w2, world) def test_invalid_args(): with pytest.raises(TypeError): _wcs.Wcsprm(keysel='A') with pytest.raises(ValueError): _wcs.Wcsprm(keysel=2) with pytest.raises(ValueError): _wcs.Wcsprm(colsel=2) with pytest.raises(ValueError): _wcs.Wcsprm(naxis=64) header = get_pkg_data_contents( 'data/spectra/orion-velo-1.hdr', encoding='binary') with pytest.raises(ValueError): _wcs.Wcsprm(header, relax='FOO') with pytest.raises(ValueError): _wcs.Wcsprm(header, naxis=3) with pytest.raises(KeyError): _wcs.Wcsprm(header, key='A') # Test keywords in the Time standard def test_datebeg(): w = _wcs.Wcsprm() assert w.datebeg == '' w.datebeg = '2001-02-11' assert w.datebeg == '2001-02-11' w.datebeg = '31/12/99' fix_ref = { 'cdfix': 'No change', 'cylfix': 'No change', 'obsfix': 'No change', 'datfix': "Invalid DATE-BEG format '31/12/99'", 'spcfix': 'No change', 'unitfix': 'No change', 'celfix': 'No change'} if Version(wcs._wcs.__version__) >= Version('7.3'): fix_ref['datfix'] = "Set DATEREF to '1858-11-17' from MJDREF.\n" + fix_ref['datfix'] elif Version(wcs._wcs.__version__) >= Version('7.1'): fix_ref['datfix'] = "Set DATE-REF to '1858-11-17' from MJD-REF.\n" + fix_ref['datfix'] assert w.fix() == fix_ref char_keys = ['timesys', 'trefpos', 'trefdir', 'plephem', 'timeunit', 'dateref', 'dateavg', 'dateend'] @pytest.mark.parametrize('key', char_keys) def test_char_keys(key): w = _wcs.Wcsprm() assert getattr(w, key) == '' setattr(w, key, "foo") assert getattr(w, key) == 'foo' with pytest.raises(TypeError): setattr(w, key, 42) num_keys = ['mjdobs', 'mjdbeg', 'mjdend', 'jepoch', 'bepoch', 'tstart', 'tstop', 'xposure', 'timsyer', 'timrder', 'timedel', 'timepixr', 'timeoffs', 'telapse', 'xposure'] @pytest.mark.parametrize('key', num_keys) def test_num_keys(key): w = _wcs.Wcsprm() assert np.isnan(getattr(w, key)) setattr(w, key, 42.0) assert getattr(w, key) == 42.0 delattr(w, key) assert np.isnan(getattr(w, key)) with pytest.raises(TypeError): setattr(w, key, "foo") @pytest.mark.parametrize('key', ['czphs', 'cperi', 'mjdref']) def test_array_keys(key): w = _wcs.Wcsprm() attr = getattr(w, key) if key == 'mjdref' and Version(_wcs.__version__) >= Version('7.1'): assert np.allclose(attr, [0, 0]) else: assert np.all(np.isnan(attr)) assert attr.dtype == float setattr(w, key, [1., 2.]) assert_array_equal(getattr(w, key), [1., 2.]) with pytest.raises(ValueError): setattr(w, key, ["foo", "bar"]) with pytest.raises(ValueError): setattr(w, key, "foo")
b03f4c05280974562886bf3489697fe5680a68614cb7f7eb2040eff6c67586be
# Licensed under a 3-clause BSD style license - see LICENSE.rst from copy import copy, deepcopy import pytest import numpy as np from astropy import wcs from . helper import SimModelTAB _WCS_UNDEFINED = 987654321.0e99 def test_celprm_init(): # test PyCelprm_cnew assert wcs.WCS().wcs.cel # test PyCelprm_new assert wcs.Celprm() with pytest.raises(wcs.InvalidPrjParametersError): cel = wcs.Celprm() cel.set() # test deletion does not crash cel = wcs.Celprm() del cel def test_celprm_copy(): # shallow copy cel = wcs.Celprm() cel2 = copy(cel) cel3 = copy(cel2) cel.ref = [6, 8, 18, 3] assert (np.allclose(cel.ref, cel2.ref, atol=1e-12, rtol=0) and np.allclose(cel.ref, cel3.ref, atol=1e-12, rtol=0)) del cel, cel2, cel3 # deep copy cel = wcs.Celprm() cel2 = deepcopy(cel) cel.ref = [6, 8, 18, 3] assert not np.allclose(cel.ref, cel2.ref, atol=1e-12, rtol=0) del cel, cel2 def test_celprm_offset(): cel = wcs.Celprm() assert not cel.offset cel.offset = True assert cel.offset def test_celprm_prj(): cel = wcs.Celprm() assert cel.prj is not None cel.prj.code = 'TAN' cel.set() assert cel._flag def test_celprm_phi0(): cel = wcs.Celprm() cel.prj.code = 'TAN' assert cel.phi0 == None assert cel._flag == 0 cel.set() assert cel.phi0 == 0.0 cel.phi0 = 0.0 assert cel._flag cel.phi0 = 2.0 assert cel._flag == 0 cel.phi0 = None assert cel.phi0 == None assert cel._flag == 0 def test_celprm_theta0(): cel = wcs.Celprm() cel.prj.code = 'TAN' assert cel.theta0 == None assert cel._flag == 0 cel.theta0 = 4.0 cel.set() assert cel.theta0 == 4.0 cel.theta0 = 4.0 assert cel._flag cel.theta0 = 8.0 assert cel._flag == 0 cel.theta0 = None assert cel.theta0 == None assert cel._flag == 0 def test_celprm_ref(): cel = wcs.Celprm() cel.prj.code = 'TAN' cel.set() assert np.allclose(cel.ref, [0.0, 0.0, 180.0, 0.0], atol=1e-12, rtol=0) cel.phi0 = 2.0 cel.theta0 = 4.0 cel.ref = [123, 12] cel.set() assert np.allclose(cel.ref, [123.0, 12.0, 2, 82], atol=1e-12, rtol=0) cel.ref = [None, 13, None, None] assert np.allclose(cel.ref, [123.0, 13.0, 2, 82], atol=1e-12, rtol=0) def test_celprm_isolat(): cel = wcs.Celprm() cel.prj.code = 'TAN' cel.set() assert cel.isolat == 0 def test_celprm_latpreq(): cel = wcs.Celprm() cel.prj.code = 'TAN' cel.set() assert cel.latpreq == 0 def test_celprm_euler(): cel = wcs.Celprm() cel.prj.code = 'TAN' cel.set() assert np.allclose(cel.euler, [0.0, 90.0, 180.0, 0.0, 1.0], atol=1e-12, rtol=0)
06cc3e5712e73a86ffce2be30ed6573562597989b4286c66a3eb937dbf3dd37a
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest import numpy as np from astropy import wcs from astropy.io import fits class SimModelTAB: def __init__(self, nx=150, ny=200, crpix=[1, 1], crval = [1, 1], cdelt = [1, 1], pc = {'PC1_1': 1, 'PC2_2': 1}): """ set essential parameters of the model (coord transformations) """ assert nx > 2 and ny > 1 # a limitation of this particular simulation self.nx = nx self.ny = ny self.crpix = crpix self.crval = crval self.cdelt = cdelt self.pc = pc def fwd_eval(self, xy): xb = 1 + self.nx // 3 px = np.array([1, xb, xb, self.nx + 1]) py = np.array([1, self.ny + 1]) xi = self.crval[0] + self.cdelt[0] * (px - self.crpix[0]) yi = self.crval[1] + self.cdelt[1] * (py - self.crpix[1]) cx = np.array([0.0, 0.26, 0.8, 1.0]) cy = np.array([-0.5, 0.5]) xy = np.atleast_2d(xy) x = xy[:, 0] y = xy[:, 1] mbad = (x < px[0]) | (y < py[0]) | (x > px[-1]) | (y > py[-1]) mgood = np.logical_not(mbad) i = 2 * (x > xb).astype(int) psix = self.crval[0] + self.cdelt[0] * (x - self.crpix[0]) psiy = self.crval[1] + self.cdelt[1] * (y - self.crpix[1]) cfx = (psix - xi[i]) / (xi[i + 1] - xi[i]) cfy = (psiy - yi[0]) / (yi[1] - yi[0]) ra = cx[i] + cfx * (cx[i + 1] - cx[i]) dec = cy[0] + cfy * (cy[1] - cy[0]) return np.dstack([ra, dec])[0] @property def hdulist(self): """ Simulates 2D data with a _spatial_ WCS that uses the ``-TAB`` algorithm with indexing. """ # coordinate array (some "arbitrary" numbers with a "jump" along x axis): x = np.array([[0.0, 0.26, 0.8, 1.0], [0.0, 0.26, 0.8, 1.0]]) y = np.array([[-0.5, -0.5, -0.5, -0.5], [0.5, 0.5, 0.5, 0.5]]) c = np.dstack([x, y]) # index arrays (skip PC matrix for simplicity - assume it is an # identity matrix): xb = 1 + self.nx // 3 px = np.array([1, xb, xb, self.nx + 1]) py = np.array([1, self.ny + 1]) xi = self.crval[0] + self.cdelt[0] * (px - self.crpix[0]) yi = self.crval[1] + self.cdelt[1] * (py - self.crpix[1]) # structured array (data) for binary table HDU: arr = np.array( [(c, xi, yi)], dtype=[ ('wavelength', np.float64, c.shape), ('xi', np.double, (xi.size,)), ('yi', np.double, (yi.size,)) ] ) # create binary table HDU: bt = fits.BinTableHDU(arr); bt.header['EXTNAME'] = 'WCS-TABLE' # create primary header: image_data = np.ones((self.ny, self.nx), dtype=np.float32) pu = fits.PrimaryHDU(image_data) pu.header['ctype1'] = 'RA---TAB' pu.header['ctype2'] = 'DEC--TAB' pu.header['naxis1'] = self.nx pu.header['naxis2'] = self.ny pu.header['PS1_0'] = 'WCS-TABLE' pu.header['PS2_0'] = 'WCS-TABLE' pu.header['PS1_1'] = 'wavelength' pu.header['PS2_1'] = 'wavelength' pu.header['PV1_3'] = 1 pu.header['PV2_3'] = 2 pu.header['CUNIT1'] = 'deg' pu.header['CUNIT2'] = 'deg' pu.header['CDELT1'] = self.cdelt[0] pu.header['CDELT2'] = self.cdelt[1] pu.header['CRPIX1'] = self.crpix[0] pu.header['CRPIX2'] = self.crpix[1] pu.header['CRVAL1'] = self.crval[0] pu.header['CRVAL2'] = self.crval[1] pu.header['PS1_2'] = 'xi' pu.header['PS2_2'] = 'yi' for k, v in self.pc.items(): pu.header[k] = v hdulist = fits.HDUList([pu, bt]) return hdulist
fdc5c7bfde76594f089d69b21dc3898141859e725abb21563b52b94194169c3f
from .sliced_wcs import * # noqa from .base import BaseWCSWrapper
2598d3745e205be979749ccf83b8a8ff635485c668623acff28a3f44751db938
import abc from astropy.wcs.wcsapi import BaseLowLevelWCS, wcs_info_str class BaseWCSWrapper(BaseLowLevelWCS, metaclass=abc.ABCMeta): """ A base wrapper class for things that modify Low Level WCSes. This wrapper implements a transparent wrapper to many of the properties, with the idea that not all of them would need to be overridden in your wrapper, but some probably will. Parameters ---------- wcs : `astropy.wcs.wcsapi.BaseLowLevelWCS` The WCS object to wrap """ def __init__(self, wcs, *args, **kwargs): self._wcs = wcs @property def pixel_n_dim(self): return self._wcs.pixel_n_dim @property def world_n_dim(self): return self._wcs.world_n_dim @property def world_axis_physical_types(self): return self._wcs.world_axis_physical_types @property def world_axis_units(self): return self._wcs.world_axis_units @property def world_axis_object_components(self): return self._wcs.world_axis_object_components @property def world_axis_object_classes(self): return self._wcs.world_axis_object_classes @property def pixel_shape(self): return self._wcs.pixel_shape @property def pixel_bounds(self): return self._wcs.pixel_bounds @property def pixel_axis_names(self): return self._wcs.pixel_axis_names @property def world_axis_names(self): return self._wcs.world_axis_names @property def axis_correlation_matrix(self): return self._wcs.axis_correlation_matrix @property def serialized_classes(self): return self._wcs.serialized_classes @abc.abstractmethod def pixel_to_world_values(self, *pixel_arrays): pass @abc.abstractmethod def world_to_pixel_values(self, *world_arrays): pass def __repr__(self): return f"{object.__repr__(self)}\n{str(self)}" def __str__(self): return wcs_info_str(self)
9fbac7091b35375a2f461a514438ce326e380b8d79339a08b6ed23392d1104f0
import numbers from collections import defaultdict import numpy as np from astropy.utils import isiterable from astropy.utils.decorators import lazyproperty from ..low_level_api import BaseLowLevelWCS from .base import BaseWCSWrapper __all__ = ['sanitize_slices', 'SlicedLowLevelWCS'] def sanitize_slices(slices, ndim): """ Given a slice as input sanitise it to an easier to parse format.format This function returns a list ``ndim`` long containing slice objects (or ints). """ if not isinstance(slices, (tuple, list)): # We just have a single int slices = (slices,) if len(slices) > ndim: raise ValueError( f"The dimensionality of the specified slice {slices} can not be greater " f"than the dimensionality ({ndim}) of the wcs.") if any((isiterable(s) for s in slices)): raise IndexError("This slice is invalid, only integer or range slices are supported.") slices = list(slices) if Ellipsis in slices: if slices.count(Ellipsis) > 1: raise IndexError("an index can only have a single ellipsis ('...')") # Replace the Ellipsis with the correct number of slice(None)s e_ind = slices.index(Ellipsis) slices.remove(Ellipsis) n_e = ndim - len(slices) for i in range(n_e): ind = e_ind + i slices.insert(ind, slice(None)) for i in range(ndim): if i < len(slices): slc = slices[i] if isinstance(slc, slice): if slc.step and slc.step != 1: raise IndexError("Slicing WCS with a step is not supported.") elif not isinstance(slc, numbers.Integral): raise IndexError("Only integer or range slices are accepted.") else: slices.append(slice(None)) return slices def combine_slices(slice1, slice2): """ Given two slices that can be applied to a 1-d array, find the resulting slice that corresponds to the combination of both slices. We assume that slice2 can be an integer, but slice1 cannot. """ if isinstance(slice1, slice) and slice1.step is not None: raise ValueError('Only slices with steps of 1 are supported') if isinstance(slice2, slice) and slice2.step is not None: raise ValueError('Only slices with steps of 1 are supported') if isinstance(slice2, numbers.Integral): if slice1.start is None: return slice2 else: return slice2 + slice1.start if slice1.start is None: if slice1.stop is None: return slice2 else: if slice2.stop is None: return slice(slice2.start, slice1.stop) else: return slice(slice2.start, min(slice1.stop, slice2.stop)) else: if slice2.start is None: start = slice1.start else: start = slice1.start + slice2.start if slice2.stop is None: stop = slice1.stop else: if slice1.start is None: stop = slice2.stop else: stop = slice2.stop + slice1.start if slice1.stop is not None: stop = min(slice1.stop, stop) return slice(start, stop) class SlicedLowLevelWCS(BaseWCSWrapper): """ A Low Level WCS wrapper which applies an array slice to a WCS. This class does not modify the underlying WCS object and can therefore drop coupled dimensions as it stores which pixel and world dimensions have been sliced out (or modified) in the underlying WCS and returns the modified results on all the Low Level WCS methods. Parameters ---------- wcs : `~astropy.wcs.wcsapi.BaseLowLevelWCS` The WCS to slice. slices : `slice` or `tuple` or `int` A valid array slice to apply to the WCS. """ def __init__(self, wcs, slices): slices = sanitize_slices(slices, wcs.pixel_n_dim) if isinstance(wcs, SlicedLowLevelWCS): # Here we combine the current slices with the previous slices # to avoid ending up with many nested WCSes self._wcs = wcs._wcs slices_original = wcs._slices_array.copy() for ipixel in range(wcs.pixel_n_dim): ipixel_orig = wcs._wcs.pixel_n_dim - 1 - wcs._pixel_keep[ipixel] ipixel_new = wcs.pixel_n_dim - 1 - ipixel slices_original[ipixel_orig] = combine_slices(slices_original[ipixel_orig], slices[ipixel_new]) self._slices_array = slices_original else: self._wcs = wcs self._slices_array = slices self._slices_pixel = self._slices_array[::-1] # figure out which pixel dimensions have been kept, then use axis correlation # matrix to figure out which world dims are kept self._pixel_keep = np.nonzero([not isinstance(self._slices_pixel[ip], numbers.Integral) for ip in range(self._wcs.pixel_n_dim)])[0] # axis_correlation_matrix[world, pixel] self._world_keep = np.nonzero( self._wcs.axis_correlation_matrix[:, self._pixel_keep].any(axis=1))[0] if len(self._pixel_keep) == 0 or len(self._world_keep) == 0: raise ValueError("Cannot slice WCS: the resulting WCS should have " "at least one pixel and one world dimension.") @lazyproperty def dropped_world_dimensions(self): """ Information describing the dropped world dimensions. """ world_coords = self._pixel_to_world_values_all(*[0]*len(self._pixel_keep)) dropped_info = defaultdict(list) for i in range(self._wcs.world_n_dim): if i in self._world_keep: continue if "world_axis_object_classes" not in dropped_info: dropped_info["world_axis_object_classes"] = dict() wao_classes = self._wcs.world_axis_object_classes wao_components = self._wcs.world_axis_object_components dropped_info["value"].append(world_coords[i]) dropped_info["world_axis_names"].append(self._wcs.world_axis_names[i]) dropped_info["world_axis_physical_types"].append(self._wcs.world_axis_physical_types[i]) dropped_info["world_axis_units"].append(self._wcs.world_axis_units[i]) dropped_info["world_axis_object_components"].append(wao_components[i]) dropped_info["world_axis_object_classes"].update(dict( filter( lambda x: x[0] == wao_components[i][0], wao_classes.items() ) )) dropped_info["serialized_classes"] = self.serialized_classes return dict(dropped_info) @property def pixel_n_dim(self): return len(self._pixel_keep) @property def world_n_dim(self): return len(self._world_keep) @property def world_axis_physical_types(self): return [self._wcs.world_axis_physical_types[i] for i in self._world_keep] @property def world_axis_units(self): return [self._wcs.world_axis_units[i] for i in self._world_keep] @property def pixel_axis_names(self): return [self._wcs.pixel_axis_names[i] for i in self._pixel_keep] @property def world_axis_names(self): return [self._wcs.world_axis_names[i] for i in self._world_keep] def _pixel_to_world_values_all(self, *pixel_arrays): pixel_arrays = tuple(map(np.asanyarray, pixel_arrays)) pixel_arrays_new = [] ipix_curr = -1 for ipix in range(self._wcs.pixel_n_dim): if isinstance(self._slices_pixel[ipix], numbers.Integral): pixel_arrays_new.append(self._slices_pixel[ipix]) else: ipix_curr += 1 if self._slices_pixel[ipix].start is not None: pixel_arrays_new.append(pixel_arrays[ipix_curr] + self._slices_pixel[ipix].start) else: pixel_arrays_new.append(pixel_arrays[ipix_curr]) pixel_arrays_new = np.broadcast_arrays(*pixel_arrays_new) return self._wcs.pixel_to_world_values(*pixel_arrays_new) def pixel_to_world_values(self, *pixel_arrays): world_arrays = self._pixel_to_world_values_all(*pixel_arrays) # Detect the case of a length 0 array if isinstance(world_arrays, np.ndarray) and not world_arrays.shape: return world_arrays if self._wcs.world_n_dim > 1: # Select the dimensions of the original WCS we are keeping. world_arrays = [world_arrays[iw] for iw in self._world_keep] # If there is only one world dimension (after slicing) we shouldn't return a tuple. if self.world_n_dim == 1: world_arrays = world_arrays[0] return world_arrays def world_to_pixel_values(self, *world_arrays): world_arrays = tuple(map(np.asanyarray, world_arrays)) world_arrays_new = [] iworld_curr = -1 for iworld in range(self._wcs.world_n_dim): if iworld in self._world_keep: iworld_curr += 1 world_arrays_new.append(world_arrays[iworld_curr]) else: world_arrays_new.append(1.) world_arrays_new = np.broadcast_arrays(*world_arrays_new) pixel_arrays = list(self._wcs.world_to_pixel_values(*world_arrays_new)) for ipixel in range(self._wcs.pixel_n_dim): if isinstance(self._slices_pixel[ipixel], slice) and self._slices_pixel[ipixel].start is not None: pixel_arrays[ipixel] -= self._slices_pixel[ipixel].start # Detect the case of a length 0 array if isinstance(pixel_arrays, np.ndarray) and not pixel_arrays.shape: return pixel_arrays pixel = tuple(pixel_arrays[ip] for ip in self._pixel_keep) if self.pixel_n_dim == 1 and self._wcs.pixel_n_dim > 1: pixel = pixel[0] return pixel @property def world_axis_object_components(self): return [self._wcs.world_axis_object_components[idx] for idx in self._world_keep] @property def world_axis_object_classes(self): keys_keep = [item[0] for item in self.world_axis_object_components] return dict([item for item in self._wcs.world_axis_object_classes.items() if item[0] in keys_keep]) @property def array_shape(self): if self._wcs.array_shape: return np.broadcast_to(0, self._wcs.array_shape)[tuple(self._slices_array)].shape @property def pixel_shape(self): if self.array_shape: return tuple(self.array_shape[::-1]) @property def pixel_bounds(self): if self._wcs.pixel_bounds is None: return bounds = [] for idx in self._pixel_keep: if self._slices_pixel[idx].start is None: bounds.append(self._wcs.pixel_bounds[idx]) else: imin, imax = self._wcs.pixel_bounds[idx] start = self._slices_pixel[idx].start bounds.append((imin - start, imax - start)) return tuple(bounds) @property def axis_correlation_matrix(self): return self._wcs.axis_correlation_matrix[self._world_keep][:, self._pixel_keep]
a6065e3f9bb90d20d2ab97bbddc477880021062c5853869c33f1c86b941e2adb
# Note that we test the main astropy.wcs.WCS class directly rather than testing # the mix-in class on its own (since it's not functional without being used as # a mix-in) import warnings from packaging.version import Version import numpy as np import pytest from numpy.testing import assert_equal, assert_allclose from itertools import product from astropy import units as u from astropy.time import Time from astropy.tests.helper import assert_quantity_allclose from astropy.units import Quantity from astropy.coordinates import ICRS, FK5, Galactic, SkyCoord, SpectralCoord, ITRS, EarthLocation from astropy.io.fits import Header from astropy.io.fits.verify import VerifyWarning from astropy.units.core import UnitsWarning from astropy.utils.data import get_pkg_data_filename from astropy.wcs.wcs import WCS, FITSFixedWarning from astropy.wcs.wcsapi.fitswcs import custom_ctype_to_ucd_mapping, VELOCITY_FRAMES from astropy.wcs._wcs import __version__ as wcsver from astropy.utils import iers from astropy.utils.exceptions import AstropyUserWarning ############################################################################### # The following example is the simplest WCS with default values ############################################################################### WCS_EMPTY = WCS(naxis=1) WCS_EMPTY.wcs.crpix = [1] def test_empty(): wcs = WCS_EMPTY # Low-level API assert wcs.pixel_n_dim == 1 assert wcs.world_n_dim == 1 assert wcs.array_shape is None assert wcs.pixel_shape is None assert wcs.world_axis_physical_types == [None] assert wcs.world_axis_units == [''] assert wcs.pixel_axis_names == [''] assert wcs.world_axis_names == [''] assert_equal(wcs.axis_correlation_matrix, True) assert wcs.world_axis_object_components == [('world', 0, 'value')] assert wcs.world_axis_object_classes['world'][0] is Quantity assert wcs.world_axis_object_classes['world'][1] == () assert wcs.world_axis_object_classes['world'][2]['unit'] is u.one assert_allclose(wcs.pixel_to_world_values(29), 29) assert_allclose(wcs.array_index_to_world_values(29), 29) assert np.ndim(wcs.pixel_to_world_values(29)) == 0 assert np.ndim(wcs.array_index_to_world_values(29)) == 0 assert_allclose(wcs.world_to_pixel_values(29), 29) assert_equal(wcs.world_to_array_index_values(29), (29,)) assert np.ndim(wcs.world_to_pixel_values(29)) == 0 assert np.ndim(wcs.world_to_array_index_values(29)) == 0 # High-level API coord = wcs.pixel_to_world(29) assert_quantity_allclose(coord, 29 * u.one) assert np.ndim(coord) == 0 coord = wcs.array_index_to_world(29) assert_quantity_allclose(coord, 29 * u.one) assert np.ndim(coord) == 0 coord = 15 * u.one x = wcs.world_to_pixel(coord) assert_allclose(x, 15.) assert np.ndim(x) == 0 i = wcs.world_to_array_index(coord) assert_equal(i, 15) assert np.ndim(i) == 0 ############################################################################### # The following example is a simple 2D image with celestial coordinates ############################################################################### HEADER_SIMPLE_CELESTIAL = """ WCSAXES = 2 CTYPE1 = RA---TAN CTYPE2 = DEC--TAN CRVAL1 = 10 CRVAL2 = 20 CRPIX1 = 30 CRPIX2 = 40 CDELT1 = -0.1 CDELT2 = 0.1 CROTA2 = 0. CUNIT1 = deg CUNIT2 = deg """ with warnings.catch_warnings(): warnings.simplefilter('ignore', VerifyWarning) WCS_SIMPLE_CELESTIAL = WCS(Header.fromstring( HEADER_SIMPLE_CELESTIAL, sep='\n')) def test_simple_celestial(): wcs = WCS_SIMPLE_CELESTIAL # Low-level API assert wcs.pixel_n_dim == 2 assert wcs.world_n_dim == 2 assert wcs.array_shape is None assert wcs.pixel_shape is None assert wcs.world_axis_physical_types == ['pos.eq.ra', 'pos.eq.dec'] assert wcs.world_axis_units == ['deg', 'deg'] assert wcs.pixel_axis_names == ['', ''] assert wcs.world_axis_names == ['', ''] assert_equal(wcs.axis_correlation_matrix, True) assert wcs.world_axis_object_components == [('celestial', 0, 'spherical.lon.degree'), ('celestial', 1, 'spherical.lat.degree')] assert wcs.world_axis_object_classes['celestial'][0] is SkyCoord assert wcs.world_axis_object_classes['celestial'][1] == () assert isinstance(wcs.world_axis_object_classes['celestial'][2]['frame'], ICRS) assert wcs.world_axis_object_classes['celestial'][2]['unit'] is u.deg assert_allclose(wcs.pixel_to_world_values(29, 39), (10, 20)) assert_allclose(wcs.array_index_to_world_values(39, 29), (10, 20)) assert_allclose(wcs.world_to_pixel_values(10, 20), (29., 39.)) assert_equal(wcs.world_to_array_index_values(10, 20), (39, 29)) # High-level API coord = wcs.pixel_to_world(29, 39) assert isinstance(coord, SkyCoord) assert isinstance(coord.frame, ICRS) assert_allclose(coord.ra.deg, 10) assert_allclose(coord.dec.deg, 20) coord = wcs.array_index_to_world(39, 29) assert isinstance(coord, SkyCoord) assert isinstance(coord.frame, ICRS) assert_allclose(coord.ra.deg, 10) assert_allclose(coord.dec.deg, 20) coord = SkyCoord(10, 20, unit='deg', frame='icrs') x, y = wcs.world_to_pixel(coord) assert_allclose(x, 29.) assert_allclose(y, 39.) i, j = wcs.world_to_array_index(coord) assert_equal(i, 39) assert_equal(j, 29) # Check that if the coordinates are passed in a different frame things still # work properly coord_galactic = coord.galactic x, y = wcs.world_to_pixel(coord_galactic) assert_allclose(x, 29.) assert_allclose(y, 39.) i, j = wcs.world_to_array_index(coord_galactic) assert_equal(i, 39) assert_equal(j, 29) # Check that we can actually index the array data = np.arange(3600).reshape((60, 60)) coord = SkyCoord(10, 20, unit='deg', frame='icrs') index = wcs.world_to_array_index(coord) assert_equal(data[index], 2369) coord = SkyCoord([10, 12], [20, 22], unit='deg', frame='icrs') index = wcs.world_to_array_index(coord) assert_equal(data[index], [2369, 3550]) ############################################################################### # The following example is a spectral cube with axes in an unusual order ############################################################################### HEADER_SPECTRAL_CUBE = """ WCSAXES = 3 CTYPE1 = GLAT-CAR CTYPE2 = FREQ CTYPE3 = GLON-CAR CNAME1 = Latitude CNAME2 = Frequency CNAME3 = Longitude CRVAL1 = 10 CRVAL2 = 20 CRVAL3 = 25 CRPIX1 = 30 CRPIX2 = 40 CRPIX3 = 45 CDELT1 = -0.1 CDELT2 = 0.5 CDELT3 = 0.1 CUNIT1 = deg CUNIT2 = Hz CUNIT3 = deg """ with warnings.catch_warnings(): warnings.simplefilter('ignore', VerifyWarning) WCS_SPECTRAL_CUBE = WCS(Header.fromstring(HEADER_SPECTRAL_CUBE, sep='\n')) def test_spectral_cube(): # Spectral cube with a weird axis ordering wcs = WCS_SPECTRAL_CUBE # Low-level API assert wcs.pixel_n_dim == 3 assert wcs.world_n_dim == 3 assert wcs.array_shape is None assert wcs.pixel_shape is None assert wcs.world_axis_physical_types == ['pos.galactic.lat', 'em.freq', 'pos.galactic.lon'] assert wcs.world_axis_units == ['deg', 'Hz', 'deg'] assert wcs.pixel_axis_names == ['', '', ''] assert wcs.world_axis_names == ['Latitude', 'Frequency', 'Longitude'] assert_equal(wcs.axis_correlation_matrix, [[True, False, True], [False, True, False], [True, False, True]]) assert len(wcs.world_axis_object_components) == 3 assert wcs.world_axis_object_components[0] == ('celestial', 1, 'spherical.lat.degree') assert wcs.world_axis_object_components[1][:2] == ('spectral', 0) assert wcs.world_axis_object_components[2] == ('celestial', 0, 'spherical.lon.degree') assert wcs.world_axis_object_classes['celestial'][0] is SkyCoord assert wcs.world_axis_object_classes['celestial'][1] == () assert isinstance(wcs.world_axis_object_classes['celestial'][2]['frame'], Galactic) assert wcs.world_axis_object_classes['celestial'][2]['unit'] is u.deg assert wcs.world_axis_object_classes['spectral'][0] is Quantity assert wcs.world_axis_object_classes['spectral'][1] == () assert wcs.world_axis_object_classes['spectral'][2] == {} assert_allclose(wcs.pixel_to_world_values(29, 39, 44), (10, 20, 25)) assert_allclose(wcs.array_index_to_world_values(44, 39, 29), (10, 20, 25)) assert_allclose(wcs.world_to_pixel_values(10, 20, 25), (29., 39., 44.)) assert_equal(wcs.world_to_array_index_values(10, 20, 25), (44, 39, 29)) # High-level API coord, spec = wcs.pixel_to_world(29, 39, 44) assert isinstance(coord, SkyCoord) assert isinstance(coord.frame, Galactic) assert_allclose(coord.l.deg, 25) assert_allclose(coord.b.deg, 10) assert isinstance(spec, SpectralCoord) assert_allclose(spec.to_value(u.Hz), 20) coord, spec = wcs.array_index_to_world(44, 39, 29) assert isinstance(coord, SkyCoord) assert isinstance(coord.frame, Galactic) assert_allclose(coord.l.deg, 25) assert_allclose(coord.b.deg, 10) assert isinstance(spec, SpectralCoord) assert_allclose(spec.to_value(u.Hz), 20) coord = SkyCoord(25, 10, unit='deg', frame='galactic') spec = 20 * u.Hz with pytest.warns(AstropyUserWarning, match='No observer defined on WCS'): x, y, z = wcs.world_to_pixel(coord, spec) assert_allclose(x, 29.) assert_allclose(y, 39.) assert_allclose(z, 44.) # Order of world coordinates shouldn't matter with pytest.warns(AstropyUserWarning, match='No observer defined on WCS'): x, y, z = wcs.world_to_pixel(spec, coord) assert_allclose(x, 29.) assert_allclose(y, 39.) assert_allclose(z, 44.) with pytest.warns(AstropyUserWarning, match='No observer defined on WCS'): i, j, k = wcs.world_to_array_index(coord, spec) assert_equal(i, 44) assert_equal(j, 39) assert_equal(k, 29) # Order of world coordinates shouldn't matter with pytest.warns(AstropyUserWarning, match='No observer defined on WCS'): i, j, k = wcs.world_to_array_index(spec, coord) assert_equal(i, 44) assert_equal(j, 39) assert_equal(k, 29) HEADER_SPECTRAL_CUBE_NONALIGNED = HEADER_SPECTRAL_CUBE.strip() + '\n' + """ PC2_3 = -0.5 PC3_2 = +0.5 """ with warnings.catch_warnings(): warnings.simplefilter('ignore', VerifyWarning) WCS_SPECTRAL_CUBE_NONALIGNED = WCS(Header.fromstring( HEADER_SPECTRAL_CUBE_NONALIGNED, sep='\n')) def test_spectral_cube_nonaligned(): # Make sure that correlation matrix gets adjusted if there are non-identity # CD matrix terms. wcs = WCS_SPECTRAL_CUBE_NONALIGNED assert wcs.world_axis_physical_types == ['pos.galactic.lat', 'em.freq', 'pos.galactic.lon'] assert wcs.world_axis_units == ['deg', 'Hz', 'deg'] assert wcs.pixel_axis_names == ['', '', ''] assert wcs.world_axis_names == ['Latitude', 'Frequency', 'Longitude'] assert_equal(wcs.axis_correlation_matrix, [[True, True, True], [False, True, True], [True, True, True]]) # NOTE: we check world_axis_object_components and world_axis_object_classes # again here because in the past this failed when non-aligned axes were # present, so this serves as a regression test. assert len(wcs.world_axis_object_components) == 3 assert wcs.world_axis_object_components[0] == ('celestial', 1, 'spherical.lat.degree') assert wcs.world_axis_object_components[1][:2] == ('spectral', 0) assert wcs.world_axis_object_components[2] == ('celestial', 0, 'spherical.lon.degree') assert wcs.world_axis_object_classes['celestial'][0] is SkyCoord assert wcs.world_axis_object_classes['celestial'][1] == () assert isinstance(wcs.world_axis_object_classes['celestial'][2]['frame'], Galactic) assert wcs.world_axis_object_classes['celestial'][2]['unit'] is u.deg assert wcs.world_axis_object_classes['spectral'][0] is Quantity assert wcs.world_axis_object_classes['spectral'][1] == () assert wcs.world_axis_object_classes['spectral'][2] == {} ############################################################################### # The following example is from Rots et al (2015), Table 5. It represents a # cube with two spatial dimensions and one time dimension ############################################################################### HEADER_TIME_CUBE = """ SIMPLE = T / Fits standard BITPIX = -32 / Bits per pixel NAXIS = 3 / Number of axes NAXIS1 = 2048 / Axis length NAXIS2 = 2048 / Axis length NAXIS3 = 11 / Axis length DATE = '2008-10-28T14:39:06' / Date FITS file was generated OBJECT = '2008 TC3' / Name of the object observed EXPTIME = 1.0011 / Integration time MJD-OBS = 54746.02749237 / Obs start DATE-OBS= '2008-10-07T00:39:35.3342' / Observing date TELESCOP= 'VISTA' / ESO Telescope Name INSTRUME= 'VIRCAM' / Instrument used. TIMESYS = 'UTC' / From Observatory Time System TREFPOS = 'TOPOCENT' / Topocentric MJDREF = 54746.0 / Time reference point in MJD RADESYS = 'ICRS' / Not equinoctal CTYPE2 = 'RA---ZPN' / Zenithal Polynomial Projection CRVAL2 = 2.01824372640628 / RA at ref pixel CUNIT2 = 'deg' / Angles are degrees always CRPIX2 = 2956.6 / Pixel coordinate at ref point CTYPE1 = 'DEC--ZPN' / Zenithal Polynomial Projection CRVAL1 = 14.8289418840003 / Dec at ref pixel CUNIT1 = 'deg' / Angles are degrees always CRPIX1 = -448.2 / Pixel coordinate at ref point CTYPE3 = 'UTC' / linear time (UTC) CRVAL3 = 2375.341 / Relative time of first frame CUNIT3 = 's' / Time unit CRPIX3 = 1.0 / Pixel coordinate at ref point CTYPE3A = 'TT' / alternative linear time (TT) CRVAL3A = 2440.525 / Relative time of first frame CUNIT3A = 's' / Time unit CRPIX3A = 1.0 / Pixel coordinate at ref point OBSGEO-B= -24.6157 / [deg] Tel geodetic latitude (=North)+ OBSGEO-L= -70.3976 / [deg] Tel geodetic longitude (=East)+ OBSGEO-H= 2530.0000 / [m] Tel height above reference ellipsoid CRDER3 = 0.0819 / random error in timings from fit CSYER3 = 0.0100 / absolute time error PC1_1 = 0.999999971570892 / WCS transform matrix element PC1_2 = 0.000238449608932 / WCS transform matrix element PC2_1 = -0.000621542859395 / WCS transform matrix element PC2_2 = 0.999999806842218 / WCS transform matrix element CDELT1 = -9.48575432499806E-5 / Axis scale at reference point CDELT2 = 9.48683176211164E-5 / Axis scale at reference point CDELT3 = 13.3629 / Axis scale at reference point PV1_1 = 1. / ZPN linear term PV1_3 = 42. / ZPN cubic term """ with warnings.catch_warnings(): warnings.simplefilter('ignore', (VerifyWarning, FITSFixedWarning)) WCS_TIME_CUBE = WCS(Header.fromstring(HEADER_TIME_CUBE, sep='\n')) def test_time_cube(): # Spectral cube with a weird axis ordering wcs = WCS_TIME_CUBE assert wcs.pixel_n_dim == 3 assert wcs.world_n_dim == 3 assert wcs.array_shape == (11, 2048, 2048) assert wcs.pixel_shape == (2048, 2048, 11) assert wcs.world_axis_physical_types == ['pos.eq.dec', 'pos.eq.ra', 'time'] assert wcs.world_axis_units == ['deg', 'deg', 's'] assert wcs.pixel_axis_names == ['', '', ''] assert wcs.world_axis_names == ['', '', ''] assert_equal(wcs.axis_correlation_matrix, [[True, True, False], [True, True, False], [False, False, True]]) components = wcs.world_axis_object_components assert components[0] == ('celestial', 1, 'spherical.lat.degree') assert components[1] == ('celestial', 0, 'spherical.lon.degree') assert components[2][:2] == ('time', 0) assert callable(components[2][2]) assert wcs.world_axis_object_classes['celestial'][0] is SkyCoord assert wcs.world_axis_object_classes['celestial'][1] == () assert isinstance(wcs.world_axis_object_classes['celestial'][2]['frame'], ICRS) assert wcs.world_axis_object_classes['celestial'][2]['unit'] is u.deg assert wcs.world_axis_object_classes['time'][0] is Time assert wcs.world_axis_object_classes['time'][1] == () assert wcs.world_axis_object_classes['time'][2] == {} assert callable(wcs.world_axis_object_classes['time'][3]) assert_allclose(wcs.pixel_to_world_values(-449.2, 2955.6, 0), (14.8289418840003, 2.01824372640628, 2375.341)) assert_allclose(wcs.array_index_to_world_values(0, 2955.6, -449.2), (14.8289418840003, 2.01824372640628, 2375.341)) assert_allclose(wcs.world_to_pixel_values(14.8289418840003, 2.01824372640628, 2375.341), (-449.2, 2955.6, 0)) assert_equal(wcs.world_to_array_index_values(14.8289418840003, 2.01824372640628, 2375.341), (0, 2956, -449)) # High-level API coord, time = wcs.pixel_to_world(29, 39, 44) assert isinstance(coord, SkyCoord) assert isinstance(coord.frame, ICRS) assert_allclose(coord.ra.deg, 1.7323356692202325) assert_allclose(coord.dec.deg, 14.783516054817797) assert isinstance(time, Time) assert_allclose(time.mjd, 54746.03429755324) coord, time = wcs.array_index_to_world(44, 39, 29) assert isinstance(coord, SkyCoord) assert isinstance(coord.frame, ICRS) assert_allclose(coord.ra.deg, 1.7323356692202325) assert_allclose(coord.dec.deg, 14.783516054817797) assert isinstance(time, Time) assert_allclose(time.mjd, 54746.03429755324) x, y, z = wcs.world_to_pixel(coord, time) assert_allclose(x, 29.) assert_allclose(y, 39.) assert_allclose(z, 44.) # Order of world coordinates shouldn't matter x, y, z = wcs.world_to_pixel(time, coord) assert_allclose(x, 29.) assert_allclose(y, 39.) assert_allclose(z, 44.) i, j, k = wcs.world_to_array_index(coord, time) assert_equal(i, 44) assert_equal(j, 39) assert_equal(k, 29) # Order of world coordinates shouldn't matter i, j, k = wcs.world_to_array_index(time, coord) assert_equal(i, 44) assert_equal(j, 39) assert_equal(k, 29) ############################################################################### # The following tests are to make sure that Time objects are constructed # correctly for a variety of combinations of WCS keywords ############################################################################### HEADER_TIME_1D = """ SIMPLE = T BITPIX = -32 NAXIS = 1 NAXIS1 = 2048 TIMESYS = 'UTC' TREFPOS = 'TOPOCENT' MJDREF = 50002.6 CTYPE1 = 'UTC' CRVAL1 = 5 CUNIT1 = 's' CRPIX1 = 1.0 CDELT1 = 2 OBSGEO-L= -20 OBSGEO-B= -70 OBSGEO-H= 2530 """ if Version(wcsver) >= Version('7.1'): HEADER_TIME_1D += "DATEREF = '1995-10-12T14:24:00'\n" @pytest.fixture def header_time_1d(): return Header.fromstring(HEADER_TIME_1D, sep='\n') def assert_time_at(header, position, jd1, jd2, scale, format): with warnings.catch_warnings(): warnings.simplefilter('ignore', FITSFixedWarning) wcs = WCS(header) time = wcs.pixel_to_world(position) assert_allclose(time.jd1, jd1, rtol=1e-10) assert_allclose(time.jd2, jd2, rtol=1e-10) assert time.format == format assert time.scale == scale @pytest.mark.parametrize('scale', ('tai', 'tcb', 'tcg', 'tdb', 'tt', 'ut1', 'utc', 'local')) def test_time_1d_values(header_time_1d, scale): # Check that Time objects are instantiated with the correct values, # scales, and formats. header_time_1d['CTYPE1'] = scale.upper() assert_time_at(header_time_1d, 1, 2450003, 0.1 + 7 / 3600 / 24, scale, 'mjd') def test_time_1d_values_gps(header_time_1d): # Special treatment for GPS scale header_time_1d['CTYPE1'] = 'GPS' assert_time_at(header_time_1d, 1, 2450003, 0.1 + (7 + 19) / 3600 / 24, 'tai', 'mjd') def test_time_1d_values_deprecated(header_time_1d): # Deprecated (in FITS) scales header_time_1d['CTYPE1'] = 'TDT' assert_time_at(header_time_1d, 1, 2450003, 0.1 + 7 / 3600 / 24, 'tt', 'mjd') header_time_1d['CTYPE1'] = 'IAT' assert_time_at(header_time_1d, 1, 2450003, 0.1 + 7 / 3600 / 24, 'tai', 'mjd') header_time_1d['CTYPE1'] = 'GMT' assert_time_at(header_time_1d, 1, 2450003, 0.1 + 7 / 3600 / 24, 'utc', 'mjd') header_time_1d['CTYPE1'] = 'ET' assert_time_at(header_time_1d, 1, 2450003, 0.1 + 7 / 3600 / 24, 'tt', 'mjd') def test_time_1d_values_time(header_time_1d): header_time_1d['CTYPE1'] = 'TIME' assert_time_at(header_time_1d, 1, 2450003, 0.1 + 7 / 3600 / 24, 'utc', 'mjd') header_time_1d['TIMESYS'] = 'TAI' assert_time_at(header_time_1d, 1, 2450003, 0.1 + 7 / 3600 / 24, 'tai', 'mjd') @pytest.mark.remote_data @pytest.mark.parametrize('scale', ('tai', 'tcb', 'tcg', 'tdb', 'tt', 'ut1', 'utc')) def test_time_1d_roundtrip(header_time_1d, scale): # Check that coordinates round-trip pixel_in = np.arange(3, 10) header_time_1d['CTYPE1'] = scale.upper() with warnings.catch_warnings(): warnings.simplefilter('ignore', FITSFixedWarning) wcs = WCS(header_time_1d) # Simple test time = wcs.pixel_to_world(pixel_in) pixel_out = wcs.world_to_pixel(time) assert_allclose(pixel_in, pixel_out) # Test with an intermediate change to a different scale/format time = wcs.pixel_to_world(pixel_in).tdb time.format = 'isot' pixel_out = wcs.world_to_pixel(time) assert_allclose(pixel_in, pixel_out) def test_time_1d_high_precision(header_time_1d): # Case where the MJDREF is split into two for high precision del header_time_1d['MJDREF'] header_time_1d['MJDREFI'] = 52000. header_time_1d['MJDREFF'] = 1e-11 with warnings.catch_warnings(): warnings.simplefilter('ignore', FITSFixedWarning) wcs = WCS(header_time_1d) time = wcs.pixel_to_world(10) # Here we have to use a very small rtol to really test that MJDREFF is # taken into account assert_allclose(time.jd1, 2452001.0, rtol=1e-12) assert_allclose(time.jd2, -0.5 + 25 / 3600 / 24 + 1e-11, rtol=1e-13) def test_time_1d_location_geodetic(header_time_1d): # Make sure that the location is correctly returned (geodetic case) with warnings.catch_warnings(): warnings.simplefilter('ignore', FITSFixedWarning) wcs = WCS(header_time_1d) time = wcs.pixel_to_world(10) lon, lat, alt = time.location.to_geodetic() # FIXME: alt won't work for now because ERFA doesn't implement the IAU 1976 # ellipsoid (https://github.com/astropy/astropy/issues/9420) assert_allclose(lon.degree, -20) assert_allclose(lat.degree, -70) # assert_allclose(alt.to_value(u.m), 2530.) @pytest.fixture def header_time_1d_no_obs(): header = Header.fromstring(HEADER_TIME_1D, sep='\n') del header['OBSGEO-L'] del header['OBSGEO-B'] del header['OBSGEO-H'] return header def test_time_1d_location_geocentric(header_time_1d_no_obs): # Make sure that the location is correctly returned (geocentric case) header = header_time_1d_no_obs header['OBSGEO-X'] = 10 header['OBSGEO-Y'] = -20 header['OBSGEO-Z'] = 30 with warnings.catch_warnings(): warnings.simplefilter('ignore', FITSFixedWarning) wcs = WCS(header) time = wcs.pixel_to_world(10) x, y, z = time.location.to_geocentric() assert_allclose(x.to_value(u.m), 10) assert_allclose(y.to_value(u.m), -20) assert_allclose(z.to_value(u.m), 30) def test_time_1d_location_geocenter(header_time_1d_no_obs): header_time_1d_no_obs['TREFPOS'] = 'GEOCENTER' wcs = WCS(header_time_1d_no_obs) time = wcs.pixel_to_world(10) x, y, z = time.location.to_geocentric() assert_allclose(x.to_value(u.m), 0) assert_allclose(y.to_value(u.m), 0) assert_allclose(z.to_value(u.m), 0) def test_time_1d_location_missing(header_time_1d_no_obs): # Check what happens when no location is present wcs = WCS(header_time_1d_no_obs) with pytest.warns(UserWarning, match='Missing or incomplete observer location ' 'information, setting location in Time to None'): time = wcs.pixel_to_world(10) assert time.location is None def test_time_1d_location_incomplete(header_time_1d_no_obs): # Check what happens when location information is incomplete header_time_1d_no_obs['OBSGEO-L'] = 10. with warnings.catch_warnings(): warnings.simplefilter('ignore', FITSFixedWarning) wcs = WCS(header_time_1d_no_obs) with pytest.warns(UserWarning, match='Missing or incomplete observer location ' 'information, setting location in Time to None'): time = wcs.pixel_to_world(10) assert time.location is None def test_time_1d_location_unsupported(header_time_1d_no_obs): # Check what happens when TREFPOS is unsupported header_time_1d_no_obs['TREFPOS'] = 'BARYCENTER' wcs = WCS(header_time_1d_no_obs) with pytest.warns(UserWarning, match="Observation location 'barycenter' is not " "supported, setting location in Time to None"): time = wcs.pixel_to_world(10) assert time.location is None def test_time_1d_unsupported_ctype(header_time_1d_no_obs): # For cases that we don't support yet, e.g. UT(...), use Time and drop sub-scale # Case where the MJDREF is split into two for high precision header_time_1d_no_obs['CTYPE1'] = 'UT(WWV)' wcs = WCS(header_time_1d_no_obs) with pytest.warns(UserWarning, match="Dropping unsupported sub-scale WWV from scale UT"): time = wcs.pixel_to_world(10) assert isinstance(time, Time) ############################################################################### # Extra corner cases ############################################################################### def test_unrecognized_unit(): # TODO: Determine whether the following behavior is desirable wcs = WCS(naxis=1) with pytest.warns(UnitsWarning): wcs.wcs.cunit = ['bananas // sekonds'] assert wcs.world_axis_units == ['bananas // sekonds'] def test_distortion_correlations(): filename = get_pkg_data_filename('../../tests/data/sip.fits') with pytest.warns(FITSFixedWarning): w = WCS(filename) assert_equal(w.axis_correlation_matrix, True) # Changing PC to an identity matrix doesn't change anything since # distortions are still present. w.wcs.pc = [[1, 0], [0, 1]] assert_equal(w.axis_correlation_matrix, True) # Nor does changing the name of the axes to make them non-celestial w.wcs.ctype = ['X', 'Y'] assert_equal(w.axis_correlation_matrix, True) # However once we turn off the distortions the matrix changes w.sip = None assert_equal(w.axis_correlation_matrix, [[True, False], [False, True]]) # If we go back to celestial coordinates then the matrix is all True again w.wcs.ctype = ['RA---TAN', 'DEC--TAN'] assert_equal(w.axis_correlation_matrix, True) # Or if we change to X/Y but have a non-identity PC w.wcs.pc = [[0.9, -0.1], [0.1, 0.9]] w.wcs.ctype = ['X', 'Y'] assert_equal(w.axis_correlation_matrix, True) def test_custom_ctype_to_ucd_mappings(): wcs = WCS(naxis=1) wcs.wcs.ctype = ['SPAM'] assert wcs.world_axis_physical_types == [None] # Check simple behavior with custom_ctype_to_ucd_mapping({'APPLE': 'food.fruit'}): assert wcs.world_axis_physical_types == [None] with custom_ctype_to_ucd_mapping({'APPLE': 'food.fruit', 'SPAM': 'food.spam'}): assert wcs.world_axis_physical_types == ['food.spam'] # Check nesting with custom_ctype_to_ucd_mapping({'SPAM': 'food.spam'}): with custom_ctype_to_ucd_mapping({'APPLE': 'food.fruit'}): assert wcs.world_axis_physical_types == ['food.spam'] with custom_ctype_to_ucd_mapping({'APPLE': 'food.fruit'}): with custom_ctype_to_ucd_mapping({'SPAM': 'food.spam'}): assert wcs.world_axis_physical_types == ['food.spam'] # Check priority in nesting with custom_ctype_to_ucd_mapping({'SPAM': 'notfood'}): with custom_ctype_to_ucd_mapping({'SPAM': 'food.spam'}): assert wcs.world_axis_physical_types == ['food.spam'] with custom_ctype_to_ucd_mapping({'SPAM': 'food.spam'}): with custom_ctype_to_ucd_mapping({'SPAM': 'notfood'}): assert wcs.world_axis_physical_types == ['notfood'] def test_caching_components_and_classes(): # Make sure that when we change the WCS object, the classes and components # are updated (we use a cache internally, so we need to make sure the cache # is invalidated if needed) wcs = WCS_SIMPLE_CELESTIAL.deepcopy() assert wcs.world_axis_object_components == [('celestial', 0, 'spherical.lon.degree'), ('celestial', 1, 'spherical.lat.degree')] assert wcs.world_axis_object_classes['celestial'][0] is SkyCoord assert wcs.world_axis_object_classes['celestial'][1] == () assert isinstance(wcs.world_axis_object_classes['celestial'][2]['frame'], ICRS) assert wcs.world_axis_object_classes['celestial'][2]['unit'] is u.deg wcs.wcs.radesys = 'FK5' frame = wcs.world_axis_object_classes['celestial'][2]['frame'] assert isinstance(frame, FK5) assert frame.equinox.jyear == 2000. wcs.wcs.equinox = 2010 frame = wcs.world_axis_object_classes['celestial'][2]['frame'] assert isinstance(frame, FK5) assert frame.equinox.jyear == 2010. def test_sub_wcsapi_attributes(): # Regression test for a bug that caused some of the WCS attributes to be # incorrect when using WCS.sub or WCS.celestial (which is an alias for sub # with lon/lat types). wcs = WCS_SPECTRAL_CUBE.deepcopy() wcs.pixel_shape = (30, 40, 50) wcs.pixel_bounds = [(-1, 11), (-2, 18), (5, 15)] # Use celestial shortcut wcs_sub1 = wcs.celestial assert wcs_sub1.pixel_n_dim == 2 assert wcs_sub1.world_n_dim == 2 assert wcs_sub1.array_shape == (50, 30) assert wcs_sub1.pixel_shape == (30, 50) assert wcs_sub1.pixel_bounds == [(-1, 11), (5, 15)] assert wcs_sub1.world_axis_physical_types == ['pos.galactic.lat', 'pos.galactic.lon'] assert wcs_sub1.world_axis_units == ['deg', 'deg'] assert wcs_sub1.world_axis_names == ['Latitude', 'Longitude'] # Try adding axes wcs_sub2 = wcs.sub([0, 2, 0]) assert wcs_sub2.pixel_n_dim == 3 assert wcs_sub2.world_n_dim == 3 assert wcs_sub2.array_shape == (None, 40, None) assert wcs_sub2.pixel_shape == (None, 40, None) assert wcs_sub2.pixel_bounds == [None, (-2, 18), None] assert wcs_sub2.world_axis_physical_types == [None, 'em.freq', None] assert wcs_sub2.world_axis_units == ['', 'Hz', ''] assert wcs_sub2.world_axis_names == ['', 'Frequency', ''] # Use strings wcs_sub3 = wcs.sub(['longitude', 'latitude']) assert wcs_sub3.pixel_n_dim == 2 assert wcs_sub3.world_n_dim == 2 assert wcs_sub3.array_shape == (30, 50) assert wcs_sub3.pixel_shape == (50, 30) assert wcs_sub3.pixel_bounds == [(5, 15), (-1, 11)] assert wcs_sub3.world_axis_physical_types == ['pos.galactic.lon', 'pos.galactic.lat'] assert wcs_sub3.world_axis_units == ['deg', 'deg'] assert wcs_sub3.world_axis_names == ['Longitude', 'Latitude'] # Now try without CNAME set wcs.wcs.cname = [''] * wcs.wcs.naxis wcs_sub4 = wcs.sub(['longitude', 'latitude']) assert wcs_sub4.pixel_n_dim == 2 assert wcs_sub4.world_n_dim == 2 assert wcs_sub4.array_shape == (30, 50) assert wcs_sub4.pixel_shape == (50, 30) assert wcs_sub4.pixel_bounds == [(5, 15), (-1, 11)] assert wcs_sub4.world_axis_physical_types == ['pos.galactic.lon', 'pos.galactic.lat'] assert wcs_sub4.world_axis_units == ['deg', 'deg'] assert wcs_sub4.world_axis_names == ['', ''] HEADER_POLARIZED = """ CTYPE1 = 'HPLT-TAN' CTYPE2 = 'HPLN-TAN' CTYPE3 = 'STOKES' """ @pytest.fixture def header_polarized(): return Header.fromstring(HEADER_POLARIZED, sep='\n') def test_phys_type_polarization(header_polarized): w = WCS(header_polarized) assert w.world_axis_physical_types[2] == 'phys.polarization.stokes' ############################################################################### # Spectral transformations ############################################################################### HEADER_SPECTRAL_FRAMES = """ BUNIT = 'Jy/beam' EQUINOX = 2.000000000E+03 CTYPE1 = 'RA---SIN' CRVAL1 = 2.60108333333E+02 CDELT1 = -2.777777845E-04 CRPIX1 = 1.0 CUNIT1 = 'deg' CTYPE2 = 'DEC--SIN' CRVAL2 = -9.75000000000E-01 CDELT2 = 2.777777845E-04 CRPIX2 = 1.0 CUNIT2 = 'deg' CTYPE3 = 'FREQ' CRVAL3 = 1.37835117405E+09 CDELT3 = 9.765625000E+04 CRPIX3 = 32.0 CUNIT3 = 'Hz' SPECSYS = 'TOPOCENT' RESTFRQ = 1.420405752E+09 / [Hz] RADESYS = 'FK5' """ @pytest.fixture def header_spectral_frames(): return Header.fromstring(HEADER_SPECTRAL_FRAMES, sep='\n') def test_spectralcoord_frame(header_spectral_frames): # This is a test to check the numerical results of transformations between # different velocity frames. We simply make sure that the returned # SpectralCoords are in the right frame but don't check the transformations # since this is already done in test_spectralcoord_accuracy # in astropy.coordinates. with iers.conf.set_temp('auto_download', False): obstime = Time(f"2009-05-04T04:44:23", scale='utc') header = header_spectral_frames.copy() header['MJD-OBS'] = obstime.mjd header['CRVAL1'] = 16.33211 header['CRVAL2'] = -34.2221 header['OBSGEO-L'] = 144.2 header['OBSGEO-B'] = -20.2 header['OBSGEO-H'] = 0. # We start off with a WCS defined in topocentric frequency with pytest.warns(FITSFixedWarning): wcs_topo = WCS(header) # We convert a single pixel coordinate to world coordinates and keep only # the second high level object - a SpectralCoord: sc_topo = wcs_topo.pixel_to_world(0, 0, 31)[1] # We check that this is in topocentric frame with zero velocities assert isinstance(sc_topo, SpectralCoord) assert isinstance(sc_topo.observer, ITRS) assert sc_topo.observer.obstime.isot == obstime.isot assert_equal(sc_topo.observer.data.differentials['s'].d_xyz.value, 0) observatory = EarthLocation.from_geodetic(144.2, -20.2).get_itrs(obstime=obstime).transform_to(ICRS()) assert observatory.separation_3d(sc_topo.observer.transform_to(ICRS())) < 1 * u.km for specsys, expected_frame in VELOCITY_FRAMES.items(): header['SPECSYS'] = specsys with pytest.warns(FITSFixedWarning): wcs = WCS(header) sc = wcs.pixel_to_world(0, 0, 31)[1] # Now transform to the expected velocity frame, which should leave # the spectral coordinate unchanged sc_check = sc.with_observer_stationary_relative_to(expected_frame) assert_quantity_allclose(sc.quantity, sc_check.quantity) @pytest.mark.parametrize(('ctype3', 'observer'), product(['ZOPT', 'BETA', 'VELO', 'VRAD', 'VOPT'], [False, True])) def test_different_ctypes(header_spectral_frames, ctype3, observer): header = header_spectral_frames.copy() header['CTYPE3'] = ctype3 header['CRVAL3'] = 0.1 header['CDELT3'] = 0.001 if ctype3[0] == 'V': header['CUNIT3'] = 'm s-1' else: header['CUNIT3'] = '' header['RESTWAV'] = 1.420405752E+09 header['MJD-OBS'] = 55197 if observer: header['OBSGEO-L'] = 144.2 header['OBSGEO-B'] = -20.2 header['OBSGEO-H'] = 0. header['SPECSYS'] = 'BARYCENT' with warnings.catch_warnings(): warnings.simplefilter('ignore', FITSFixedWarning) wcs = WCS(header) skycoord, spectralcoord = wcs.pixel_to_world(0, 0, 31) assert isinstance(spectralcoord, SpectralCoord) if observer: pix = wcs.world_to_pixel(skycoord, spectralcoord) else: with pytest.warns(AstropyUserWarning, match='No observer defined on WCS'): pix = wcs.world_to_pixel(skycoord, spectralcoord) assert_allclose(pix, [0, 0, 31], rtol=1e-6)
a2d329c6d9f08be5c61f5206f62590ffcd13da05d3dc22d12e8ac5206136dfde
import numpy as np from numpy.testing import assert_allclose from astropy.units import Quantity from astropy.coordinates import SkyCoord from astropy.wcs.wcsapi.low_level_api import BaseLowLevelWCS from astropy.wcs.wcsapi.high_level_api import HighLevelWCSMixin, high_level_objects_to_values, values_to_high_level_objects class DoubleLowLevelWCS(BaseLowLevelWCS): """ Basic dummy transformation that doubles values. """ def pixel_to_world_values(self, *pixel_arrays): return [np.asarray(pix) * 2 for pix in pixel_arrays] def world_to_pixel_values(self, *world_arrays): return [np.asarray(world) / 2 for world in world_arrays] class SimpleDuplicateWCS(DoubleLowLevelWCS, HighLevelWCSMixin): """ This example WCS has two of the world coordinates that use the same class, which triggers a different path in the high level WCS code. """ @property def pixel_n_dim(self): return 2 @property def world_n_dim(self): return 2 @property def world_axis_physical_types(self): return ['pos.eq.ra', 'pos.eq.dec'] @property def world_axis_units(self): return ['deg', 'deg'] @property def world_axis_object_components(self): return [('test1', 0, 'value'), ('test2', 0, 'value')] @property def world_axis_object_classes(self): return {'test1': (Quantity, (), {'unit': 'deg'}), 'test2': (Quantity, (), {'unit': 'deg'})} def test_simple_duplicate(): # Make sure that things work properly when the low-level WCS uses the same # class for two of the coordinates. wcs = SimpleDuplicateWCS() q1, q2 = wcs.pixel_to_world(1, 2) assert isinstance(q1, Quantity) assert isinstance(q2, Quantity) x, y = wcs.world_to_pixel(q1, q2) assert_allclose(x, 1) assert_allclose(y, 2) class SkyCoordDuplicateWCS(DoubleLowLevelWCS, HighLevelWCSMixin): """ This example WCS returns two SkyCoord objects which, which triggers a different path in the high level WCS code. """ @property def pixel_n_dim(self): return 4 @property def world_n_dim(self): return 4 @property def world_axis_physical_types(self): return ['pos.eq.ra', 'pos.eq.dec', 'pos.galactic.lon', 'pos.galactic.lat'] @property def world_axis_units(self): return ['deg', 'deg', 'deg', 'deg'] @property def world_axis_object_components(self): # Deliberately use 'ra'/'dec' here to make sure that string argument # names work properly. return [('test1', 'ra', 'spherical.lon.degree'), ('test1', 'dec', 'spherical.lat.degree'), ('test2', 0, 'spherical.lon.degree'), ('test2', 1, 'spherical.lat.degree')] @property def world_axis_object_classes(self): return {'test1': (SkyCoord, (), {'unit': 'deg'}), 'test2': (SkyCoord, (), {'unit': 'deg', 'frame': 'galactic'})} def test_skycoord_duplicate(): # Make sure that things work properly when the low-level WCS uses the same # class, and specifically a SkyCoord for two of the coordinates. wcs = SkyCoordDuplicateWCS() c1, c2 = wcs.pixel_to_world(1, 2, 3, 4) assert isinstance(c1, SkyCoord) assert isinstance(c2, SkyCoord) x, y, z, a = wcs.world_to_pixel(c1, c2) assert_allclose(x, 1) assert_allclose(y, 2) assert_allclose(z, 3) assert_allclose(a, 4) class SerializedWCS(DoubleLowLevelWCS, HighLevelWCSMixin): """ WCS with serialized classes """ @property def serialized_classes(self): return True @property def pixel_n_dim(self): return 2 @property def world_n_dim(self): return 2 @property def world_axis_physical_types(self): return ['pos.eq.ra', 'pos.eq.dec'] @property def world_axis_units(self): return ['deg', 'deg'] @property def world_axis_object_components(self): return [('test', 0, 'value')] @property def world_axis_object_classes(self): return {'test': ('astropy.units.Quantity', (), {'unit': ('astropy.units.Unit', ('deg',), {})})} def test_serialized_classes(): wcs = SerializedWCS() q = wcs.pixel_to_world(1) assert isinstance(q, Quantity) x = wcs.world_to_pixel(q) assert_allclose(x, 1) def test_objects_to_values(): wcs = SkyCoordDuplicateWCS() c1, c2 = wcs.pixel_to_world(1, 2, 3, 4) values = high_level_objects_to_values(c1, c2, low_level_wcs=wcs) assert np.allclose(values, [2, 4, 6, 8]) def test_values_to_objects(): wcs = SkyCoordDuplicateWCS() c1, c2 = wcs.pixel_to_world(1, 2, 3, 4) c1_out, c2_out = values_to_high_level_objects(*[2,4,6,8], low_level_wcs=wcs) assert c1.ra == c1_out.ra assert c2.l == c2_out.l assert c1.dec == c1_out.dec assert c2.b == c2_out.b
9124e51ee9f7a99780d3c5cfe724f59cc42539b4588596c26464c1c427e2ccee
import numpy as np from numpy.testing import assert_allclose import pytest from pytest import raises from astropy import units as u from astropy.wcs import WCS from astropy.tests.helper import assert_quantity_allclose from astropy.wcs.wcsapi.utils import deserialize_class, wcs_info_str def test_construct(): result = deserialize_class(('astropy.units.Quantity', (10,), {'unit': 'deg'})) assert_quantity_allclose(result, 10 * u.deg) def test_noconstruct(): result = deserialize_class(('astropy.units.Quantity', (), {'unit': 'deg'}), construct=False) assert result == (u.Quantity, (), {'unit': 'deg'}) def test_invalid(): with raises(ValueError) as exc: deserialize_class(('astropy.units.Quantity', (), {'unit': 'deg'}, ())) assert exc.value.args[0] == 'Expected a tuple of three values' DEFAULT_1D_STR = """ WCS Transformation This transformation has 1 pixel and 1 world dimensions Array shape (Numpy order): None Pixel Dim Axis Name Data size Bounds 0 None None None World Dim Axis Name Physical Type Units 0 None None unknown Correlation between pixel and world axes: Pixel Dim World Dim 0 0 yes """ def test_wcs_info_str(): # The tests in test_sliced_low_level_wcs.py exercise wcs_info_str # extensively. This test is to ensure that the function exists and the # API of the function works as expected. wcs_empty = WCS(naxis=1) assert wcs_info_str(wcs_empty).strip() == DEFAULT_1D_STR.strip()
a0ccabbf0e260f8c89e19402a8e0d717cd900a2caa683e821180a9cf05e407da
from pytest import raises from astropy.wcs.wcsapi.low_level_api import validate_physical_types def test_validate_physical_types(): # Check valid cases validate_physical_types(['pos.eq.ra', 'pos.eq.ra']) validate_physical_types(['spect.dopplerVeloc.radio', 'custom:spam']) validate_physical_types(['time', None]) # Make sure validation is case sensitive with raises(ValueError, match=r"'Pos\.eq\.dec' is not a valid IOVA UCD1\+ physical type"): validate_physical_types(['pos.eq.ra', 'Pos.eq.dec']) # Make sure nonsense types are picked up with raises(ValueError, match=r"'spam' is not a valid IOVA UCD1\+ physical type"): validate_physical_types(['spam'])
0b2b622cdcd0e07b8018c7a848a96c4bf959aab1118e553138668c46ff4bc341
import pytest import numpy as np from numpy.testing import assert_allclose from astropy.coordinates import SkyCoord from astropy.wcs.wcsapi.low_level_api import BaseLowLevelWCS from astropy.wcs.wcsapi.high_level_wcs_wrapper import HighLevelWCSWrapper class CustomLowLevelWCS(BaseLowLevelWCS): @property def pixel_n_dim(self): return 2 @property def world_n_dim(self): return 2 @property def world_axis_physical_types(self): return ['pos.eq.ra', 'pos.eq.dec'] @property def world_axis_units(self): return ['deg', 'deg'] def pixel_to_world_values(self, *pixel_arrays): return [np.asarray(pix) * 2 for pix in pixel_arrays] def world_to_pixel_values(self, *world_arrays): return [np.asarray(world) / 2 for world in world_arrays] @property def world_axis_object_components(self): return [('test', 0, 'spherical.lon.degree'), ('test', 1, 'spherical.lat.degree')] @property def world_axis_object_classes(self): return {'test': (SkyCoord, (), {'unit': 'deg'})} def test_wrapper(): wcs = CustomLowLevelWCS() wrapper = HighLevelWCSWrapper(wcs) coord = wrapper.pixel_to_world(1, 2) assert isinstance(coord, SkyCoord) assert coord.isscalar x, y = wrapper.world_to_pixel(coord) assert_allclose(x, 1) assert_allclose(y, 2) assert wrapper.low_level_wcs is wcs assert wrapper.pixel_n_dim == 2 assert wrapper.world_n_dim == 2 assert wrapper.world_axis_physical_types == ['pos.eq.ra', 'pos.eq.dec'] assert wrapper.world_axis_units == ['deg', 'deg'] assert wrapper.array_shape is None assert wrapper.pixel_bounds is None assert np.all(wrapper.axis_correlation_matrix) def test_wrapper_invalid(): class InvalidCustomLowLevelWCS(CustomLowLevelWCS): @property def world_axis_object_classes(self): return {} wcs = InvalidCustomLowLevelWCS() wrapper = HighLevelWCSWrapper(wcs) with pytest.raises(KeyError): wrapper.pixel_to_world(1, 2)
a870efcfdea7fe14e61c2affac5219388d1383ca9ba5cb3914e87f6024c26802
import warnings import pytest import numpy as np from numpy.testing import assert_equal, assert_allclose from astropy.wcs.wcs import WCS, FITSFixedWarning from astropy.time import Time from astropy.wcs import WCS from astropy.io.fits import Header from astropy.io.fits.verify import VerifyWarning from astropy.coordinates import SkyCoord, Galactic, ICRS from astropy.units import Quantity from astropy.wcs.wcsapi.wrappers.sliced_wcs import SlicedLowLevelWCS, sanitize_slices, combine_slices from astropy.wcs.wcsapi.utils import wcs_info_str import astropy.units as u from astropy.coordinates.spectral_coordinate import SpectralCoord # To test the slicing we start off from standard FITS WCS # objects since those implement the low-level API. We create # a WCS for a spectral cube with axes in non-standard order # and with correlated celestial axes and an uncorrelated # spectral axis. HEADER_SPECTRAL_CUBE = """ NAXIS = 3 NAXIS1 = 10 NAXIS2 = 20 NAXIS3 = 30 CTYPE1 = GLAT-CAR CTYPE2 = FREQ CTYPE3 = GLON-CAR CNAME1 = Latitude CNAME2 = Frequency CNAME3 = Longitude CRVAL1 = 10 CRVAL2 = 20 CRVAL3 = 25 CRPIX1 = 30 CRPIX2 = 40 CRPIX3 = 45 CDELT1 = -0.1 CDELT2 = 0.5 CDELT3 = 0.1 CUNIT1 = deg CUNIT2 = Hz CUNIT3 = deg """ with warnings.catch_warnings(): warnings.simplefilter('ignore', VerifyWarning) WCS_SPECTRAL_CUBE = WCS(Header.fromstring(HEADER_SPECTRAL_CUBE, sep='\n')) WCS_SPECTRAL_CUBE.pixel_bounds = [(-1, 11), (-2, 18), (5, 15)] def test_invalid_slices(): with pytest.raises(IndexError): SlicedLowLevelWCS(WCS_SPECTRAL_CUBE, [None, None, [False, False, False]]) with pytest.raises(IndexError): SlicedLowLevelWCS(WCS_SPECTRAL_CUBE, [None, None, slice(None, None, 2)]) with pytest.raises(IndexError): SlicedLowLevelWCS(WCS_SPECTRAL_CUBE, [None, None, 1000.100]) @pytest.mark.parametrize("item, ndim, expected", ( ([Ellipsis, 10], 4, [slice(None)] * 3 + [10]), ([10, slice(20, 30)], 5, [10, slice(20, 30)] + [slice(None)] * 3), ([10, Ellipsis, 8], 10, [10] + [slice(None)] * 8 + [8]) )) def test_sanitize_slice(item, ndim, expected): new_item = sanitize_slices(item, ndim) # FIXME: do we still need the first two since the third assert # should cover it all? assert len(new_item) == ndim assert all(isinstance(i, (slice, int)) for i in new_item) assert new_item == expected EXPECTED_ELLIPSIS_REPR = """ SlicedLowLevelWCS Transformation This transformation has 3 pixel and 3 world dimensions Array shape (Numpy order): (30, 20, 10) Pixel Dim Axis Name Data size Bounds 0 None 10 (-1, 11) 1 None 20 (-2, 18) 2 None 30 (5, 15) World Dim Axis Name Physical Type Units 0 Latitude pos.galactic.lat deg 1 Frequency em.freq Hz 2 Longitude pos.galactic.lon deg Correlation between pixel and world axes: Pixel Dim World Dim 0 1 2 0 yes no yes 1 no yes no 2 yes no yes """ def test_ellipsis(): wcs = SlicedLowLevelWCS(WCS_SPECTRAL_CUBE, Ellipsis) assert wcs.pixel_n_dim == 3 assert wcs.world_n_dim == 3 assert wcs.array_shape == (30, 20, 10) assert wcs.pixel_shape == (10, 20, 30) assert wcs.world_axis_physical_types == ['pos.galactic.lat', 'em.freq', 'pos.galactic.lon'] assert wcs.world_axis_units == ['deg', 'Hz', 'deg'] assert wcs.pixel_axis_names == ['', '', ''] assert wcs.world_axis_names == ['Latitude', 'Frequency', 'Longitude'] assert_equal(wcs.axis_correlation_matrix, [[True, False, True], [False, True, False], [True, False, True]]) assert len(wcs.world_axis_object_components) == 3 assert wcs.world_axis_object_components[0] == ('celestial', 1, 'spherical.lat.degree') assert wcs.world_axis_object_components[1][:2] == ('spectral', 0) assert wcs.world_axis_object_components[2] == ('celestial', 0, 'spherical.lon.degree') assert wcs.world_axis_object_classes['celestial'][0] is SkyCoord assert wcs.world_axis_object_classes['celestial'][1] == () assert isinstance(wcs.world_axis_object_classes['celestial'][2]['frame'], Galactic) assert wcs.world_axis_object_classes['celestial'][2]['unit'] is u.deg assert wcs.world_axis_object_classes['spectral'][0] is Quantity assert wcs.world_axis_object_classes['spectral'][1] == () assert wcs.world_axis_object_classes['spectral'][2] == {} assert_allclose(wcs.pixel_to_world_values(29, 39, 44), (10, 20, 25)) assert_allclose(wcs.array_index_to_world_values(44, 39, 29), (10, 20, 25)) assert_allclose(wcs.world_to_pixel_values(10, 20, 25), (29., 39., 44.)) assert_equal(wcs.world_to_array_index_values(10, 20, 25), (44, 39, 29)) assert_equal(wcs.pixel_bounds, [(-1, 11), (-2, 18), (5, 15)]) assert str(wcs) == EXPECTED_ELLIPSIS_REPR.strip() assert EXPECTED_ELLIPSIS_REPR.strip() in repr(wcs) def test_pixel_to_world_broadcasting(): wcs = SlicedLowLevelWCS(WCS_SPECTRAL_CUBE, Ellipsis) assert_allclose(wcs.pixel_to_world_values((29, 29), 39, 44), ((10, 10), (20, 20), (25, 25))) def test_world_to_pixel_broadcasting(): wcs = SlicedLowLevelWCS(WCS_SPECTRAL_CUBE, Ellipsis) assert_allclose(wcs.world_to_pixel_values((10, 10), 20, 25), ((29., 29.), (39., 39.), (44., 44.))) EXPECTED_SPECTRAL_SLICE_REPR = """ SlicedLowLevelWCS Transformation This transformation has 2 pixel and 2 world dimensions Array shape (Numpy order): (30, 10) Pixel Dim Axis Name Data size Bounds 0 None 10 (-1, 11) 1 None 30 (5, 15) World Dim Axis Name Physical Type Units 0 Latitude pos.galactic.lat deg 1 Longitude pos.galactic.lon deg Correlation between pixel and world axes: Pixel Dim World Dim 0 1 0 yes yes 1 yes yes """ def test_spectral_slice(): wcs = SlicedLowLevelWCS(WCS_SPECTRAL_CUBE, [slice(None), 10]) assert wcs.pixel_n_dim == 2 assert wcs.world_n_dim == 2 assert wcs.array_shape == (30, 10) assert wcs.pixel_shape == (10, 30) assert wcs.world_axis_physical_types == ['pos.galactic.lat', 'pos.galactic.lon'] assert wcs.world_axis_units == ['deg', 'deg'] assert wcs.pixel_axis_names == ['', ''] assert wcs.world_axis_names == ['Latitude', 'Longitude'] assert_equal(wcs.axis_correlation_matrix, [[True, True], [True, True]]) assert wcs.world_axis_object_components == [('celestial', 1, 'spherical.lat.degree'), ('celestial', 0, 'spherical.lon.degree')] assert wcs.world_axis_object_classes['celestial'][0] is SkyCoord assert wcs.world_axis_object_classes['celestial'][1] == () assert isinstance(wcs.world_axis_object_classes['celestial'][2]['frame'], Galactic) assert wcs.world_axis_object_classes['celestial'][2]['unit'] is u.deg assert_allclose(wcs.pixel_to_world_values(29, 44), (10, 25)) assert_allclose(wcs.array_index_to_world_values(44, 29), (10, 25)) assert_allclose(wcs.world_to_pixel_values(10, 25), (29., 44.)) assert_equal(wcs.world_to_array_index_values(10, 25), (44, 29)) assert_equal(wcs.pixel_bounds, [(-1, 11), (5, 15)]) assert str(wcs) == EXPECTED_SPECTRAL_SLICE_REPR.strip() assert EXPECTED_SPECTRAL_SLICE_REPR.strip() in repr(wcs) EXPECTED_SPECTRAL_RANGE_REPR = """ SlicedLowLevelWCS Transformation This transformation has 3 pixel and 3 world dimensions Array shape (Numpy order): (30, 6, 10) Pixel Dim Axis Name Data size Bounds 0 None 10 (-1, 11) 1 None 6 (-6, 14) 2 None 30 (5, 15) World Dim Axis Name Physical Type Units 0 Latitude pos.galactic.lat deg 1 Frequency em.freq Hz 2 Longitude pos.galactic.lon deg Correlation between pixel and world axes: Pixel Dim World Dim 0 1 2 0 yes no yes 1 no yes no 2 yes no yes """ def test_spectral_range(): wcs = SlicedLowLevelWCS(WCS_SPECTRAL_CUBE, [slice(None), slice(4, 10)]) assert wcs.pixel_n_dim == 3 assert wcs.world_n_dim == 3 assert wcs.array_shape == (30, 6, 10) assert wcs.pixel_shape == (10, 6, 30) assert wcs.world_axis_physical_types == ['pos.galactic.lat', 'em.freq', 'pos.galactic.lon'] assert wcs.world_axis_units == ['deg', 'Hz', 'deg'] assert wcs.pixel_axis_names == ['', '', ''] assert wcs.world_axis_names == ['Latitude', 'Frequency', 'Longitude'] assert_equal(wcs.axis_correlation_matrix, [[True, False, True], [False, True, False], [True, False, True]]) assert len(wcs.world_axis_object_components) == 3 assert wcs.world_axis_object_components[0] == ('celestial', 1, 'spherical.lat.degree') assert wcs.world_axis_object_components[1][:2] == ('spectral', 0) assert wcs.world_axis_object_components[2] == ('celestial', 0, 'spherical.lon.degree') assert wcs.world_axis_object_classes['celestial'][0] is SkyCoord assert wcs.world_axis_object_classes['celestial'][1] == () assert isinstance(wcs.world_axis_object_classes['celestial'][2]['frame'], Galactic) assert wcs.world_axis_object_classes['celestial'][2]['unit'] is u.deg assert wcs.world_axis_object_classes['spectral'][0] is Quantity assert wcs.world_axis_object_classes['spectral'][1] == () assert wcs.world_axis_object_classes['spectral'][2] == {} assert_allclose(wcs.pixel_to_world_values(29, 35, 44), (10, 20, 25)) assert_allclose(wcs.array_index_to_world_values(44, 35, 29), (10, 20, 25)) assert_allclose(wcs.world_to_pixel_values(10, 20, 25), (29., 35., 44.)) assert_equal(wcs.world_to_array_index_values(10, 20, 25), (44, 35, 29)) assert_equal(wcs.pixel_bounds, [(-1, 11), (-6, 14), (5, 15)]) assert str(wcs) == EXPECTED_SPECTRAL_RANGE_REPR.strip() assert EXPECTED_SPECTRAL_RANGE_REPR.strip() in repr(wcs) EXPECTED_CELESTIAL_SLICE_REPR = """ SlicedLowLevelWCS Transformation This transformation has 2 pixel and 3 world dimensions Array shape (Numpy order): (30, 20) Pixel Dim Axis Name Data size Bounds 0 None 20 (-2, 18) 1 None 30 (5, 15) World Dim Axis Name Physical Type Units 0 Latitude pos.galactic.lat deg 1 Frequency em.freq Hz 2 Longitude pos.galactic.lon deg Correlation between pixel and world axes: Pixel Dim World Dim 0 1 0 no yes 1 yes no 2 no yes """ def test_celestial_slice(): wcs = SlicedLowLevelWCS(WCS_SPECTRAL_CUBE, [Ellipsis, 5]) assert wcs.pixel_n_dim == 2 assert wcs.world_n_dim == 3 assert wcs.array_shape == (30, 20) assert wcs.pixel_shape == (20, 30) assert wcs.world_axis_physical_types == ['pos.galactic.lat', 'em.freq', 'pos.galactic.lon'] assert wcs.world_axis_units == ['deg', 'Hz', 'deg'] assert wcs.pixel_axis_names == ['', ''] assert wcs.world_axis_names == ['Latitude', 'Frequency', 'Longitude'] assert_equal(wcs.axis_correlation_matrix, [[False, True], [True, False], [False, True]]) assert len(wcs.world_axis_object_components) == 3 assert wcs.world_axis_object_components[0] == ('celestial', 1, 'spherical.lat.degree') assert wcs.world_axis_object_components[1][:2] == ('spectral', 0) assert wcs.world_axis_object_components[2] == ('celestial', 0, 'spherical.lon.degree') assert wcs.world_axis_object_classes['celestial'][0] is SkyCoord assert wcs.world_axis_object_classes['celestial'][1] == () assert isinstance(wcs.world_axis_object_classes['celestial'][2]['frame'], Galactic) assert wcs.world_axis_object_classes['celestial'][2]['unit'] is u.deg assert wcs.world_axis_object_classes['spectral'][0] is Quantity assert wcs.world_axis_object_classes['spectral'][1] == () assert wcs.world_axis_object_classes['spectral'][2] == {} assert_allclose(wcs.pixel_to_world_values(39, 44), (12.4, 20, 25)) assert_allclose(wcs.array_index_to_world_values(44, 39), (12.4, 20, 25)) assert_allclose(wcs.world_to_pixel_values(12.4, 20, 25), (39., 44.)) assert_equal(wcs.world_to_array_index_values(12.4, 20, 25), (44, 39)) assert_equal(wcs.pixel_bounds, [(-2, 18), (5, 15)]) assert str(wcs) == EXPECTED_CELESTIAL_SLICE_REPR.strip() assert EXPECTED_CELESTIAL_SLICE_REPR.strip() in repr(wcs) EXPECTED_CELESTIAL_RANGE_REPR = """ SlicedLowLevelWCS Transformation This transformation has 3 pixel and 3 world dimensions Array shape (Numpy order): (30, 20, 5) Pixel Dim Axis Name Data size Bounds 0 None 5 (-6, 6) 1 None 20 (-2, 18) 2 None 30 (5, 15) World Dim Axis Name Physical Type Units 0 Latitude pos.galactic.lat deg 1 Frequency em.freq Hz 2 Longitude pos.galactic.lon deg Correlation between pixel and world axes: Pixel Dim World Dim 0 1 2 0 yes no yes 1 no yes no 2 yes no yes """ def test_celestial_range(): wcs = SlicedLowLevelWCS(WCS_SPECTRAL_CUBE, [Ellipsis, slice(5, 10)]) assert wcs.pixel_n_dim == 3 assert wcs.world_n_dim == 3 assert wcs.array_shape == (30, 20, 5) assert wcs.pixel_shape == (5, 20, 30) assert wcs.world_axis_physical_types == ['pos.galactic.lat', 'em.freq', 'pos.galactic.lon'] assert wcs.world_axis_units == ['deg', 'Hz', 'deg'] assert wcs.pixel_axis_names == ['', '', ''] assert wcs.world_axis_names == ['Latitude', 'Frequency', 'Longitude'] assert_equal(wcs.axis_correlation_matrix, [[True, False, True], [False, True, False], [True, False, True]]) assert len(wcs.world_axis_object_components) == 3 assert wcs.world_axis_object_components[0] == ('celestial', 1, 'spherical.lat.degree') assert wcs.world_axis_object_components[1][:2] == ('spectral', 0) assert wcs.world_axis_object_components[2] == ('celestial', 0, 'spherical.lon.degree') assert wcs.world_axis_object_classes['celestial'][0] is SkyCoord assert wcs.world_axis_object_classes['celestial'][1] == () assert isinstance(wcs.world_axis_object_classes['celestial'][2]['frame'], Galactic) assert wcs.world_axis_object_classes['celestial'][2]['unit'] is u.deg assert wcs.world_axis_object_classes['spectral'][0] is Quantity assert wcs.world_axis_object_classes['spectral'][1] == () assert wcs.world_axis_object_classes['spectral'][2] == {} assert_allclose(wcs.pixel_to_world_values(24, 39, 44), (10, 20, 25)) assert_allclose(wcs.array_index_to_world_values(44, 39, 24), (10, 20, 25)) assert_allclose(wcs.world_to_pixel_values(10, 20, 25), (24., 39., 44.)) assert_equal(wcs.world_to_array_index_values(10, 20, 25), (44, 39, 24)) assert_equal(wcs.pixel_bounds, [(-6, 6), (-2, 18), (5, 15)]) assert str(wcs) == EXPECTED_CELESTIAL_RANGE_REPR.strip() assert EXPECTED_CELESTIAL_RANGE_REPR.strip() in repr(wcs) # Now try with a 90 degree rotation with warnings.catch_warnings(): warnings.simplefilter('ignore', VerifyWarning) WCS_SPECTRAL_CUBE_ROT = WCS(Header.fromstring( HEADER_SPECTRAL_CUBE, sep='\n')) WCS_SPECTRAL_CUBE_ROT.wcs.pc = [[0, 0, 1], [0, 1, 0], [1, 0, 0]] WCS_SPECTRAL_CUBE_ROT.wcs.crval[0] = 0 WCS_SPECTRAL_CUBE_ROT.pixel_bounds = [(-1, 11), (-2, 18), (5, 15)] EXPECTED_CELESTIAL_RANGE_ROT_REPR = """ SlicedLowLevelWCS Transformation This transformation has 3 pixel and 3 world dimensions Array shape (Numpy order): (30, 20, 5) Pixel Dim Axis Name Data size Bounds 0 None 5 (-6, 6) 1 None 20 (-2, 18) 2 None 30 (5, 15) World Dim Axis Name Physical Type Units 0 Latitude pos.galactic.lat deg 1 Frequency em.freq Hz 2 Longitude pos.galactic.lon deg Correlation between pixel and world axes: Pixel Dim World Dim 0 1 2 0 yes no yes 1 no yes no 2 yes no yes """ def test_celestial_range_rot(): wcs = SlicedLowLevelWCS(WCS_SPECTRAL_CUBE_ROT, [Ellipsis, slice(5, 10)]) assert wcs.pixel_n_dim == 3 assert wcs.world_n_dim == 3 assert wcs.array_shape == (30, 20, 5) assert wcs.pixel_shape == (5, 20, 30) assert wcs.world_axis_physical_types == ['pos.galactic.lat', 'em.freq', 'pos.galactic.lon'] assert wcs.world_axis_units == ['deg', 'Hz', 'deg'] assert wcs.pixel_axis_names == ['', '', ''] assert wcs.world_axis_names == ['Latitude', 'Frequency', 'Longitude'] assert_equal(wcs.axis_correlation_matrix, [[True, False, True], [False, True, False], [True, False, True]]) assert len(wcs.world_axis_object_components) == 3 assert wcs.world_axis_object_components[0] == ('celestial', 1, 'spherical.lat.degree') assert wcs.world_axis_object_components[1][:2] == ('spectral', 0) assert wcs.world_axis_object_components[2] == ('celestial', 0, 'spherical.lon.degree') assert wcs.world_axis_object_classes['celestial'][0] is SkyCoord assert wcs.world_axis_object_classes['celestial'][1] == () assert isinstance(wcs.world_axis_object_classes['celestial'][2]['frame'], Galactic) assert wcs.world_axis_object_classes['celestial'][2]['unit'] is u.deg assert wcs.world_axis_object_classes['spectral'][0] is Quantity assert wcs.world_axis_object_classes['spectral'][1] == () assert wcs.world_axis_object_classes['spectral'][2] == {} assert_allclose(wcs.pixel_to_world_values(14, 29, 34), (1, 15, 24)) assert_allclose(wcs.array_index_to_world_values(34, 29, 14), (1, 15, 24)) assert_allclose(wcs.world_to_pixel_values(1, 15, 24), (14., 29., 34.)) assert_equal(wcs.world_to_array_index_values(1, 15, 24), (34, 29, 14)) assert_equal(wcs.pixel_bounds, [(-6, 6), (-2, 18), (5, 15)]) assert str(wcs) == EXPECTED_CELESTIAL_RANGE_ROT_REPR.strip() assert EXPECTED_CELESTIAL_RANGE_ROT_REPR.strip() in repr(wcs) HEADER_NO_SHAPE_CUBE = """ NAXIS = 3 CTYPE1 = GLAT-CAR CTYPE2 = FREQ CTYPE3 = GLON-CAR CRVAL1 = 10 CRVAL2 = 20 CRVAL3 = 25 CRPIX1 = 30 CRPIX2 = 40 CRPIX3 = 45 CDELT1 = -0.1 CDELT2 = 0.5 CDELT3 = 0.1 CUNIT1 = deg CUNIT2 = Hz CUNIT3 = deg """ with warnings.catch_warnings(): warnings.simplefilter('ignore', VerifyWarning) WCS_NO_SHAPE_CUBE = WCS(Header.fromstring(HEADER_NO_SHAPE_CUBE, sep='\n')) EXPECTED_NO_SHAPE_REPR = """ SlicedLowLevelWCS Transformation This transformation has 3 pixel and 3 world dimensions Array shape (Numpy order): None Pixel Dim Axis Name Data size Bounds 0 None None None 1 None None None 2 None None None World Dim Axis Name Physical Type Units 0 None pos.galactic.lat deg 1 None em.freq Hz 2 None pos.galactic.lon deg Correlation between pixel and world axes: Pixel Dim World Dim 0 1 2 0 yes no yes 1 no yes no 2 yes no yes """ def test_no_array_shape(): wcs = SlicedLowLevelWCS(WCS_NO_SHAPE_CUBE, Ellipsis) assert wcs.pixel_n_dim == 3 assert wcs.world_n_dim == 3 assert wcs.array_shape is None assert wcs.pixel_shape is None assert wcs.world_axis_physical_types == ['pos.galactic.lat', 'em.freq', 'pos.galactic.lon'] assert wcs.world_axis_units == ['deg', 'Hz', 'deg'] assert_equal(wcs.axis_correlation_matrix, [[True, False, True], [False, True, False], [True, False, True]]) assert len(wcs.world_axis_object_components) == 3 assert wcs.world_axis_object_components[0] == ('celestial', 1, 'spherical.lat.degree') assert wcs.world_axis_object_components[1][:2] == ('spectral', 0) assert wcs.world_axis_object_components[2] == ('celestial', 0, 'spherical.lon.degree') assert wcs.world_axis_object_classes['celestial'][0] is SkyCoord assert wcs.world_axis_object_classes['celestial'][1] == () assert isinstance(wcs.world_axis_object_classes['celestial'][2]['frame'], Galactic) assert wcs.world_axis_object_classes['celestial'][2]['unit'] is u.deg assert wcs.world_axis_object_classes['spectral'][0] is Quantity assert wcs.world_axis_object_classes['spectral'][1] == () assert wcs.world_axis_object_classes['spectral'][2] == {} assert_allclose(wcs.pixel_to_world_values(29, 39, 44), (10, 20, 25)) assert_allclose(wcs.array_index_to_world_values(44, 39, 29), (10, 20, 25)) assert_allclose(wcs.world_to_pixel_values(10, 20, 25), (29., 39., 44.)) assert_equal(wcs.world_to_array_index_values(10, 20, 25), (44, 39, 29)) assert str(wcs) == EXPECTED_NO_SHAPE_REPR.strip() assert EXPECTED_NO_SHAPE_REPR.strip() in repr(wcs) # Testing the WCS object having some physical types as None/Unknown HEADER_SPECTRAL_CUBE_NONE_TYPES = { 'CTYPE1': 'GLAT-CAR', 'CUNIT1': 'deg', 'CDELT1': -0.1, 'CRPIX1': 30, 'CRVAL1': 10, 'NAXIS1': 10, 'CTYPE2': '', 'CUNIT2': 'Hz', 'CDELT2': 0.5, 'CRPIX2': 40, 'CRVAL2': 20, 'NAXIS2': 20, 'CTYPE3': 'GLON-CAR', 'CUNIT3': 'deg', 'CDELT3': 0.1, 'CRPIX3': 45, 'CRVAL3': 25, 'NAXIS3': 30 } WCS_SPECTRAL_CUBE_NONE_TYPES = WCS(header=HEADER_SPECTRAL_CUBE_NONE_TYPES) WCS_SPECTRAL_CUBE_NONE_TYPES.pixel_bounds = [(-1, 11), (-2, 18), (5, 15)] EXPECTED_ELLIPSIS_REPR_NONE_TYPES = """ SlicedLowLevelWCS Transformation This transformation has 3 pixel and 3 world dimensions Array shape (Numpy order): (30, 20, 10) Pixel Dim Axis Name Data size Bounds 0 None 10 (-1, 11) 1 None 20 (-2, 18) 2 None 30 (5, 15) World Dim Axis Name Physical Type Units 0 None pos.galactic.lat deg 1 None None Hz 2 None pos.galactic.lon deg Correlation between pixel and world axes: Pixel Dim World Dim 0 1 2 0 yes no yes 1 no yes no 2 yes no yes """ def test_ellipsis_none_types(): wcs = SlicedLowLevelWCS(WCS_SPECTRAL_CUBE_NONE_TYPES, Ellipsis) assert wcs.pixel_n_dim == 3 assert wcs.world_n_dim == 3 assert wcs.array_shape == (30, 20, 10) assert wcs.pixel_shape == (10, 20, 30) assert wcs.world_axis_physical_types == ['pos.galactic.lat', None, 'pos.galactic.lon'] assert wcs.world_axis_units == ['deg', 'Hz', 'deg'] assert_equal(wcs.axis_correlation_matrix, [[True, False, True], [False, True, False], [True, False, True]]) assert wcs.world_axis_object_components == [('celestial', 1, 'spherical.lat.degree'), ('world', 0, 'value'), ('celestial', 0, 'spherical.lon.degree')] assert wcs.world_axis_object_classes['celestial'][0] is SkyCoord assert wcs.world_axis_object_classes['celestial'][1] == () assert isinstance(wcs.world_axis_object_classes['celestial'][2]['frame'], Galactic) assert wcs.world_axis_object_classes['celestial'][2]['unit'] is u.deg assert_allclose(wcs.pixel_to_world_values(29, 39, 44), (10, 20, 25)) assert_allclose(wcs.array_index_to_world_values(44, 39, 29), (10, 20, 25)) assert_allclose(wcs.world_to_pixel_values(10, 20, 25), (29., 39., 44.)) assert_equal(wcs.world_to_array_index_values(10, 20, 25), (44, 39, 29)) assert_equal(wcs.pixel_bounds, [(-1, 11), (-2, 18), (5, 15)]) assert str(wcs) == EXPECTED_ELLIPSIS_REPR_NONE_TYPES.strip() assert EXPECTED_ELLIPSIS_REPR_NONE_TYPES.strip() in repr(wcs) CASES = [(slice(None), slice(None), slice(None)), (slice(None), slice(3, None), slice(3, None)), (slice(None), slice(None, 16), slice(None, 16)), (slice(None), slice(3, 16), slice(3, 16)), (slice(2, None), slice(None), slice(2, None)), (slice(2, None), slice(3, None), slice(5, None)), (slice(2, None), slice(None, 16), slice(2, 18)), (slice(2, None), slice(3, 16), slice(5, 18)), (slice(None, 10), slice(None), slice(None, 10)), (slice(None, 10), slice(3, None), slice(3, 10)), (slice(None, 10), slice(None, 16), slice(None, 10)), (slice(None, 10), slice(3, 16), slice(3, 10)), (slice(2, 10), slice(None), slice(2, 10)), (slice(2, 10), slice(3, None), slice(5, 10)), (slice(2, 10), slice(None, 16), slice(2, 10)), (slice(2, 10), slice(3, 16), slice(5, 10)), (slice(None), 3, 3), (slice(2, None), 3, 5), (slice(None, 10), 3, 3), (slice(2, 10), 3, 5)] @pytest.mark.parametrize(('slice1', 'slice2', 'expected'), CASES) def test_combine_slices(slice1, slice2, expected): assert combine_slices(slice1, slice2) == expected def test_nested_slicing(): # Make sure that if we call slicing several times, the result is the same # as calling the slicing once with the final slice settings. wcs = WCS_SPECTRAL_CUBE sub1 = SlicedLowLevelWCS( SlicedLowLevelWCS( SlicedLowLevelWCS(wcs, [slice(None), slice(1, 10), slice(None)]), [3, slice(2, None)]), [slice(None), slice(2, 8)]) sub2 = wcs[3, 3:10, 2:8] assert_allclose(sub1.pixel_to_world_values(3, 5), sub2.pixel_to_world_values(3, 5)) assert not isinstance(sub1._wcs, SlicedLowLevelWCS) def test_too_much_slicing(): wcs = WCS_SPECTRAL_CUBE with pytest.raises(ValueError, match='Cannot slice WCS: the resulting WCS ' 'should have at least one pixel and ' 'one world dimension'): wcs[0, 1, 2] HEADER_TIME_1D = """ SIMPLE = T BITPIX = -32 NAXIS = 1 NAXIS1 = 2048 TIMESYS = 'UTC' TREFPOS = 'TOPOCENT' MJDREF = 50002.6 CTYPE1 = 'UTC' CRVAL1 = 5 CUNIT1 = 's' CRPIX1 = 1.0 CDELT1 = 2 OBSGEO-L= -20 OBSGEO-B= -70 OBSGEO-H= 2530 """ @pytest.fixture def header_time_1d(): return Header.fromstring(HEADER_TIME_1D, sep='\n') @pytest.fixture def time_1d_wcs(header_time_1d): with warnings.catch_warnings(): warnings.simplefilter('ignore', FITSFixedWarning) return WCS(header_time_1d) def test_1d_sliced_low_level(time_1d_wcs): sll = SlicedLowLevelWCS(time_1d_wcs, np.s_[10:20]) world = sll.pixel_to_world_values([1, 2]) assert isinstance(world, np.ndarray) assert np.allclose(world, [27, 29]) def validate_info_dict(result, expected): result_value = result.pop("value") expected_value = expected.pop("value") np.testing.assert_allclose(result_value, expected_value) assert result == expected def test_dropped_dimensions(): wcs = WCS_SPECTRAL_CUBE sub = SlicedLowLevelWCS(wcs, np.s_[:, :, :]) assert sub.dropped_world_dimensions == {} sub = SlicedLowLevelWCS(wcs, np.s_[:, 2:5, :]) assert sub.dropped_world_dimensions == {} sub = SlicedLowLevelWCS(wcs, np.s_[:, 0]) waocomp =sub.dropped_world_dimensions.pop("world_axis_object_components") assert len(waocomp) == 1 and waocomp[0][0] == "spectral" and waocomp[0][1] == 0 waocls = sub.dropped_world_dimensions.pop("world_axis_object_classes") assert len(waocls) == 1 and "spectral" in waocls and waocls["spectral"][0] == u.Quantity validate_info_dict(sub.dropped_world_dimensions, { "value": [0.5], "world_axis_physical_types": ["em.freq"], "world_axis_names": ["Frequency"], "world_axis_units": ["Hz"], "serialized_classes": False, }) sub = SlicedLowLevelWCS(wcs, np.s_[:, 0, 0]) waocomp =sub.dropped_world_dimensions.pop("world_axis_object_components") assert len(waocomp) == 1 and waocomp[0][0] == "spectral" and waocomp[0][1] == 0 waocls = sub.dropped_world_dimensions.pop("world_axis_object_classes") assert len(waocls) == 1 and "spectral" in waocls and waocls["spectral"][0] == u.Quantity validate_info_dict(sub.dropped_world_dimensions, { "value": [0.5], "world_axis_physical_types": ["em.freq"], "world_axis_names": ["Frequency"], "world_axis_units": ["Hz"], "serialized_classes": False, }) sub = SlicedLowLevelWCS(wcs, np.s_[0, :, 0]) dwd = sub.dropped_world_dimensions wao_classes = dwd.pop("world_axis_object_classes") validate_info_dict(dwd, { "value": [12.86995801, 20.49217541], "world_axis_physical_types": ["pos.galactic.lat", "pos.galactic.lon"], "world_axis_names": ["Latitude", "Longitude"], "world_axis_units": ["deg", "deg"], "serialized_classes": False, "world_axis_object_components": [('celestial', 1, 'spherical.lat.degree'), ('celestial', 0, 'spherical.lon.degree')], }) assert wao_classes['celestial'][0] is SkyCoord assert wao_classes['celestial'][1] == () assert isinstance(wao_classes['celestial'][2]['frame'], Galactic) assert wao_classes['celestial'][2]['unit'] is u.deg sub = SlicedLowLevelWCS(wcs, np.s_[5, :5, 12]) dwd = sub.dropped_world_dimensions wao_classes = dwd.pop("world_axis_object_classes") validate_info_dict(dwd, { "value": [11.67648267, 21.01921192], "world_axis_physical_types": ["pos.galactic.lat", "pos.galactic.lon"], "world_axis_names": ["Latitude", "Longitude"], "world_axis_units": ["deg", "deg"], "serialized_classes": False, "world_axis_object_components": [('celestial', 1, 'spherical.lat.degree'), ('celestial', 0, 'spherical.lon.degree')], }) assert wao_classes['celestial'][0] is SkyCoord assert wao_classes['celestial'][1] == () assert isinstance(wao_classes['celestial'][2]['frame'], Galactic) assert wao_classes['celestial'][2]['unit'] is u.deg def test_dropped_dimensions_4d(cube_4d_fitswcs): sub = SlicedLowLevelWCS(cube_4d_fitswcs, np.s_[:, 12, 5, 5]) dwd = sub.dropped_world_dimensions wao_classes = dwd.pop("world_axis_object_classes") wao_components = dwd.pop("world_axis_object_components") validate_info_dict(dwd, { "value": [4.e+00, -2.e+00, 1.e+10], "world_axis_physical_types": ["pos.eq.ra", "pos.eq.dec", "em.freq"], "world_axis_names": ['Right Ascension', 'Declination', 'Frequency'], "world_axis_units": ["deg", "deg", "Hz"], "serialized_classes": False, }) assert wao_classes['celestial'][0] is SkyCoord assert wao_classes['celestial'][1] == () assert isinstance(wao_classes['celestial'][2]['frame'], ICRS) assert wao_classes['celestial'][2]['unit'] is u.deg assert wao_classes['spectral'][0:3] == (u.Quantity, (), {}) assert wao_components[0] == ('celestial', 0, 'spherical.lon.degree') assert wao_components[1] == ('celestial', 1, 'spherical.lat.degree') assert wao_components[2][0:2] == ('spectral', 0) sub = SlicedLowLevelWCS(cube_4d_fitswcs, np.s_[12, 12]) dwd = sub.dropped_world_dimensions wao_classes = dwd.pop("world_axis_object_classes") wao_components = dwd.pop("world_axis_object_components") validate_info_dict(dwd, { "value": [1.e+10, 5.e+00], "world_axis_physical_types": ["em.freq", "time"], "world_axis_names": ["Frequency", "Time"], "world_axis_units": ["Hz", "s"], "serialized_classes": False, }) assert wao_components[0][0:2] == ('spectral', 0) assert wao_components[1][0] == 'time' assert wao_components[1][1] == 0 assert wao_classes['spectral'][0:3] == (u.Quantity, (), {}) assert wao_classes['time'][0:3] == (Time, (), {}) def test_pixel_to_world_values_different_int_types(): int_sliced = SlicedLowLevelWCS(WCS_SPECTRAL_CUBE, np.s_[:, 0, :]) np64_sliced = SlicedLowLevelWCS(WCS_SPECTRAL_CUBE, np.s_[:, np.int64(0), :]) pixel_arrays = ([0, 1], [0, 1]) for int_coord, np64_coord in zip(int_sliced.pixel_to_world_values(*pixel_arrays), np64_sliced.pixel_to_world_values(*pixel_arrays)): assert all(int_coord == np64_coord)
dc09edaf43873d8820dc1e84950eec7c0ca7330a3de489db2bc0bd79787132ce
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest import numpy as np from astropy.time import Time, TimeDelta from astropy.units.quantity_helper.function_helpers import ARRAY_FUNCTION_ENABLED class TestFunctionsTime: def setup_class(cls): cls.t = Time(50000, np.arange(8).reshape(4, 2), format='mjd', scale='tai') def check(self, func, cls=None, scale=None, format=None, *args, **kwargs): if cls is None: cls = self.t.__class__ if scale is None: scale = self.t.scale if format is None: format = self.t.format out = func(self.t, *args, **kwargs) jd1 = func(self.t.jd1, *args, **kwargs) jd2 = func(self.t.jd2, *args, **kwargs) expected = cls(jd1, jd2, format=format, scale=scale) if isinstance(out, np.ndarray): expected = np.array(expected) assert np.all(out == expected) @pytest.mark.parametrize('axis', (0, 1)) def test_diff(self, axis): self.check(np.diff, axis=axis, cls=TimeDelta, format='jd') class TestFunctionsTimeDelta(TestFunctionsTime): def setup_class(cls): cls.t = TimeDelta(np.arange(8).reshape(4, 2), format='jd', scale='tai') @pytest.mark.parametrize('axis', (0, 1, None)) @pytest.mark.parametrize('func', (np.sum, np.mean, np.median)) def test_sum_like(self, func, axis): self.check(func, axis=axis) @pytest.mark.xfail(not ARRAY_FUNCTION_ENABLED, reason="Needs __array_function__ support") @pytest.mark.parametrize('attribute', ['shape', 'ndim', 'size']) @pytest.mark.parametrize('t', [ Time('2001-02-03T04:05:06'), Time(50000, np.arange(8).reshape(4, 2), format='mjd', scale='tai'), TimeDelta(100, format='jd')]) def test_shape_attribute_functions(t, attribute): # Regression test for # https://github.com/astropy/astropy/issues/8610#issuecomment-736855217 function = getattr(np, attribute) result = function(t) assert result == getattr(t, attribute)
5f12db6759d17501442d5ce9fbcf029f423b86d254d0bbaaace7a34a19557f0b
# Licensed under a 3-clause BSD style license - see LICENSE.rst import functools import itertools import operator from decimal import Decimal from datetime import timedelta import pytest import numpy as np from astropy.time import ( Time, TimeDelta, OperandTypeError, ScaleValueError, TIME_SCALES, STANDARD_TIME_SCALES, TIME_DELTA_SCALES, TimeDeltaMissingUnitWarning, ) from astropy.utils import iers from astropy import units as u from astropy.table import Table allclose_jd = functools.partial(np.allclose, rtol=2. ** -52, atol=0) allclose_jd2 = functools.partial(np.allclose, rtol=2. ** -52, atol=2. ** -52) # 20 ps atol allclose_sec = functools.partial(np.allclose, rtol=2. ** -52, atol=2. ** -52 * 24 * 3600) # 20 ps atol orig_auto_download = iers.conf.auto_download def setup_module(module): """Use offline IERS table only.""" iers.conf.auto_download = False def teardown_module(module): """Restore original setting.""" iers.conf.auto_download = orig_auto_download class TestTimeDelta: """Test TimeDelta class""" def setup(self): self.t = Time('2010-01-01', scale='utc') self.t2 = Time('2010-01-02 00:00:01', scale='utc') self.t3 = Time('2010-01-03 01:02:03', scale='utc', precision=9, in_subfmt='date_hms', out_subfmt='date_hm', location=(-75. * u.degree, 30. * u.degree, 500 * u.m)) self.t4 = Time('2010-01-01', scale='local') self.dt = TimeDelta(100.0, format='sec') self.dt_array = TimeDelta(np.arange(100, 1000, 100), format='sec') def test_sub(self): # time - time dt = self.t2 - self.t assert (repr(dt).startswith("<TimeDelta object: scale='tai' " "format='jd' value=1.00001157407")) assert allclose_jd(dt.jd, 86401.0 / 86400.0) assert allclose_sec(dt.sec, 86401.0) # time - delta_time t = self.t2 - dt assert t.iso == self.t.iso # delta_time - delta_time dt2 = dt - self.dt assert allclose_sec(dt2.sec, 86301.0) # delta_time - time with pytest.raises(OperandTypeError): dt - self.t def test_add(self): # time + time with pytest.raises(OperandTypeError): self.t2 + self.t # time + delta_time dt = self.t2 - self.t t2 = self.t + dt assert t2.iso == self.t2.iso # delta_time + delta_time dt2 = dt + self.dt assert allclose_sec(dt2.sec, 86501.0) # delta_time + time dt = self.t2 - self.t t2 = dt + self.t assert t2.iso == self.t2.iso def test_add_vector(self): """Check time arithmetic as well as properly keeping track of whether a time is a scalar or a vector""" t = Time(0.0, format='mjd', scale='tai') t2 = Time([0.0, 1.0], format='mjd', scale='tai') dt = TimeDelta(100.0, format='jd') dt2 = TimeDelta([100.0, 200.0], format='jd') out = t + dt assert allclose_jd(out.mjd, 100.0) assert out.isscalar out = t + dt2 assert allclose_jd(out.mjd, [100.0, 200.0]) assert not out.isscalar out = t2 + dt assert allclose_jd(out.mjd, [100.0, 101.0]) assert not out.isscalar out = dt + dt assert allclose_jd(out.jd, 200.0) assert out.isscalar out = dt + dt2 assert allclose_jd(out.jd, [200.0, 300.0]) assert not out.isscalar # Reverse the argument order out = dt + t assert allclose_jd(out.mjd, 100.0) assert out.isscalar out = dt2 + t assert allclose_jd(out.mjd, [100.0, 200.0]) assert not out.isscalar out = dt + t2 assert allclose_jd(out.mjd, [100.0, 101.0]) assert not out.isscalar out = dt2 + dt assert allclose_jd(out.jd, [200.0, 300.0]) assert not out.isscalar def test_sub_vector(self): """Check time arithmetic as well as properly keeping track of whether a time is a scalar or a vector""" t = Time(0.0, format='mjd', scale='tai') t2 = Time([0.0, 1.0], format='mjd', scale='tai') dt = TimeDelta(100.0, format='jd') dt2 = TimeDelta([100.0, 200.0], format='jd') out = t - dt assert allclose_jd(out.mjd, -100.0) assert out.isscalar out = t - dt2 assert allclose_jd(out.mjd, [-100.0, -200.0]) assert not out.isscalar out = t2 - dt assert allclose_jd(out.mjd, [-100.0, -99.0]) assert not out.isscalar out = dt - dt assert allclose_jd(out.jd, 0.0) assert out.isscalar out = dt - dt2 assert allclose_jd(out.jd, [0.0, -100.0]) assert not out.isscalar @pytest.mark.parametrize('values', [(2455197.5, 2455198.5), ([2455197.5], [2455198.5])]) def test_copy_timedelta(self, values): """Test copying the values of a TimeDelta object by passing it into the Time initializer. """ val1, val2 = values t = Time(val1, format='jd', scale='utc') t2 = Time(val2, format='jd', scale='utc') dt = t2 - t dt2 = TimeDelta(dt, copy=False) assert np.all(dt.jd == dt2.jd) assert dt._time.jd1 is dt2._time.jd1 assert dt._time.jd2 is dt2._time.jd2 dt2 = TimeDelta(dt, copy=True) assert np.all(dt.jd == dt2.jd) assert dt._time.jd1 is not dt2._time.jd1 assert dt._time.jd2 is not dt2._time.jd2 # Include initializers dt2 = TimeDelta(dt, format='sec') assert allclose_sec(dt2.value, 86400.0) def test_neg_abs(self): for dt in (self.dt, self.dt_array): dt2 = -dt assert np.all(dt2.jd == -dt.jd) dt3 = abs(dt) assert np.all(dt3.jd == dt.jd) dt4 = abs(dt2) assert np.all(dt4.jd == dt.jd) def test_mul_div(self): for dt in (self.dt, self.dt_array): dt2 = dt + dt + dt dt3 = 3. * dt assert allclose_jd(dt2.jd, dt3.jd) dt4 = dt3 / 3. assert allclose_jd(dt4.jd, dt.jd) dt5 = self.dt * np.arange(3) assert dt5[0].jd == 0. assert dt5[-1].jd == (self.dt + self.dt).jd dt6 = self.dt * [0, 1, 2] assert np.all(dt6.jd == dt5.jd) with pytest.raises(OperandTypeError): self.dt * self.t with pytest.raises(TypeError): self.dt * object() def test_keep_properties(self): # closes #1924 (partially) dt = TimeDelta(1000., format='sec') for t in (self.t, self.t3): ta = t + dt assert ta.location is t.location assert ta.precision == t.precision assert ta.in_subfmt == t.in_subfmt assert ta.out_subfmt == t.out_subfmt tr = dt + t assert tr.location is t.location assert tr.precision == t.precision assert tr.in_subfmt == t.in_subfmt assert tr.out_subfmt == t.out_subfmt ts = t - dt assert ts.location is t.location assert ts.precision == t.precision assert ts.in_subfmt == t.in_subfmt assert ts.out_subfmt == t.out_subfmt t_tdb = self.t.tdb assert hasattr(t_tdb, '_delta_tdb_tt') assert not hasattr(t_tdb, '_delta_ut1_utc') t_tdb_ut1 = t_tdb.ut1 assert hasattr(t_tdb_ut1, '_delta_tdb_tt') assert hasattr(t_tdb_ut1, '_delta_ut1_utc') t_tdb_ut1_utc = t_tdb_ut1.utc assert hasattr(t_tdb_ut1_utc, '_delta_tdb_tt') assert hasattr(t_tdb_ut1_utc, '_delta_ut1_utc') # adding or subtracting some time should remove the delta's # since these are time-dependent and should be recalculated for op in (operator.add, operator.sub): t1 = op(t_tdb, dt) assert not hasattr(t1, '_delta_tdb_tt') assert not hasattr(t1, '_delta_ut1_utc') t2 = op(t_tdb_ut1, dt) assert not hasattr(t2, '_delta_tdb_tt') assert not hasattr(t2, '_delta_ut1_utc') t3 = op(t_tdb_ut1_utc, dt) assert not hasattr(t3, '_delta_tdb_tt') assert not hasattr(t3, '_delta_ut1_utc') def test_set_format(self): """ Test basics of setting format attribute. """ dt = TimeDelta(86400.0, format='sec') assert dt.value == 86400.0 assert dt.format == 'sec' dt.format = 'jd' assert dt.value == 1.0 assert dt.format == 'jd' dt.format = 'datetime' assert dt.value == timedelta(days=1) assert dt.format == 'datetime' def test_from_non_float(self): dt = TimeDelta('1.000000000000001', format='jd') assert dt != TimeDelta(1.000000000000001, format='jd') # precision loss. assert dt == TimeDelta(1, .000000000000001, format='jd') dt2 = TimeDelta(Decimal('1.000000000000001'), format='jd') assert dt2 == dt def test_to_value(self): dt = TimeDelta(86400.0, format='sec') assert dt.to_value('jd') == 1. assert dt.to_value('jd', 'str') == '1.0' assert dt.to_value('sec', subfmt='str') == '86400.0' with pytest.raises(ValueError, match=("not one of the known formats.*" "failed to parse as a unit")): dt.to_value('julian') with pytest.raises(TypeError, match='missing required format or unit'): dt.to_value() class TestTimeDeltaScales: """Test scale conversion for Time Delta. Go through @taldcroft's list of expected behavior from #1932""" def setup(self): # pick a date that includes a leap second for better testing self.iso_times = ['2012-06-30 12:00:00', '2012-06-30 23:59:59', '2012-07-01 00:00:00', '2012-07-01 12:00:00'] self.t = dict((scale, Time(self.iso_times, scale=scale, precision=9)) for scale in TIME_SCALES) self.dt = dict((scale, self.t[scale] - self.t[scale][0]) for scale in TIME_SCALES) def test_delta_scales_definition(self): for scale in list(TIME_DELTA_SCALES) + [None]: TimeDelta([0., 1., 10.], format='sec', scale=scale) with pytest.raises(ScaleValueError): TimeDelta([0., 1., 10.], format='sec', scale='utc') @pytest.mark.parametrize(('scale1', 'scale2'), list(itertools.product(STANDARD_TIME_SCALES, STANDARD_TIME_SCALES))) def test_standard_scales_for_time_minus_time(self, scale1, scale2): """T(X) - T2(Y) -- does T(X) - T2(Y).X and return dT(X) and T(X) +/- dT(Y) -- does (in essence) (T(X).Y +/- dT(Y)).X I.e., time differences of two times should have the scale of the first time. The one exception is UTC, which returns TAI. There are no standard timescales for which this does not work. """ t1 = self.t[scale1] t2 = self.t[scale2] dt = t1 - t2 if scale1 in TIME_DELTA_SCALES: assert dt.scale == scale1 else: assert scale1 == 'utc' assert dt.scale == 'tai' # now check with delta time; also check reversibility t1_recover_t2_scale = t2 + dt assert t1_recover_t2_scale.scale == scale2 t1_recover = getattr(t1_recover_t2_scale, scale1) assert allclose_jd(t1_recover.jd, t1.jd) t2_recover_t1_scale = t1 - dt assert t2_recover_t1_scale.scale == scale1 t2_recover = getattr(t2_recover_t1_scale, scale2) assert allclose_jd(t2_recover.jd, t2.jd) def test_local_scales_for_time_minus_time(self): """ T1(local) - T2(local) should return dT(local) T1(local) +/- dT(local) or T1(local) +/- Quantity(time-like) should also return T(local) I.e. Tests that time differences of two local scale times should return delta time with local timescale. Furthermore, checks that arithmetic of T(local) with dT(None) or time-like quantity does work. Also tests that subtracting two Time objects, one having local time scale and other having standard time scale should raise TypeError. """ t1 = self.t['local'] t2 = Time('2010-01-01', scale='local') dt = t1 - t2 assert dt.scale == 'local' # now check with delta time t1_recover = t2 + dt assert t1_recover.scale == 'local' assert allclose_jd(t1_recover.jd, t1.jd) # check that dT(None) can be subtracted from T(local) dt2 = TimeDelta([10.], format='sec', scale=None) t3 = t2 - dt2 assert t3.scale == t2.scale # check that time quantity can be subtracted from T(local) q = 10 * u.s assert (t2 - q).value == (t2 - dt2).value # Check that one cannot subtract/add times with a standard scale # from a local one (or vice versa) t1 = self.t['local'] for scale in STANDARD_TIME_SCALES: t2 = self.t[scale] with pytest.raises(TypeError): t1 - t2 with pytest.raises(TypeError): t2 - t1 with pytest.raises(TypeError): t2 - dt with pytest.raises(TypeError): t2 + dt with pytest.raises(TypeError): dt + t2 def test_scales_for_delta_minus_delta(self): """dT(X) +/- dT2(Y) -- Add/substract JDs for dT(X) and dT(Y).X I.e. this will succeed if dT(Y) can be converted to scale X. Returns delta time in scale X """ # geocentric timescales dt_tai = self.dt['tai'] dt_tt = self.dt['tt'] dt0 = dt_tai - dt_tt assert dt0.scale == 'tai' # tai and tt have the same scale, so differences should be the same assert allclose_sec(dt0.sec, 0.) dt_tcg = self.dt['tcg'] dt1 = dt_tai - dt_tcg assert dt1.scale == 'tai' # tai and tcg do not have the same scale, so differences different assert not allclose_sec(dt1.sec, 0.) t_tai_tcg = self.t['tai'].tcg dt_tai_tcg = t_tai_tcg - t_tai_tcg[0] dt2 = dt_tai - dt_tai_tcg assert dt2.scale == 'tai' # but if tcg difference calculated from tai, it should roundtrip assert allclose_sec(dt2.sec, 0.) # check that if we put TCG first, we get a TCG scale back dt3 = dt_tai_tcg - dt_tai assert dt3.scale == 'tcg' assert allclose_sec(dt3.sec, 0.) for scale in 'tdb', 'tcb', 'ut1': with pytest.raises(TypeError): dt_tai - self.dt[scale] # barycentric timescales dt_tcb = self.dt['tcb'] dt_tdb = self.dt['tdb'] dt4 = dt_tcb - dt_tdb assert dt4.scale == 'tcb' assert not allclose_sec(dt1.sec, 0.) t_tcb_tdb = self.t['tcb'].tdb dt_tcb_tdb = t_tcb_tdb - t_tcb_tdb[0] dt5 = dt_tcb - dt_tcb_tdb assert dt5.scale == 'tcb' assert allclose_sec(dt5.sec, 0.) for scale in 'utc', 'tai', 'tt', 'tcg', 'ut1': with pytest.raises(TypeError): dt_tcb - self.dt[scale] # rotational timescale dt_ut1 = self.dt['ut1'] dt5 = dt_ut1 - dt_ut1[-1] assert dt5.scale == 'ut1' assert dt5[-1].sec == 0. for scale in 'utc', 'tai', 'tt', 'tcg', 'tcb', 'tdb': with pytest.raises(TypeError): dt_ut1 - self.dt[scale] # local time scale dt_local = self.dt['local'] dt6 = dt_local - dt_local[-1] assert dt6.scale == 'local' assert dt6[-1].sec == 0. for scale in 'utc', 'tai', 'tt', 'tcg', 'tcb', 'tdb', 'ut1': with pytest.raises(TypeError): dt_local - self.dt[scale] @pytest.mark.parametrize( ('scale', 'op'), list(itertools.product(TIME_SCALES, (operator.add, operator.sub)))) def test_scales_for_delta_scale_is_none(self, scale, op): """T(X) +/- dT(None) or T(X) +/- Quantity(time-like) This is always allowed and just adds JDs, i.e., the scale of the TimeDelta or time-like Quantity will be taken to be X. The one exception is again for X=UTC, where TAI is assumed instead, so that a day is always defined as 86400 seconds. """ dt_none = TimeDelta([0., 1., -1., 1000.], format='sec') assert dt_none.scale is None q_time = dt_none.to('s') dt = self.dt[scale] dt1 = op(dt, dt_none) assert dt1.scale == dt.scale assert allclose_jd(dt1.jd, op(dt.jd, dt_none.jd)) dt2 = op(dt_none, dt) assert dt2.scale == dt.scale assert allclose_jd(dt2.jd, op(dt_none.jd, dt.jd)) dt3 = op(q_time, dt) assert dt3.scale == dt.scale assert allclose_jd(dt3.jd, dt2.jd) t = self.t[scale] t1 = op(t, dt_none) assert t1.scale == t.scale assert allclose_jd(t1.jd, op(t.jd, dt_none.jd)) if op is operator.add: t2 = op(dt_none, t) assert t2.scale == t.scale assert allclose_jd(t2.jd, t1.jd) t3 = op(t, q_time) assert t3.scale == t.scale assert allclose_jd(t3.jd, t1.jd) @pytest.mark.parametrize('scale', TIME_SCALES) def test_delta_day_is_86400_seconds(self, scale): """TimeDelta or Quantity holding 1 day always means 24*60*60 seconds This holds true for all timescales but UTC, for which leap-second days are longer or shorter by one second. """ t = self.t[scale] dt_day = TimeDelta(1., format='jd') q_day = dt_day.to('day') dt_day_leap = t[-1] - t[0] # ^ = exclusive or, so either equal and not UTC, or not equal and UTC assert allclose_jd(dt_day_leap.jd, dt_day.jd) ^ (scale == 'utc') t1 = t[0] + dt_day assert allclose_jd(t1.jd, t[-1].jd) ^ (scale == 'utc') t2 = q_day + t[0] assert allclose_jd(t2.jd, t[-1].jd) ^ (scale == 'utc') t3 = t[-1] - dt_day assert allclose_jd(t3.jd, t[0].jd) ^ (scale == 'utc') t4 = t[-1] - q_day assert allclose_jd(t4.jd, t[0].jd) ^ (scale == 'utc') def test_timedelta_setitem(): t = TimeDelta([1, 2, 3] * u.d, format='jd') t[0] = 0.5 assert allclose_jd(t.value, [0.5, 2, 3]) t[1:] = 4.5 assert allclose_jd(t.value, [0.5, 4.5, 4.5]) t[:] = 86400 * u.s assert allclose_jd(t.value, [1, 1, 1]) t[1] = TimeDelta(2, format='jd') assert allclose_jd(t.value, [1, 2, 1]) with pytest.raises(ValueError) as err: t[1] = 1 * u.m assert 'cannot convert value to a compatible TimeDelta' in str(err.value) def test_timedelta_setitem_sec(): t = TimeDelta([1, 2, 3], format='sec') t[0] = 0.5 assert allclose_jd(t.value, [0.5, 2, 3]) t[1:] = 4.5 assert allclose_jd(t.value, [0.5, 4.5, 4.5]) t[:] = 1 * u.day assert allclose_jd(t.value, [86400, 86400, 86400]) t[1] = TimeDelta(2, format='jd') assert allclose_jd(t.value, [86400, 86400 * 2, 86400]) with pytest.raises(ValueError) as err: t[1] = 1 * u.m assert 'cannot convert value to a compatible TimeDelta' in str(err.value) def test_timedelta_mask(): t = TimeDelta([1, 2] * u.d, format='jd') t[1] = np.ma.masked assert np.all(t.mask == [False, True]) assert allclose_jd(t[0].value, 1) assert t.value[1] is np.ma.masked def test_python_timedelta_scalar(): td = timedelta(days=1, seconds=1) td1 = TimeDelta(td, format='datetime') assert td1.sec == 86401.0 td2 = TimeDelta(86401.0, format='sec') assert td2.datetime == td def test_python_timedelta_vector(): td = [[timedelta(days=1), timedelta(days=2)], [timedelta(days=3), timedelta(days=4)]] td1 = TimeDelta(td, format='datetime') assert np.all(td1.jd == [[1, 2], [3, 4]]) td2 = TimeDelta([[1, 2], [3, 4]], format='jd') assert np.all(td2.datetime == td) def test_timedelta_to_datetime(): td = TimeDelta(1, format='jd') assert td.to_datetime() == timedelta(days=1) td2 = TimeDelta([[1, 2], [3, 4]], format='jd') td = [[timedelta(days=1), timedelta(days=2)], [timedelta(days=3), timedelta(days=4)]] assert np.all(td2.to_datetime() == td) def test_insert_timedelta(): tm = TimeDelta([1, 2], format='sec') # Insert a scalar using an auto-parsed string tm2 = tm.insert(1, TimeDelta([10, 20], format='sec')) assert np.all(tm2 == TimeDelta([1, 10, 20, 2], format='sec')) def test_no_units_warning(): with pytest.warns(TimeDeltaMissingUnitWarning): delta = TimeDelta(1) assert delta.to_value(u.day) == 1 with pytest.warns(TimeDeltaMissingUnitWarning): table = Table({"t": [1, 2, 3]}) delta = TimeDelta(table["t"]) assert np.all(delta.to_value(u.day) == [1, 2, 3]) with pytest.warns(TimeDeltaMissingUnitWarning): delta = TimeDelta(np.array([1, 2, 3])) assert np.all(delta.to_value(u.day) == [1, 2, 3]) with pytest.warns(TimeDeltaMissingUnitWarning): t = Time('2012-01-01') + 1 assert t.isot[:10] == '2012-01-02' with pytest.warns(TimeDeltaMissingUnitWarning): comp = TimeDelta([1, 2, 3], format="jd") >= 2 assert np.all(comp == [False, True, True]) with pytest.warns(TimeDeltaMissingUnitWarning): # 2 is also interpreted as days, not seconds assert (TimeDelta(5 * u.s) > 2) is False # with unit is ok assert TimeDelta(1 * u.s).to_value(u.s) == 1 # with format is also ok assert TimeDelta(1, format="sec").to_value(u.s) == 1 assert TimeDelta(1, format="jd").to_value(u.day) == 1 # table column with units table = Table({"t": [1, 2, 3] * u.s}) assert np.all(TimeDelta(table["t"]).to_value(u.s) == [1, 2, 3])
054a32279eaebc40a7f0d8aa0c2faf452d586006dd4422d3a73efc7a2fb1416f
# Licensed under a 3-clause BSD style license - see LICENSE.rst import re import numpy as np import pytest from astropy.time import Time, conf, TimeYearDayTime iso_times = ['2000-02-29', '1981-12-31 12:13', '1981-12-31 12:13:14', '2020-12-31 12:13:14.56'] isot_times = [re.sub(' ', 'T', tm) for tm in iso_times] yday_times = ['2000:060', '1981:365:12:13:14', '1981:365:12:13', '2020:366:12:13:14.56'] # Transpose the array to check that strides are dealt with correctly. yday_array = np.array([['2000:060', '1981:365:12:13:14'], ['1981:365:12:13', '2020:366:12:13:14.56']]).T def test_fast_conf(): # Default is to try C parser and then Python parser. Both fail so we get the # Python message. assert conf.use_fast_parser == 'True' # default with pytest.raises(ValueError, match='Time 2000:0601 does not match yday format'): Time('2000:0601', format='yday') # This is one case where Python parser is different from C parser because the # Python parser has a bug and fails with a trailing ".", but C parser works. Time('2020:150:12:13:14.', format='yday') with conf.set_temp('use_fast_parser', 'force'): Time('2020:150:12:13:14.', format='yday') with conf.set_temp('use_fast_parser', 'False'): with pytest.raises(ValueError, match='could not convert string to float'): Time('2020:150:12:13:14.', format='yday') with conf.set_temp('use_fast_parser', 'False'): assert conf.use_fast_parser == 'False' # Make sure that this is really giving the Python parser with pytest.raises(ValueError, match='Time 2000:0601 does not match yday format'): Time('2000:0601', format='yday') with conf.set_temp('use_fast_parser', 'force'): assert conf.use_fast_parser == 'force' # Make sure that this is really giving the Python parser err = 'fast C time string parser failed: time string ends in middle of component' with pytest.raises(ValueError, match=err): Time('2000:0601', format='yday') @pytest.mark.parametrize('times,format', [(iso_times, 'iso'), (isot_times, 'isot'), (yday_times, 'yday'), (yday_array, 'yday')]) @pytest.mark.parametrize('variant', [0, 1, 2]) def test_fast_matches_python(times, format, variant): if variant == 0: pass # list/array of different values (null terminated strings included) elif variant == 1: times = times[-1] # scalar elif variant == 2: times = [times[-1]] * 2 # list/array of identical values (no null terminations) with conf.set_temp('use_fast_parser', 'False'): tms_py = Time(times, format=format) with conf.set_temp('use_fast_parser', 'force'): tms_c = Time(times, format=format) # Times are binary identical assert np.all(tms_py == tms_c) def test_fast_yday_exceptions(): # msgs = {1: 'time string ends at beginning of component where break is not allowed', # 2: 'time string ends in middle of component', # 3: 'required delimiter character not found', # 4: 'non-digit found where digit (0-9) required', # 5: 'bad day of year (1 <= doy <= 365 or 366 for leap year'} with conf.set_temp('use_fast_parser', 'force'): for times, err in [('2020:150:12', 'time string ends at beginning of component'), ('2020:150:1', 'time string ends in middle of component'), ('2020:150*12:13:14', 'required delimiter character'), ('2020:15*:12:13:14', 'non-digit found where digit'), ('2020:999:12:13:14', 'bad day of year')]: with pytest.raises(ValueError, match=err): Time(times, format='yday') def test_fast_iso_exceptions(): with conf.set_temp('use_fast_parser', 'force'): for times, err in [('2020-10-10 12', 'time string ends at beginning of component'), ('2020-10-10 1', 'time string ends in middle of component'), ('2020*10-10 12:13:14', 'required delimiter character'), ('2020-10-10 *2:13:14', 'non-digit found where digit')]: with pytest.raises(ValueError, match=err): Time(times, format='iso') def test_fast_non_ascii(): with pytest.raises(ValueError, match='input is not pure ASCII'): with conf.set_temp('use_fast_parser', 'force'): Time('2020-01-01 1ᛦ:13:14.4324') def test_fast_subclass(): """Test subclass where use_fast_parser class attribute is not in __dict__""" class TimeYearDayTimeSubClass(TimeYearDayTime): name = 'yday_subclass' # Inheritance works assert hasattr(TimeYearDayTimeSubClass, 'fast_parser_pars') assert 'fast_parser_pars' not in TimeYearDayTimeSubClass.__dict__ try: # For YearDayTime, forcing the fast parser with a bad date will give # "fast C time string parser failed: time string ends in middle of component". # But since YearDayTimeSubClass does not have fast_parser_pars it will # use the Python parser. with pytest.raises(ValueError, match='Time 2000:0601 does not match yday_subclass format'): with conf.set_temp('use_fast_parser', 'force'): Time('2000:0601', format='yday_subclass') finally: del TimeYearDayTimeSubClass._registry['yday_subclass']
5246348189651ed3fe946f227808a3eef68760a1d480b734919b4e90a9ee0d9d
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os import copy import functools import datetime from copy import deepcopy from decimal import Decimal, localcontext import numpy as np import pytest from numpy.testing import assert_allclose import erfa from erfa import ErfaWarning from astropy.utils.exceptions import AstropyDeprecationWarning from astropy.utils import isiterable, iers from astropy.time import (Time, TimeDelta, ScaleValueError, STANDARD_TIME_SCALES, TimeString, TimezoneInfo, TIME_FORMATS) from astropy.coordinates import EarthLocation from astropy import units as u from astropy.table import Column, Table from astropy.utils.compat.optional_deps import HAS_PYTZ # noqa allclose_jd = functools.partial(np.allclose, rtol=np.finfo(float).eps, atol=0) allclose_jd2 = functools.partial(np.allclose, rtol=np.finfo(float).eps, atol=np.finfo(float).eps) # 20 ps atol allclose_sec = functools.partial(np.allclose, rtol=np.finfo(float).eps, atol=np.finfo(float).eps * 24 * 3600) allclose_year = functools.partial(np.allclose, rtol=np.finfo(float).eps, atol=0.) # 14 microsec at current epoch def setup_function(func): func.FORMATS_ORIG = deepcopy(Time.FORMATS) def teardown_function(func): Time.FORMATS.clear() Time.FORMATS.update(func.FORMATS_ORIG) class TestBasic: """Basic tests stemming from initial example and API reference""" def test_simple(self): times = ['1999-01-01 00:00:00.123456789', '2010-01-01 00:00:00'] t = Time(times, format='iso', scale='utc') assert (repr(t) == "<Time object: scale='utc' format='iso' " "value=['1999-01-01 00:00:00.123' '2010-01-01 00:00:00.000']>") assert allclose_jd(t.jd1, np.array([2451180., 2455198.])) assert allclose_jd2(t.jd2, np.array([-0.5 + 1.4288980208333335e-06, -0.50000000e+00])) # Set scale to TAI t = t.tai assert (repr(t) == "<Time object: scale='tai' format='iso' " "value=['1999-01-01 00:00:32.123' '2010-01-01 00:00:34.000']>") assert allclose_jd(t.jd1, np.array([2451180., 2455198.])) assert allclose_jd2(t.jd2, np.array([-0.5 + 0.00037179926839122024, -0.5 + 0.00039351851851851852])) # Get a new ``Time`` object which is referenced to the TT scale # (internal JD1 and JD1 are now with respect to TT scale)""" assert (repr(t.tt) == "<Time object: scale='tt' format='iso' " "value=['1999-01-01 00:01:04.307' '2010-01-01 00:01:06.184']>") # Get the representation of the ``Time`` object in a particular format # (in this case seconds since 1998.0). This returns either a scalar or # array, depending on whether the input was a scalar or array""" assert allclose_sec(t.cxcsec, np.array([31536064.307456788, 378691266.18400002])) def test_different_dimensions(self): """Test scalars, vector, and higher-dimensions""" # scalar val, val1 = 2450000.0, 0.125 t1 = Time(val, val1, format='jd') assert t1.isscalar is True and t1.shape == () # vector val = np.arange(2450000., 2450010.) t2 = Time(val, format='jd') assert t2.isscalar is False and t2.shape == val.shape # explicitly check broadcasting for mixed vector, scalar. val2 = 0. t3 = Time(val, val2, format='jd') assert t3.isscalar is False and t3.shape == val.shape val2 = (np.arange(5.) / 10.).reshape(5, 1) # now see if broadcasting to two-dimensional works t4 = Time(val, val2, format='jd') assert t4.isscalar is False assert t4.shape == np.broadcast(val, val2).shape @pytest.mark.parametrize('format_', Time.FORMATS) def test_empty_value(self, format_): t = Time([], format=format_) assert t.size == 0 assert t.shape == (0,) assert t.format == format_ t_value = t.value assert t_value.size == 0 assert t_value.shape == (0,) t2 = Time(t_value, format=format_) assert t2.size == 0 assert t2.shape == (0,) assert t2.format == format_ t3 = t2.tai assert t3.size == 0 assert t3.shape == (0,) assert t3.format == format_ assert t3.scale == 'tai' @pytest.mark.parametrize('value', [2455197.5, [2455197.5]]) def test_copy_time(self, value): """Test copying the values of a Time object by passing it into the Time initializer. """ t = Time(value, format='jd', scale='utc') t2 = Time(t, copy=False) assert np.all(t.jd - t2.jd == 0) assert np.all((t - t2).jd == 0) assert t._time.jd1 is t2._time.jd1 assert t._time.jd2 is t2._time.jd2 t2 = Time(t, copy=True) assert np.all(t.jd - t2.jd == 0) assert np.all((t - t2).jd == 0) assert t._time.jd1 is not t2._time.jd1 assert t._time.jd2 is not t2._time.jd2 # Include initializers t2 = Time(t, format='iso', scale='tai', precision=1) assert t2.value == '2010-01-01 00:00:34.0' t2 = Time(t, format='iso', scale='tai', out_subfmt='date') assert t2.value == '2010-01-01' def test_getitem(self): """Test that Time objects holding arrays are properly subscriptable, set isscalar as appropriate, and also subscript delta_ut1_utc, etc.""" mjd = np.arange(50000, 50010) t = Time(mjd, format='mjd', scale='utc', location=('45d', '50d')) t1 = t[3] assert t1.isscalar is True assert t1._time.jd1 == t._time.jd1[3] assert t1.location is t.location t1a = Time(mjd[3], format='mjd', scale='utc') assert t1a.isscalar is True assert np.all(t1._time.jd1 == t1a._time.jd1) t1b = Time(t[3]) assert t1b.isscalar is True assert np.all(t1._time.jd1 == t1b._time.jd1) t2 = t[4:6] assert t2.isscalar is False assert np.all(t2._time.jd1 == t._time.jd1[4:6]) assert t2.location is t.location t2a = Time(t[4:6]) assert t2a.isscalar is False assert np.all(t2a._time.jd1 == t._time.jd1[4:6]) t2b = Time([t[4], t[5]]) assert t2b.isscalar is False assert np.all(t2b._time.jd1 == t._time.jd1[4:6]) t2c = Time((t[4], t[5])) assert t2c.isscalar is False assert np.all(t2c._time.jd1 == t._time.jd1[4:6]) t.delta_tdb_tt = np.arange(len(t)) # Explicitly set (not testing .tdb) t3 = t[4:6] assert np.all(t3._delta_tdb_tt == t._delta_tdb_tt[4:6]) t4 = Time(mjd, format='mjd', scale='utc', location=(np.arange(len(mjd)), np.arange(len(mjd)))) t5a = t4[3] assert t5a.location == t4.location[3] assert t5a.location.shape == () t5b = t4[3:4] assert t5b.location.shape == (1,) # Check that indexing a size-1 array returns a scalar location as well; # see gh-10113. t5c = t5b[0] assert t5c.location.shape == () t6 = t4[4:6] assert np.all(t6.location == t4.location[4:6]) # check it is a view # (via ndarray, since quantity setter problematic for structured array) allzeros = np.array((0., 0., 0.), dtype=t4.location.dtype) assert t6.location.view(np.ndarray)[-1] != allzeros assert t4.location.view(np.ndarray)[5] != allzeros t6.location.view(np.ndarray)[-1] = allzeros assert t4.location.view(np.ndarray)[5] == allzeros # Test subscription also works for two-dimensional arrays. frac = np.arange(0., 0.999, 0.2) t7 = Time(mjd[:, np.newaxis] + frac, format='mjd', scale='utc', location=('45d', '50d')) assert t7[0, 0]._time.jd1 == t7._time.jd1[0, 0] assert t7[0, 0].isscalar is True assert np.all(t7[5]._time.jd1 == t7._time.jd1[5]) assert np.all(t7[5]._time.jd2 == t7._time.jd2[5]) assert np.all(t7[:, 2]._time.jd1 == t7._time.jd1[:, 2]) assert np.all(t7[:, 2]._time.jd2 == t7._time.jd2[:, 2]) assert np.all(t7[:, 0]._time.jd1 == t._time.jd1) assert np.all(t7[:, 0]._time.jd2 == t._time.jd2) # Get tdb to check that delta_tdb_tt attribute is sliced properly. t7_tdb = t7.tdb assert t7_tdb[0, 0].delta_tdb_tt == t7_tdb.delta_tdb_tt[0, 0] assert np.all(t7_tdb[5].delta_tdb_tt == t7_tdb.delta_tdb_tt[5]) assert np.all(t7_tdb[:, 2].delta_tdb_tt == t7_tdb.delta_tdb_tt[:, 2]) # Explicitly set delta_tdb_tt attribute. Now it should not be sliced. t7.delta_tdb_tt = 0.1 t7_tdb2 = t7.tdb assert t7_tdb2[0, 0].delta_tdb_tt == 0.1 assert t7_tdb2[5].delta_tdb_tt == 0.1 assert t7_tdb2[:, 2].delta_tdb_tt == 0.1 # Check broadcasting of location. t8 = Time(mjd[:, np.newaxis] + frac, format='mjd', scale='utc', location=(np.arange(len(frac)), np.arange(len(frac)))) assert t8[0, 0].location == t8.location[0, 0] assert np.all(t8[5].location == t8.location[5]) assert np.all(t8[:, 2].location == t8.location[:, 2]) # Finally check empty array. t9 = t[:0] assert t9.isscalar is False assert t9.shape == (0,) assert t9.size == 0 def test_properties(self): """Use properties to convert scales and formats. Note that the UT1 to UTC transformation requires a supplementary value (``delta_ut1_utc``) that can be obtained by interpolating from a table supplied by IERS. This is tested separately.""" t = Time('2010-01-01 00:00:00', format='iso', scale='utc') t.delta_ut1_utc = 0.3341 # Explicitly set one part of the xform assert allclose_jd(t.jd, 2455197.5) assert t.iso == '2010-01-01 00:00:00.000' assert t.tt.iso == '2010-01-01 00:01:06.184' assert t.tai.fits == '2010-01-01T00:00:34.000' assert allclose_jd(t.utc.jd, 2455197.5) assert allclose_jd(t.ut1.jd, 2455197.500003867) assert t.tcg.isot == '2010-01-01T00:01:06.910' assert allclose_sec(t.unix, 1262304000.0) assert allclose_sec(t.cxcsec, 378691266.184) assert allclose_sec(t.gps, 946339215.0) assert t.datetime == datetime.datetime(2010, 1, 1) def test_precision(self): """Set the output precision which is used for some formats. This is also a test of the code that provides a dict for global and instance options.""" t = Time('2010-01-01 00:00:00', format='iso', scale='utc') # Uses initial class-defined precision=3 assert t.iso == '2010-01-01 00:00:00.000' # Set instance precision to 9 t.precision = 9 assert t.iso == '2010-01-01 00:00:00.000000000' assert t.tai.utc.iso == '2010-01-01 00:00:00.000000000' def test_transforms(self): """Transform from UTC to all supported time scales (TAI, TCB, TCG, TDB, TT, UT1, UTC). This requires auxiliary information (latitude and longitude).""" lat = 19.48125 lon = -155.933222 t = Time('2006-01-15 21:24:37.5', format='iso', scale='utc', precision=7, location=(lon, lat)) t.delta_ut1_utc = 0.3341 # Explicitly set one part of the xform assert t.utc.iso == '2006-01-15 21:24:37.5000000' assert t.ut1.iso == '2006-01-15 21:24:37.8341000' assert t.tai.iso == '2006-01-15 21:25:10.5000000' assert t.tt.iso == '2006-01-15 21:25:42.6840000' assert t.tcg.iso == '2006-01-15 21:25:43.3226905' assert t.tdb.iso == '2006-01-15 21:25:42.6843728' assert t.tcb.iso == '2006-01-15 21:25:56.8939523' def test_transforms_no_location(self): """Location should default to geocenter (relevant for TDB, TCB).""" t = Time('2006-01-15 21:24:37.5', format='iso', scale='utc', precision=7) t.delta_ut1_utc = 0.3341 # Explicitly set one part of the xform assert t.utc.iso == '2006-01-15 21:24:37.5000000' assert t.ut1.iso == '2006-01-15 21:24:37.8341000' assert t.tai.iso == '2006-01-15 21:25:10.5000000' assert t.tt.iso == '2006-01-15 21:25:42.6840000' assert t.tcg.iso == '2006-01-15 21:25:43.3226905' assert t.tdb.iso == '2006-01-15 21:25:42.6843725' assert t.tcb.iso == '2006-01-15 21:25:56.8939519' # Check we get the same result t2 = Time('2006-01-15 21:24:37.5', format='iso', scale='utc', location=(0*u.m, 0*u.m, 0*u.m)) assert t == t2 assert t.tdb == t2.tdb def test_location(self): """Check that location creates an EarthLocation object, and that such objects can be used as arguments. """ lat = 19.48125 lon = -155.933222 t = Time(['2006-01-15 21:24:37.5'], format='iso', scale='utc', precision=6, location=(lon, lat)) assert isinstance(t.location, EarthLocation) location = EarthLocation(lon, lat) t2 = Time(['2006-01-15 21:24:37.5'], format='iso', scale='utc', precision=6, location=location) assert isinstance(t2.location, EarthLocation) assert t2.location == t.location t3 = Time(['2006-01-15 21:24:37.5'], format='iso', scale='utc', precision=6, location=(location.x, location.y, location.z)) assert isinstance(t3.location, EarthLocation) assert t3.location == t.location def test_location_array(self): """Check that location arrays are checked for size and used for the corresponding times. Also checks that erfa can handle array-valued locations, and can broadcast these if needed. """ lat = 19.48125 lon = -155.933222 t = Time(['2006-01-15 21:24:37.5'] * 2, format='iso', scale='utc', precision=6, location=(lon, lat)) assert np.all(t.utc.iso == '2006-01-15 21:24:37.500000') assert np.all(t.tdb.iso[0] == '2006-01-15 21:25:42.684373') t2 = Time(['2006-01-15 21:24:37.5'] * 2, format='iso', scale='utc', precision=6, location=(np.array([lon, 0]), np.array([lat, 0]))) assert np.all(t2.utc.iso == '2006-01-15 21:24:37.500000') assert t2.tdb.iso[0] == '2006-01-15 21:25:42.684373' assert t2.tdb.iso[1] != '2006-01-15 21:25:42.684373' with pytest.raises(ValueError): # 1 time, but two locations Time('2006-01-15 21:24:37.5', format='iso', scale='utc', precision=6, location=(np.array([lon, 0]), np.array([lat, 0]))) with pytest.raises(ValueError): # 3 times, but two locations Time(['2006-01-15 21:24:37.5'] * 3, format='iso', scale='utc', precision=6, location=(np.array([lon, 0]), np.array([lat, 0]))) # multidimensional mjd = np.arange(50000., 50008.).reshape(4, 2) t3 = Time(mjd, format='mjd', scale='utc', location=(lon, lat)) assert t3.shape == (4, 2) assert t3.location.shape == () assert t3.tdb.shape == t3.shape t4 = Time(mjd, format='mjd', scale='utc', location=(np.array([lon, 0]), np.array([lat, 0]))) assert t4.shape == (4, 2) assert t4.location.shape == t4.shape assert t4.tdb.shape == t4.shape t5 = Time(mjd, format='mjd', scale='utc', location=(np.array([[lon], [0], [0], [0]]), np.array([[lat], [0], [0], [0]]))) assert t5.shape == (4, 2) assert t5.location.shape == t5.shape assert t5.tdb.shape == t5.shape def test_all_scale_transforms(self): """Test that standard scale transforms work. Does not test correctness, except reversibility [#2074]. Also tests that standard scales can't be converted to local scales""" lat = 19.48125 lon = -155.933222 with iers.conf.set_temp('auto_download', False): for scale1 in STANDARD_TIME_SCALES: t1 = Time('2006-01-15 21:24:37.5', format='iso', scale=scale1, location=(lon, lat)) for scale2 in STANDARD_TIME_SCALES: t2 = getattr(t1, scale2) t21 = getattr(t2, scale1) assert allclose_jd(t21.jd, t1.jd) # test for conversion to local scale scale3 = 'local' with pytest.raises(ScaleValueError): t2 = getattr(t1, scale3) def test_creating_all_formats(self): """Create a time object using each defined format""" Time(2000.5, format='decimalyear') Time(100.0, format='cxcsec') Time(100.0, format='unix') Time(100.0, format='gps') Time(1950.0, format='byear', scale='tai') Time(2000.0, format='jyear', scale='tai') Time('B1950.0', format='byear_str', scale='tai') Time('J2000.0', format='jyear_str', scale='tai') Time('2000-01-01 12:23:34.0', format='iso', scale='tai') Time('2000-01-01 12:23:34.0Z', format='iso', scale='utc') Time('2000-01-01T12:23:34.0', format='isot', scale='tai') Time('2000-01-01T12:23:34.0Z', format='isot', scale='utc') Time('2000-01-01T12:23:34.0', format='fits') Time('2000-01-01T12:23:34.0', format='fits', scale='tdb') Time(2400000.5, 51544.0333981, format='jd', scale='tai') Time(0.0, 51544.0333981, format='mjd', scale='tai') Time('2000:001:12:23:34.0', format='yday', scale='tai') Time('2000:001:12:23:34.0Z', format='yday', scale='utc') dt = datetime.datetime(2000, 1, 2, 3, 4, 5, 123456) Time(dt, format='datetime', scale='tai') Time([dt, dt], format='datetime', scale='tai') dt64 = np.datetime64('2012-06-18T02:00:05.453000000') Time(dt64, format='datetime64', scale='tai') Time([dt64, dt64], format='datetime64', scale='tai') def test_local_format_transforms(self): """ Test transformation of local time to different formats Transformation to formats with reference time should give ScalevalueError """ t = Time('2006-01-15 21:24:37.5', scale='local') assert_allclose(t.jd, 2453751.3921006946, atol=0.001 / 3600. / 24., rtol=0.) assert_allclose(t.mjd, 53750.892100694444, atol=0.001 / 3600. / 24., rtol=0.) assert_allclose(t.decimalyear, 2006.0408002758752, atol=0.001 / 3600. / 24. / 365., rtol=0.) assert t.datetime == datetime.datetime(2006, 1, 15, 21, 24, 37, 500000) assert t.isot == '2006-01-15T21:24:37.500' assert t.yday == '2006:015:21:24:37.500' assert t.fits == '2006-01-15T21:24:37.500' assert_allclose(t.byear, 2006.04217888831, atol=0.001 / 3600. / 24. / 365., rtol=0.) assert_allclose(t.jyear, 2006.0407723496082, atol=0.001 / 3600. / 24. / 365., rtol=0.) assert t.byear_str == 'B2006.042' assert t.jyear_str == 'J2006.041' # epochTimeFormats with pytest.raises(ScaleValueError): t.gps with pytest.raises(ScaleValueError): t.unix with pytest.raises(ScaleValueError): t.cxcsec with pytest.raises(ScaleValueError): t.plot_date def test_datetime(self): """ Test datetime format, including guessing the format from the input type by not providing the format keyword to Time. """ dt = datetime.datetime(2000, 1, 2, 3, 4, 5, 123456) dt2 = datetime.datetime(2001, 1, 1) t = Time(dt, scale='utc', precision=9) assert t.iso == '2000-01-02 03:04:05.123456000' assert t.datetime == dt assert t.value == dt t2 = Time(t.iso, scale='utc') assert t2.datetime == dt t = Time([dt, dt2], scale='utc') assert np.all(t.value == [dt, dt2]) t = Time('2000-01-01 01:01:01.123456789', scale='tai') assert t.datetime == datetime.datetime(2000, 1, 1, 1, 1, 1, 123457) # broadcasting dt3 = (dt + (dt2-dt) * np.arange(12)).reshape(4, 3) t3 = Time(dt3, scale='utc') assert t3.shape == (4, 3) assert t3[2, 1].value == dt3[2, 1] assert t3[2, 1] == Time(dt3[2, 1]) assert np.all(t3.value == dt3) assert np.all(t3[1].value == dt3[1]) assert np.all(t3[:, 2] == Time(dt3[:, 2])) assert Time(t3[2, 0]) == t3[2, 0] def test_datetime64(self): dt64 = np.datetime64('2000-01-02T03:04:05.123456789') dt64_2 = np.datetime64('2000-01-02') t = Time(dt64, scale='utc', precision=9, format='datetime64') assert t.iso == '2000-01-02 03:04:05.123456789' assert t.datetime64 == dt64 assert t.value == dt64 t2 = Time(t.iso, scale='utc') assert t2.datetime64 == dt64 t = Time(dt64_2, scale='utc', precision=3, format='datetime64') assert t.iso == '2000-01-02 00:00:00.000' assert t.datetime64 == dt64_2 assert t.value == dt64_2 t2 = Time(t.iso, scale='utc') assert t2.datetime64 == dt64_2 t = Time([dt64, dt64_2], scale='utc', format='datetime64') assert np.all(t.value == [dt64, dt64_2]) t = Time('2000-01-01 01:01:01.123456789', scale='tai') assert t.datetime64 == np.datetime64('2000-01-01T01:01:01.123456789') # broadcasting dt3 = (dt64 + (dt64_2-dt64) * np.arange(12)).reshape(4, 3) t3 = Time(dt3, scale='utc', format='datetime64') assert t3.shape == (4, 3) assert t3[2, 1].value == dt3[2, 1] assert t3[2, 1] == Time(dt3[2, 1], format='datetime64') assert np.all(t3.value == dt3) assert np.all(t3[1].value == dt3[1]) assert np.all(t3[:, 2] == Time(dt3[:, 2], format='datetime64')) assert Time(t3[2, 0], format='datetime64') == t3[2, 0] def test_epoch_transform(self): """Besselian and julian epoch transforms""" jd = 2457073.05631 t = Time(jd, format='jd', scale='tai', precision=6) assert allclose_year(t.byear, 2015.1365941020817) assert allclose_year(t.jyear, 2015.1349933196439) assert t.byear_str == 'B2015.136594' assert t.jyear_str == 'J2015.134993' t2 = Time(t.byear, format='byear', scale='tai') assert allclose_jd(t2.jd, jd) t2 = Time(t.jyear, format='jyear', scale='tai') assert allclose_jd(t2.jd, jd) t = Time('J2015.134993', scale='tai', precision=6) assert np.allclose(t.jd, jd, rtol=1e-10, atol=0) # J2015.134993 has 10 digit precision assert t.byear_str == 'B2015.136594' def test_input_validation(self): """Wrong input type raises error""" times = [10, 20] with pytest.raises(ValueError): Time(times, format='iso', scale='utc') with pytest.raises(ValueError): Time('2000:001', format='jd', scale='utc') with pytest.raises(ValueError): # unguessable Time([]) with pytest.raises(ValueError): Time([50000.0], ['bad'], format='mjd', scale='tai') with pytest.raises(ValueError): Time(50000.0, 'bad', format='mjd', scale='tai') with pytest.raises(ValueError): Time('2005-08-04T00:01:02.000Z', scale='tai') # regression test against #3396 with pytest.raises(ValueError): Time(np.nan, format='jd', scale='utc') with pytest.raises(ValueError): with pytest.warns(AstropyDeprecationWarning): Time('2000-01-02T03:04:05(TAI)', scale='utc') with pytest.raises(ValueError): Time('2000-01-02T03:04:05(TAI') with pytest.raises(ValueError): Time('2000-01-02T03:04:05(UT(NIST)') def test_utc_leap_sec(self): """Time behaves properly near or in UTC leap second. This uses the 2012-06-30 leap second for testing.""" for year, month, day in ((2012, 6, 30), (2016, 12, 31)): # Start with a day without a leap second and note rollover yyyy_mm = f'{year:04d}-{month:02d}' yyyy_mm_dd = f'{year:04d}-{month:02d}-{day:02d}' with pytest.warns(ErfaWarning): t1 = Time(yyyy_mm + '-01 23:59:60.0', scale='utc') assert t1.iso == yyyy_mm + '-02 00:00:00.000' # Leap second is different t1 = Time(yyyy_mm_dd + ' 23:59:59.900', scale='utc') assert t1.iso == yyyy_mm_dd + ' 23:59:59.900' t1 = Time(yyyy_mm_dd + ' 23:59:60.000', scale='utc') assert t1.iso == yyyy_mm_dd + ' 23:59:60.000' t1 = Time(yyyy_mm_dd + ' 23:59:60.999', scale='utc') assert t1.iso == yyyy_mm_dd + ' 23:59:60.999' if month == 6: yyyy_mm_dd_plus1 = f'{year:04d}-07-01' else: yyyy_mm_dd_plus1 = f'{year + 1:04d}-01-01' with pytest.warns(ErfaWarning): t1 = Time(yyyy_mm_dd + ' 23:59:61.0', scale='utc') assert t1.iso == yyyy_mm_dd_plus1 + ' 00:00:00.000' # Delta time gives 2 seconds here as expected t0 = Time(yyyy_mm_dd + ' 23:59:59', scale='utc') t1 = Time(yyyy_mm_dd_plus1 + ' 00:00:00', scale='utc') assert allclose_sec((t1 - t0).sec, 2.0) def test_init_from_time_objects(self): """Initialize from one or more Time objects""" t1 = Time('2007:001', scale='tai') t2 = Time(['2007-01-02', '2007-01-03'], scale='utc') # Init from a list of Time objects without an explicit scale t3 = Time([t1, t2]) # Test that init appropriately combines a scalar (t1) and list (t2) # and that scale and format are same as first element. assert len(t3) == 3 assert t3.scale == t1.scale assert t3.format == t1.format # t1 format is yday assert np.all(t3.value == np.concatenate([[t1.yday], t2.tai.yday])) # Init from a single Time object without a scale t3 = Time(t1) assert t3.isscalar assert t3.scale == t1.scale assert t3.format == t1.format assert np.all(t3.value == t1.value) # Init from a single Time object with scale specified t3 = Time(t1, scale='utc') assert t3.scale == 'utc' assert np.all(t3.value == t1.utc.value) # Init from a list of Time object with scale specified t3 = Time([t1, t2], scale='tt') assert t3.scale == 'tt' assert t3.format == t1.format # yday assert np.all(t3.value == np.concatenate([[t1.tt.yday], t2.tt.yday])) # OK, how likely is this... but might as well test. mjd = np.arange(50000., 50006.) frac = np.arange(0., 0.999, 0.2) t4 = Time(mjd[:, np.newaxis] + frac, format='mjd', scale='utc') t5 = Time([t4[:2], t4[4:5]]) assert t5.shape == (3, 5) # throw error when deriving local scale time # from non local time scale with pytest.raises(ValueError): Time(t1, scale='local') class TestVal2: """Tests related to val2""" @pytest.mark.parametrize("d", [ dict(val="2001:001", val2="ignored", scale="utc"), dict(val={'year': 2015, 'month': 2, 'day': 3, 'hour': 12, 'minute': 13, 'second': 14.567}, val2="ignored", scale="utc"), dict(val=np.datetime64('2005-02-25'), val2="ignored", scale="utc"), dict(val=datetime.datetime(2000, 1, 2, 12, 0, 0), val2="ignored", scale="utc"), ]) def test_unused_val2_raises(self, d): """Test that providing val2 is for string input lets user know we won't use it""" with pytest.raises(ValueError): Time(**d) def test_val2(self): """Various tests of the val2 input""" t = Time([0.0, 50000.0], [50000.0, 0.0], format='mjd', scale='tai') assert t.mjd[0] == t.mjd[1] assert t.jd[0] == t.jd[1] def test_val_broadcasts_against_val2(self): mjd = np.arange(50000., 50007.) frac = np.arange(0., 0.999, 0.2) t = Time(mjd[:, np.newaxis], frac, format='mjd', scale='utc') assert t.shape == (7, 5) with pytest.raises(ValueError): Time([0.0, 50000.0], [0.0, 1.0, 2.0], format='mjd', scale='tai') def test_broadcast_not_writable(self): val = (2458000 + np.arange(3))[:, None] val2 = np.linspace(0, 1, 4, endpoint=False) t = Time(val=val, val2=val2, format="jd", scale="tai") t_b = Time(val=val + 0 * val2, val2=0 * val + val2, format="jd", scale="tai") t_i = Time(val=57990, val2=0.3, format="jd", scale="tai") t_b[1, 2] = t_i t[1, 2] = t_i assert t_b[1, 2] == t[1, 2], "writing worked" assert t_b[0, 2] == t[0, 2], "broadcasting didn't cause problems" assert t_b[1, 1] == t[1, 1], "broadcasting didn't cause problems" assert np.all(t_b == t), "behaved as expected" def test_broadcast_one_not_writable(self): val = (2458000 + np.arange(3)) val2 = np.arange(1) t = Time(val=val, val2=val2, format="jd", scale="tai") t_b = Time(val=val + 0 * val2, val2=0 * val + val2, format="jd", scale="tai") t_i = Time(val=57990, val2=0.3, format="jd", scale="tai") t_b[1] = t_i t[1] = t_i assert t_b[1] == t[1], "writing worked" assert t_b[0] == t[0], "broadcasting didn't cause problems" assert np.all(t_b == t), "behaved as expected" class TestSubFormat: """Test input and output subformat functionality""" def test_input_subformat(self): """Input subformat selection""" # Heterogeneous input formats with in_subfmt='*' (default) times = ['2000-01-01', '2000-01-01 01:01', '2000-01-01 01:01:01', '2000-01-01 01:01:01.123'] t = Time(times, format='iso', scale='tai') assert np.all(t.iso == np.array(['2000-01-01 00:00:00.000', '2000-01-01 01:01:00.000', '2000-01-01 01:01:01.000', '2000-01-01 01:01:01.123'])) # Heterogeneous input formats with in_subfmt='date_*' times = ['2000-01-01 01:01', '2000-01-01 01:01:01', '2000-01-01 01:01:01.123'] t = Time(times, format='iso', scale='tai', in_subfmt='date_*') assert np.all(t.iso == np.array(['2000-01-01 01:01:00.000', '2000-01-01 01:01:01.000', '2000-01-01 01:01:01.123'])) def test_input_subformat_fail(self): """Failed format matching""" with pytest.raises(ValueError): Time('2000-01-01 01:01', format='iso', scale='tai', in_subfmt='date') def test_bad_input_subformat(self): """Non-existent input subformat""" with pytest.raises(ValueError): Time('2000-01-01 01:01', format='iso', scale='tai', in_subfmt='doesnt exist') def test_output_subformat(self): """Input subformat selection""" # Heterogeneous input formats with in_subfmt='*' (default) times = ['2000-01-01', '2000-01-01 01:01', '2000-01-01 01:01:01', '2000-01-01 01:01:01.123'] t = Time(times, format='iso', scale='tai', out_subfmt='date_hm') assert np.all(t.iso == np.array(['2000-01-01 00:00', '2000-01-01 01:01', '2000-01-01 01:01', '2000-01-01 01:01'])) def test_fits_format(self): """FITS format includes bigger years.""" # Heterogeneous input formats with in_subfmt='*' (default) times = ['2000-01-01', '2000-01-01T01:01:01', '2000-01-01T01:01:01.123'] t = Time(times, format='fits', scale='tai') assert np.all(t.fits == np.array(['2000-01-01T00:00:00.000', '2000-01-01T01:01:01.000', '2000-01-01T01:01:01.123'])) # Explicit long format for output, default scale is UTC. t2 = Time(times, format='fits', out_subfmt='long*') assert np.all(t2.fits == np.array(['+02000-01-01T00:00:00.000', '+02000-01-01T01:01:01.000', '+02000-01-01T01:01:01.123'])) # Implicit long format for output, because of negative year. times[2] = '-00594-01-01' t3 = Time(times, format='fits', scale='tai') assert np.all(t3.fits == np.array(['+02000-01-01T00:00:00.000', '+02000-01-01T01:01:01.000', '-00594-01-01T00:00:00.000'])) # Implicit long format for output, because of large positive year. times[2] = '+10594-01-01' t4 = Time(times, format='fits', scale='tai') assert np.all(t4.fits == np.array(['+02000-01-01T00:00:00.000', '+02000-01-01T01:01:01.000', '+10594-01-01T00:00:00.000'])) def test_yday_format(self): """Year:Day_of_year format""" # Heterogeneous input formats with in_subfmt='*' (default) times = ['2000-12-01', '2001-12-01 01:01:01.123'] t = Time(times, format='iso', scale='tai') t.out_subfmt = 'date_hm' assert np.all(t.yday == np.array(['2000:336:00:00', '2001:335:01:01'])) t.out_subfmt = '*' assert np.all(t.yday == np.array(['2000:336:00:00:00.000', '2001:335:01:01:01.123'])) def test_scale_input(self): """Test for issues related to scale input""" # Check case where required scale is defined by the TimeFormat. # All three should work. t = Time(100.0, format='cxcsec', scale='utc') assert t.scale == 'utc' t = Time(100.0, format='unix', scale='tai') assert t.scale == 'tai' t = Time(100.0, format='gps', scale='utc') assert t.scale == 'utc' # Check that bad scale is caught when format is specified with pytest.raises(ScaleValueError): Time(1950.0, format='byear', scale='bad scale') # Check that bad scale is caught when format is auto-determined with pytest.raises(ScaleValueError): Time('2000:001:00:00:00', scale='bad scale') def test_fits_scale(self): """Test that the previous FITS-string formatting can still be handled but with a DeprecationWarning.""" for inputs in (("2000-01-02(TAI)", "tai"), ("1999-01-01T00:00:00.123(ET(NIST))", "tt"), ("2014-12-12T01:00:44.1(UTC)", "utc")): with pytest.warns(AstropyDeprecationWarning): t = Time(inputs[0]) assert t.scale == inputs[1] # Create Time using normal ISOT syntax and compare with FITS t2 = Time(inputs[0][:inputs[0].index("(")], format="isot", scale=inputs[1]) assert t == t2 # Explicit check that conversions still work despite warning with pytest.warns(AstropyDeprecationWarning): t = Time('1999-01-01T00:00:00.123456789(UTC)') t = t.tai assert t.isot == '1999-01-01T00:00:32.123' with pytest.warns(AstropyDeprecationWarning): t = Time('1999-01-01T00:00:32.123456789(TAI)') t = t.utc assert t.isot == '1999-01-01T00:00:00.123' # Check scale consistency with pytest.warns(AstropyDeprecationWarning): t = Time('1999-01-01T00:00:32.123456789(TAI)', scale="tai") assert t.scale == "tai" with pytest.warns(AstropyDeprecationWarning): t = Time('1999-01-01T00:00:32.123456789(ET)', scale="tt") assert t.scale == "tt" with pytest.raises(ValueError), pytest.warns(AstropyDeprecationWarning): t = Time('1999-01-01T00:00:32.123456789(TAI)', scale="utc") def test_scale_default(self): """Test behavior when no scale is provided""" # These first three are TimeFromEpoch and have an intrinsic time scale t = Time(100.0, format='cxcsec') assert t.scale == 'tt' t = Time(100.0, format='unix') assert t.scale == 'utc' t = Time(100.0, format='gps') assert t.scale == 'tai' for date in ('2000:001', '2000-01-01T00:00:00'): t = Time(date) assert t.scale == 'utc' t = Time(2000.1, format='byear') assert t.scale == 'tt' t = Time('J2000') assert t.scale == 'tt' def test_epoch_times(self): """Test time formats derived from EpochFromTime""" t = Time(0.0, format='cxcsec', scale='tai') assert t.tt.iso == '1998-01-01 00:00:00.000' # Create new time object from this one and change scale, format t2 = Time(t, scale='tt', format='iso') assert t2.value == '1998-01-01 00:00:00.000' # Value take from Chandra.Time.DateTime('2010:001:00:00:00').secs t_cxcsec = 378691266.184 t = Time(t_cxcsec, format='cxcsec', scale='utc') assert allclose_sec(t.value, t_cxcsec) assert allclose_sec(t.cxcsec, t_cxcsec) assert allclose_sec(t.tt.value, t_cxcsec) assert allclose_sec(t.tt.cxcsec, t_cxcsec) assert t.yday == '2010:001:00:00:00.000' t = Time('2010:001:00:00:00.000', scale='utc') assert allclose_sec(t.cxcsec, t_cxcsec) assert allclose_sec(t.tt.cxcsec, t_cxcsec) # Round trip through epoch time for scale in ('utc', 'tt'): t = Time('2000:001', scale=scale) t2 = Time(t.unix, scale=scale, format='unix') assert getattr(t2, scale).iso == '2000-01-01 00:00:00.000' # Test unix time. Values taken from http://en.wikipedia.org/wiki/Unix_time t = Time('2013-05-20 21:18:46', scale='utc') assert allclose_sec(t.unix, 1369084726.0) assert allclose_sec(t.tt.unix, 1369084726.0) # Values from issue #1118 t = Time('2004-09-16T23:59:59', scale='utc') assert allclose_sec(t.unix, 1095379199.0) def test_plot_date(self): """Test the plot_date format. Depending on the situation with matplotlib, this can give different results because the plot date epoch time changed in matplotlib 3.3. This test tries to use the matplotlib date2num function to make the test independent of version, but if matplotlib isn't available then the code (and test) use the pre-3.3 epoch. """ try: from matplotlib.dates import date2num except ImportError: # No matplotlib, in which case this uses the epoch 0000-12-31 # as per matplotlib < 3.3. # Value from: # matplotlib.dates.set_epoch('0000-12-31') # val = matplotlib.dates.date2num('2000-01-01') val = 730120.0 else: val = date2num(datetime.datetime(2000, 1, 1)) t = Time('2000-01-01 00:00:00', scale='utc') assert np.allclose(t.plot_date, val, atol=1e-5, rtol=0) class TestNumericalSubFormat: def test_explicit_example(self): t = Time('54321.000000000001', format='mjd') assert t == Time(54321, 1e-12, format='mjd') assert t.mjd == 54321. # Lost precision! assert t.value == 54321. # Lost precision! assert t.to_value('mjd') == 54321. # Lost precision! assert t.to_value('mjd', subfmt='str') == '54321.000000000001' assert t.to_value('mjd', 'bytes') == b'54321.000000000001' expected_long = np.longdouble(54321.) + np.longdouble(1e-12) # Check we're the same to within the double holding jd2 # (which is less precise than longdouble on arm64). assert np.allclose(t.to_value('mjd', subfmt='long'), expected_long, rtol=0, atol=np.finfo(float).eps) t.out_subfmt = 'str' assert t.value == '54321.000000000001' assert t.to_value('mjd') == 54321. # Lost precision! assert t.mjd == '54321.000000000001' assert t.to_value('mjd', subfmt='bytes') == b'54321.000000000001' assert t.to_value('mjd', subfmt='float') == 54321. # Lost precision! t.out_subfmt = 'long' assert np.allclose(t.value, expected_long, rtol=0., atol=np.finfo(float).eps) assert np.allclose(t.to_value('mjd', subfmt=None), expected_long, rtol=0., atol=np.finfo(float).eps) assert np.allclose(t.mjd, expected_long, rtol=0., atol=np.finfo(float).eps) assert t.to_value('mjd', subfmt='str') == '54321.000000000001' assert t.to_value('mjd', subfmt='float') == 54321. # Lost precision! @pytest.mark.skipif(np.finfo(np.longdouble).eps >= np.finfo(float).eps, reason="long double is the same as float") def test_explicit_longdouble(self): i = 54321 # Create a different long double (which will give a different jd2 # even when long doubles are more precise than Time, as on arm64). f = max(2.**(-np.finfo(np.longdouble).nmant) * 65536, np.finfo(float).eps) mjd_long = np.longdouble(i) + np.longdouble(f) assert mjd_long != i, "longdouble failure!" t = Time(mjd_long, format='mjd') expected = Time(i, f, format='mjd') assert abs(t - expected) <= 20. * u.ps t_float = Time(i + f, format='mjd') assert t_float == Time(i, format='mjd') assert t_float != t assert t.value == 54321. # Lost precision! assert np.allclose(t.to_value('mjd', subfmt='long'), mjd_long, rtol=0., atol=np.finfo(float).eps) t2 = Time(mjd_long, format='mjd', out_subfmt='long') assert np.allclose(t2.value, mjd_long, rtol=0., atol=np.finfo(float).eps) @pytest.mark.skipif(np.finfo(np.longdouble).eps >= np.finfo(float).eps, reason="long double is the same as float") def test_explicit_longdouble_one_val(self): """Ensure either val1 or val2 being longdouble is possible. Regression test for issue gh-10033. """ i = 54321 f = max(2.**(-np.finfo(np.longdouble).nmant) * 65536, np.finfo(float).eps) t1 = Time(i, f, format='mjd') t2 = Time(np.longdouble(i), f, format='mjd') t3 = Time(i, np.longdouble(f), format='mjd') t4 = Time(np.longdouble(i), np.longdouble(f), format='mjd') assert t1 == t2 == t3 == t4 @pytest.mark.skipif(np.finfo(np.longdouble).eps >= np.finfo(float).eps, reason="long double is the same as float") @pytest.mark.parametrize("fmt", ["mjd", "unix", "cxcsec"]) def test_longdouble_for_other_types(self, fmt): t_fmt = getattr(Time(58000, format="mjd"), fmt) # Get regular float t_fmt_long = np.longdouble(t_fmt) # Create a different long double (ensuring it will give a different jd2 # even when long doubles are more precise than Time, as on arm64). atol = np.finfo(float).eps * (1. if fmt == 'mjd' else 24. * 3600.) t_fmt_long2 = t_fmt_long + max( t_fmt_long * np.finfo(np.longdouble).eps * 2, atol) assert t_fmt_long != t_fmt_long2, "longdouble weird!" tm = Time(t_fmt_long, format=fmt) tm2 = Time(t_fmt_long2, format=fmt) assert tm != tm2 tm_long2 = tm2.to_value(fmt, subfmt='long') assert np.allclose(tm_long2, t_fmt_long2, rtol=0., atol=atol) def test_subformat_input(self): s = '54321.01234567890123456789' i, f = s.split('.') # Note, OK only for fraction < 0.5 t = Time(float(i), float('.' + f), format='mjd') t_str = Time(s, format='mjd') t_bytes = Time(s.encode('ascii'), format='mjd') t_decimal = Time(Decimal(s), format='mjd') assert t_str == t assert t_bytes == t assert t_decimal == t @pytest.mark.parametrize('out_subfmt', ('str', 'bytes')) def test_subformat_output(self, out_subfmt): i = 54321 f = np.array([0., 1e-9, 1e-12]) t = Time(i, f, format='mjd', out_subfmt=out_subfmt) t_value = t.value expected = np.array(['54321.0', '54321.000000001', '54321.000000000001'], dtype=out_subfmt) assert np.all(t_value == expected) assert np.all(Time(expected, format='mjd') == t) # Explicit sub-format. t = Time(i, f, format='mjd') t_mjd_subfmt = t.to_value('mjd', subfmt=out_subfmt) assert np.all(t_mjd_subfmt == expected) @pytest.mark.parametrize('fmt,string,val1,val2', [ ('jd', '2451544.5333981', 2451544.5, .0333981), ('decimalyear', '2000.54321', 2000., .54321), ('cxcsec', '100.0123456', 100.0123456, None), ('unix', '100.0123456', 100.0123456, None), ('gps', '100.0123456', 100.0123456, None), ('byear', '1950.1', 1950.1, None), ('jyear', '2000.1', 2000.1, None)]) def test_explicit_string_other_formats(self, fmt, string, val1, val2): t = Time(string, format=fmt) assert t == Time(val1, val2, format=fmt) assert t.to_value(fmt, subfmt='str') == string def test_basic_subformat_setting(self): t = Time('2001', format='jyear', scale='tai') t.format = "mjd" t.out_subfmt = "str" assert t.value.startswith("5") def test_basic_subformat_cache_does_not_crash(self): t = Time('2001', format='jyear', scale='tai') t.to_value('mjd', subfmt='str') assert ('mjd', 'str') in t.cache['format'] t.to_value('mjd', 'str') @pytest.mark.parametrize("fmt", ["jd", "mjd", "cxcsec", "unix", "gps", "jyear"]) def test_decimal_context_does_not_affect_string(self, fmt): t = Time('2001', format='jyear', scale='tai') t.format = fmt with localcontext() as ctx: ctx.prec = 2 t_s_2 = t.to_value(fmt, "str") t2 = Time('2001', format='jyear', scale='tai') t2.format = fmt with localcontext() as ctx: ctx.prec = 40 t2_s_40 = t.to_value(fmt, "str") assert t_s_2 == t2_s_40, "String representation should not depend on Decimal context" def test_decimal_context_caching(self): t = Time(val=58000, val2=1e-14, format='mjd', scale='tai') with localcontext() as ctx: ctx.prec = 2 t_s_2 = t.to_value('mjd', subfmt='decimal') t2 = Time(val=58000, val2=1e-14, format='mjd', scale='tai') with localcontext() as ctx: ctx.prec = 40 t_s_40 = t.to_value('mjd', subfmt='decimal') t2_s_40 = t2.to_value('mjd', subfmt='decimal') assert t_s_2 == t_s_40, "Should be the same but cache might make this automatic" assert t_s_2 == t2_s_40, "Different precision should produce the same results" @pytest.mark.parametrize("f, s, t", [("sec", "long", np.longdouble), ("sec", "decimal", Decimal), ("sec", "str", str)]) def test_timedelta_basic(self, f, s, t): dt = (Time("58000", format="mjd", scale="tai") - Time("58001", format="mjd", scale="tai")) value = dt.to_value(f, s) assert isinstance(value, t) dt.format = f dt.out_subfmt = s assert isinstance(dt.value, t) assert isinstance(dt.to_value(f, None), t) def test_need_format_argument(self): t = Time('J2000') with pytest.raises(TypeError, match="missing.*required.*'format'"): t.to_value() with pytest.raises(ValueError, match='format must be one of'): t.to_value('julian') def test_wrong_in_subfmt(self): with pytest.raises(ValueError, match='not among selected'): Time("58000", format='mjd', in_subfmt='float') with pytest.raises(ValueError, match='not among selected'): Time(np.longdouble(58000), format='mjd', in_subfmt='float') with pytest.raises(ValueError, match='not among selected'): Time(58000., format='mjd', in_subfmt='str') with pytest.raises(ValueError, match='not among selected'): Time(58000., format='mjd', in_subfmt='long') def test_wrong_subfmt(self): t = Time(58000., format='mjd') with pytest.raises(ValueError, match='must match one'): t.to_value('mjd', subfmt='parrot') with pytest.raises(ValueError, match='must match one'): t.out_subfmt = 'parrot' with pytest.raises(ValueError, match='must match one'): t.in_subfmt = 'parrot' def test_not_allowed_subfmt(self): """Test case where format has no defined subfmts""" t = Time('J2000') match = 'subformat not allowed for format jyear_str' with pytest.raises(ValueError, match=match): t.to_value('jyear_str', subfmt='parrot') with pytest.raises(ValueError, match=match): t.out_subfmt = 'parrot' with pytest.raises(ValueError, match=match): Time('J2000', out_subfmt='parrot') with pytest.raises(ValueError, match=match): t.in_subfmt = 'parrot' with pytest.raises(ValueError, match=match): Time('J2000', format='jyear_str', in_subfmt='parrot') def test_switch_to_format_with_no_out_subfmt(self): t = Time('2001-01-01', out_subfmt='date_hm') assert t.out_subfmt == 'date_hm' # Now do an in-place switch to format 'jyear_str' that has no subfmts # where out_subfmt is changed to '*'. t.format = 'jyear_str' assert t.out_subfmt == '*' assert t.value == 'J2001.001' class TestSofaErrors: """Test that erfa status return values are handled correctly""" def test_bad_time(self): iy = np.array([2000], dtype=np.intc) im = np.array([2000], dtype=np.intc) # bad month id = np.array([2000], dtype=np.intc) # bad day with pytest.raises(ValueError): # bad month, fatal error djm0, djm = erfa.cal2jd(iy, im, id) iy[0] = -5000 im[0] = 2 with pytest.raises(ValueError): # bad year, fatal error djm0, djm = erfa.cal2jd(iy, im, id) iy[0] = 2000 with pytest.warns(ErfaWarning, match=r'bad day \(JD computed\)') as w: djm0, djm = erfa.cal2jd(iy, im, id) assert len(w) == 1 assert allclose_jd(djm0, [2400000.5]) assert allclose_jd(djm, [53574.]) class TestCopyReplicate: """Test issues related to copying and replicating data""" def test_immutable_input(self): """Internals are never mutable.""" jds = np.array([2450000.5], dtype=np.double) t = Time(jds, format='jd', scale='tai') assert allclose_jd(t.jd, jds) jds[0] = 2458654 assert not allclose_jd(t.jd, jds) mjds = np.array([50000.0], dtype=np.double) t = Time(mjds, format='mjd', scale='tai') assert allclose_jd(t.jd, [2450000.5]) mjds[0] = 0.0 assert allclose_jd(t.jd, [2450000.5]) def test_replicate(self): """Test replicate method""" t = Time(['2000:001'], format='yday', scale='tai', location=('45d', '45d')) t_yday = t.yday t_loc_x = t.location.x.copy() t2 = t.replicate() assert t.yday == t2.yday assert t.format == t2.format assert t.scale == t2.scale assert t.location == t2.location # This is not allowed publicly, but here we hack the internal time # and location values to show that t and t2 are sharing references. t2._time.jd1 += 100.0 # Need to delete the cached yday attributes (only an issue because # of the internal _time hack). del t.cache del t2.cache assert t.yday == t2.yday assert t.yday != t_yday # prove that it changed t2_loc_x_view = t2.location.x t2_loc_x_view[()] = 0 # use 0 to avoid having to give units assert t2.location.x == t2_loc_x_view assert t.location.x == t2.location.x assert t.location.x != t_loc_x # prove that it changed def test_copy(self): """Test copy method""" t = Time('2000:001', format='yday', scale='tai', location=('45d', '45d')) t_yday = t.yday t_loc_x = t.location.x.copy() t2 = t.copy() assert t.yday == t2.yday # This is not allowed publicly, but here we hack the internal time # and location values to show that t and t2 are not sharing references. t2._time.jd1 += 100.0 # Need to delete the cached yday attributes (only an issue because # of the internal _time hack). del t.cache del t2.cache assert t.yday != t2.yday assert t.yday == t_yday # prove that it did not change t2_loc_x_view = t2.location.x t2_loc_x_view[()] = 0 # use 0 to avoid having to give units assert t2.location.x == t2_loc_x_view assert t.location.x != t2.location.x assert t.location.x == t_loc_x # prove that it changed class TestStardate: """Sync chronometers with Starfleet Command""" def test_iso_to_stardate(self): assert str(Time('2320-01-01', scale='tai').stardate)[:7] == '1368.99' assert str(Time('2330-01-01', scale='tai').stardate)[:8] == '10552.76' assert str(Time('2340-01-01', scale='tai').stardate)[:8] == '19734.02' @pytest.mark.parametrize('dates', [(10000, '2329-05-26 03:02'), (20000, '2340-04-15 19:05'), (30000, '2351-03-07 11:08')]) def test_stardate_to_iso(self, dates): stardate, iso = dates t_star = Time(stardate, format='stardate') t_iso = Time(t_star, format='iso', out_subfmt='date_hm') assert t_iso.value == iso def test_python_builtin_copy(): t = Time('2000:001', format='yday', scale='tai') t2 = copy.copy(t) t3 = copy.deepcopy(t) assert t.jd == t2.jd assert t.jd == t3.jd def test_now(): """ Tests creating a Time object with the `now` class method. """ now = datetime.datetime.utcnow() t = Time.now() assert t.format == 'datetime' assert t.scale == 'utc' dt = t.datetime - now # a datetime.timedelta object # this gives a .1 second margin between the `utcnow` call and the `Time` # initializer, which is really way more generous than necessary - typical # times are more like microseconds. But it seems safer in case some # platforms have slow clock calls or something. assert dt.total_seconds() < 0.1 def test_decimalyear(): t = Time('2001:001', format='yday') assert t.decimalyear == 2001.0 t = Time(2000.0, [0.5, 0.75], format='decimalyear') assert np.all(t.value == [2000.5, 2000.75]) jd0 = Time('2000:001').jd jd1 = Time('2001:001').jd d_jd = jd1 - jd0 assert np.all(t.jd == [jd0 + 0.5 * d_jd, jd0 + 0.75 * d_jd]) def test_fits_year0(): t = Time(1721425.5, format='jd', scale='tai') assert t.fits == '0001-01-01T00:00:00.000' t = Time(1721425.5 - 366., format='jd', scale='tai') assert t.fits == '+00000-01-01T00:00:00.000' t = Time(1721425.5 - 366. - 365., format='jd', scale='tai') assert t.fits == '-00001-01-01T00:00:00.000' def test_fits_year10000(): t = Time(5373484.5, format='jd', scale='tai') assert t.fits == '+10000-01-01T00:00:00.000' t = Time(5373484.5 - 365., format='jd', scale='tai') assert t.fits == '9999-01-01T00:00:00.000' t = Time(5373484.5, -1. / 24. / 3600., format='jd', scale='tai') assert t.fits == '9999-12-31T23:59:59.000' def test_dir(): t = Time('2000:001', format='yday', scale='tai') assert 'utc' in dir(t) def test_time_from_epoch_jds(): """Test that jd1/jd2 in a TimeFromEpoch format is always well-formed: jd1 is an integral value and abs(jd2) <= 0.5. """ # From 1999:001 00:00 to 1999:002 12:00 by a non-round step. This will # catch jd2 == 0 and a case of abs(jd2) == 0.5. cxcsecs = np.linspace(0, 86400 * 1.5, 49) for cxcsec in cxcsecs: t = Time(cxcsec, format='cxcsec') assert np.round(t.jd1) == t.jd1 assert np.abs(t.jd2) <= 0.5 t = Time(cxcsecs, format='cxcsec') assert np.all(np.round(t.jd1) == t.jd1) assert np.all(np.abs(t.jd2) <= 0.5) assert np.any(np.abs(t.jd2) == 0.5) # At least one exactly 0.5 def test_bool(): """Any Time object should evaluate to True unless it is empty [#3520].""" t = Time(np.arange(50000, 50010), format='mjd', scale='utc') assert bool(t) is True assert bool(t[0]) is True assert bool(t[:0]) is False def test_len_size(): """Check length of Time objects and that scalar ones do not have one.""" t = Time(np.arange(50000, 50010), format='mjd', scale='utc') assert len(t) == 10 and t.size == 10 t1 = Time(np.arange(50000, 50010).reshape(2, 5), format='mjd', scale='utc') assert len(t1) == 2 and t1.size == 10 # Can have length 1 or length 0 arrays. t2 = t[:1] assert len(t2) == 1 and t2.size == 1 t3 = t[:0] assert len(t3) == 0 and t3.size == 0 # But cannot get length from scalar. t4 = t[0] with pytest.raises(TypeError) as err: len(t4) # Ensure we're not just getting the old error of # "object of type 'float' has no len()". assert 'Time' in str(err.value) def test_TimeFormat_scale(): """guard against recurrence of #1122, where TimeFormat class looses uses attributes (delta_ut1_utc here), preventing conversion to unix, cxc""" t = Time('1900-01-01', scale='ut1') t.delta_ut1_utc = 0.0 with pytest.warns(ErfaWarning): t.unix assert t.unix == t.utc.unix @pytest.mark.remote_data def test_scale_conversion(monkeypatch): # Check that if we have internet, and downloading is allowed, we # can get conversion to UT1 for the present, since we will download # IERS_A in IERS_Auto. monkeypatch.setattr('astropy.utils.iers.conf.auto_download', True) Time(Time.now().cxcsec, format='cxcsec', scale='ut1') def test_byteorder(): """Ensure that bigendian and little-endian both work (closes #2942)""" mjd = np.array([53000.00, 54000.00]) big_endian = mjd.astype('>f8') little_endian = mjd.astype('<f8') time_mjd = Time(mjd, format='mjd') time_big = Time(big_endian, format='mjd') time_little = Time(little_endian, format='mjd') assert np.all(time_big == time_mjd) assert np.all(time_little == time_mjd) def test_datetime_tzinfo(): """ Test #3160 that time zone info in datetime objects is respected. """ class TZm6(datetime.tzinfo): def utcoffset(self, dt): return datetime.timedelta(hours=-6) d = datetime.datetime(2002, 1, 2, 10, 3, 4, tzinfo=TZm6()) t = Time(d) assert t.value == datetime.datetime(2002, 1, 2, 16, 3, 4) def test_subfmts_regex(): """ Test having a custom subfmts with a regular expression """ class TimeLongYear(TimeString): name = 'longyear' subfmts = (('date', r'(?P<year>[+-]\d{5})-%m-%d', # hybrid '{year:+06d}-{mon:02d}-{day:02d}'),) t = Time('+02000-02-03', format='longyear') assert t.value == '+02000-02-03' assert t.jd == Time('2000-02-03').jd def test_set_format_basic(): """ Test basics of setting format attribute. """ for format, value in (('jd', 2451577.5), ('mjd', 51577.0), ('cxcsec', 65923264.184), # confirmed with Chandra.Time ('datetime', datetime.datetime(2000, 2, 3, 0, 0)), ('iso', '2000-02-03 00:00:00.000')): t = Time('+02000-02-03', format='fits') t0 = t.replicate() t.format = format assert t.value == value # Internal jd1 and jd2 are preserved assert t._time.jd1 is t0._time.jd1 assert t._time.jd2 is t0._time.jd2 def test_unix_tai_format(): t = Time('2020-01-01', scale='utc') assert allclose_sec(t.unix_tai - t.unix, 37.0) t = Time('1970-01-01', scale='utc') assert allclose_sec(t.unix_tai - t.unix, 8 + 8.2e-05) def test_set_format_shares_subfmt(): """ Set format and round trip through a format that shares out_subfmt """ t = Time('+02000-02-03', format='fits', out_subfmt='date_hms', precision=5) tc = t.copy() t.format = 'isot' assert t.precision == 5 assert t.out_subfmt == 'date_hms' assert t.value == '2000-02-03T00:00:00.00000' t.format = 'fits' assert t.value == tc.value assert t.precision == 5 def test_set_format_does_not_share_subfmt(): """ Set format and round trip through a format that does not share out_subfmt """ t = Time('+02000-02-03', format='fits', out_subfmt='longdate') t.format = 'isot' assert t.out_subfmt == '*' # longdate_hms not there, goes to default assert t.value == '2000-02-03T00:00:00.000' t.format = 'fits' assert t.out_subfmt == '*' assert t.value == '2000-02-03T00:00:00.000' # date_hms def test_replicate_value_error(): """ Passing a bad format to replicate should raise ValueError, not KeyError. PR #3857. """ t1 = Time('2007:001', scale='tai') with pytest.raises(ValueError) as err: t1.replicate(format='definitely_not_a_valid_format') assert 'format must be one of' in str(err.value) def test_remove_astropy_time(): """ Make sure that 'astropy_time' format is really gone after #3857. Kind of silly test but just to be sure. """ t1 = Time('2007:001', scale='tai') assert 'astropy_time' not in t1.FORMATS with pytest.raises(ValueError) as err: Time(t1, format='astropy_time') assert 'format must be one of' in str(err.value) def test_isiterable(): """ Ensure that scalar `Time` instances are not reported as iterable by the `isiterable` utility. Regression test for https://github.com/astropy/astropy/issues/4048 """ t1 = Time.now() assert not isiterable(t1) t2 = Time(['1999-01-01 00:00:00.123456789', '2010-01-01 00:00:00'], format='iso', scale='utc') assert isiterable(t2) def test_to_datetime(): tz = TimezoneInfo(utc_offset=-10 * u.hour, tzname='US/Hawaii') # The above lines produces a `datetime.tzinfo` object similar to: # tzinfo = pytz.timezone('US/Hawaii') time = Time('2010-09-03 00:00:00') tz_aware_datetime = time.to_datetime(tz) assert tz_aware_datetime.time() == datetime.time(14, 0) forced_to_astropy_time = Time(tz_aware_datetime) assert tz.tzname(time.datetime) == tz_aware_datetime.tzname() assert time == forced_to_astropy_time # Test non-scalar time inputs: time = Time(['2010-09-03 00:00:00', '2005-09-03 06:00:00', '1990-09-03 06:00:00']) tz_aware_datetime = time.to_datetime(tz) forced_to_astropy_time = Time(tz_aware_datetime) for dt, tz_dt in zip(time.datetime, tz_aware_datetime): assert tz.tzname(dt) == tz_dt.tzname() assert np.all(time == forced_to_astropy_time) with pytest.raises(ValueError, match=r'does not support leap seconds'): Time('2015-06-30 23:59:60.000').to_datetime() @pytest.mark.skipif('not HAS_PYTZ') def test_to_datetime_pytz(): import pytz tz = pytz.timezone('US/Hawaii') time = Time('2010-09-03 00:00:00') tz_aware_datetime = time.to_datetime(tz) forced_to_astropy_time = Time(tz_aware_datetime) assert tz_aware_datetime.time() == datetime.time(14, 0) assert tz.tzname(time.datetime) == tz_aware_datetime.tzname() assert time == forced_to_astropy_time # Test non-scalar time inputs: time = Time(['2010-09-03 00:00:00', '2005-09-03 06:00:00', '1990-09-03 06:00:00']) tz_aware_datetime = time.to_datetime(tz) forced_to_astropy_time = Time(tz_aware_datetime) for dt, tz_dt in zip(time.datetime, tz_aware_datetime): assert tz.tzname(dt) == tz_dt.tzname() assert np.all(time == forced_to_astropy_time) def test_cache(): t = Time('2010-09-03 00:00:00') t2 = Time('2010-09-03 00:00:00') # Time starts out without a cache assert 'cache' not in t._time.__dict__ # Access the iso format and confirm that the cached version is as expected t.iso assert t.cache['format']['iso'] == t2.iso # Access the TAI scale and confirm that the cached version is as expected t.tai assert t.cache['scale']['tai'] == t2.tai # New Time object after scale transform does not have a cache yet assert 'cache' not in t.tt._time.__dict__ # Clear the cache del t.cache assert 'cache' not in t._time.__dict__ # Check accessing the cache creates an empty dictionary assert not t.cache assert 'cache' in t._time.__dict__ def test_epoch_date_jd_is_day_fraction(): """ Ensure that jd1 and jd2 of an epoch Time are respect the (day, fraction) convention (see #6638) """ t0 = Time("J2000", scale="tdb") assert t0.jd1 == 2451545.0 assert t0.jd2 == 0.0 t1 = Time(datetime.datetime(2000, 1, 1, 12, 0, 0), scale="tdb") assert t1.jd1 == 2451545.0 assert t1.jd2 == 0.0 def test_sum_is_equivalent(): """ Ensure that two equal dates defined in different ways behave equally (#6638) """ t0 = Time("J2000", scale="tdb") t1 = Time("2000-01-01 12:00:00", scale="tdb") assert t0 == t1 assert (t0 + 1 * u.second) == (t1 + 1 * u.second) def test_string_valued_columns(): # Columns have a nice shim that translates bytes to string as needed. # Ensure Time can handle these. Use multi-d array just to be sure. times = [[[f'{y:04d}-{m:02d}-{d:02d}' for d in range(1, 3)] for m in range(5, 7)] for y in range(2012, 2014)] cutf32 = Column(times) cbytes = cutf32.astype('S') tutf32 = Time(cutf32) tbytes = Time(cbytes) assert np.all(tutf32 == tbytes) tutf32 = Time(Column(['B1950'])) tbytes = Time(Column([b'B1950'])) assert tutf32 == tbytes # Regression tests for arrays with entries with unequal length. gh-6903. times = Column([b'2012-01-01', b'2012-01-01T00:00:00']) assert np.all(Time(times) == Time(['2012-01-01', '2012-01-01T00:00:00'])) def test_bytes_input(): tstring = '2011-01-02T03:04:05' tbytes = b'2011-01-02T03:04:05' assert tbytes.decode('ascii') == tstring t0 = Time(tstring) t1 = Time(tbytes) assert t1 == t0 tarray = np.array(tbytes) assert tarray.dtype.kind == 'S' t2 = Time(tarray) assert t2 == t0 def test_writeable_flag(): t = Time([1, 2, 3], format='cxcsec') t[1] = 5.0 assert allclose_sec(t[1].value, 5.0) t.writeable = False with pytest.raises(ValueError) as err: t[1] = 5.0 assert 'Time object is read-only. Make a copy()' in str(err.value) with pytest.raises(ValueError) as err: t[:] = 5.0 assert 'Time object is read-only. Make a copy()' in str(err.value) t.writeable = True t[1] = 10.0 assert allclose_sec(t[1].value, 10.0) # Scalar is writeable because it gets boxed into a zero-d array t = Time('2000:001', scale='utc') t[()] = '2000:002' assert t.value.startswith('2000:002') # Transformed attribute is not writeable t = Time(['2000:001', '2000:002'], scale='utc') t2 = t.tt # t2 is read-only now because t.tt is cached with pytest.raises(ValueError) as err: t2[0] = '2005:001' assert 'Time object is read-only. Make a copy()' in str(err.value) def test_setitem_location(): loc = EarthLocation(x=[1, 2] * u.m, y=[3, 4] * u.m, z=[5, 6] * u.m) t = Time([[1, 2], [3, 4]], format='cxcsec', location=loc) # Succeeds because the right hand side makes no implication about # location and just inherits t.location t[0, 0] = 0 assert allclose_sec(t.value, [[0, 2], [3, 4]]) # Fails because the right hand side has location=None with pytest.raises(ValueError) as err: t[0, 0] = Time(-1, format='cxcsec') assert ('cannot set to Time with different location: ' 'expected location={} and ' 'got location=None'.format(loc[0])) in str(err.value) # Succeeds because the right hand side correctly sets location t[0, 0] = Time(-2, format='cxcsec', location=loc[0]) assert allclose_sec(t.value, [[-2, 2], [3, 4]]) # Fails because the right hand side has different location with pytest.raises(ValueError) as err: t[0, 0] = Time(-2, format='cxcsec', location=loc[1]) assert ('cannot set to Time with different location: ' 'expected location={} and ' 'got location={}'.format(loc[0], loc[1])) in str(err.value) # Fails because the Time has None location and RHS has defined location t = Time([[1, 2], [3, 4]], format='cxcsec') with pytest.raises(ValueError) as err: t[0, 0] = Time(-2, format='cxcsec', location=loc[1]) assert ('cannot set to Time with different location: ' 'expected location=None and ' 'got location={}'.format(loc[1])) in str(err.value) # Broadcasting works t = Time([[1, 2], [3, 4]], format='cxcsec', location=loc) t[0, :] = Time([-3, -4], format='cxcsec', location=loc) assert allclose_sec(t.value, [[-3, -4], [3, 4]]) def test_setitem_from_python_objects(): t = Time([[1, 2], [3, 4]], format='cxcsec') assert t.cache == {} t.iso assert 'iso' in t.cache['format'] assert np.all(t.iso == [['1998-01-01 00:00:01.000', '1998-01-01 00:00:02.000'], ['1998-01-01 00:00:03.000', '1998-01-01 00:00:04.000']]) # Setting item clears cache t[0, 1] = 100 assert t.cache == {} assert allclose_sec(t.value, [[1, 100], [3, 4]]) assert np.all(t.iso == [['1998-01-01 00:00:01.000', '1998-01-01 00:01:40.000'], ['1998-01-01 00:00:03.000', '1998-01-01 00:00:04.000']]) # Set with a float value t.iso t[1, :] = 200 assert t.cache == {} assert allclose_sec(t.value, [[1, 100], [200, 200]]) # Array of strings in yday format t[:, 1] = ['1998:002', '1998:003'] assert allclose_sec(t.value, [[1, 86400 * 1], [200, 86400 * 2]]) # Incompatible numeric value t = Time(['2000:001', '2000:002']) t[0] = '2001:001' with pytest.raises(ValueError) as err: t[0] = 100 assert 'cannot convert value to a compatible Time object' in str(err.value) def test_setitem_from_time_objects(): """Set from existing Time object. """ # Set from time object with different scale t = Time(['2000:001', '2000:002'], scale='utc') t2 = Time(['2000:010'], scale='tai') t[1] = t2[0] assert t.value[1] == t2.utc.value[0] # Time object with different scale and format t = Time(['2000:001', '2000:002'], scale='utc') t2.format = 'jyear' t[1] = t2[0] assert t.yday[1] == t2.utc.yday[0] def test_setitem_bad_item(): t = Time([1, 2], format='cxcsec') with pytest.raises(IndexError): t['asdf'] = 3 def test_setitem_deltas(): """Setting invalidates any transform deltas""" t = Time([1, 2], format='cxcsec') t.delta_tdb_tt = [1, 2] t.delta_ut1_utc = [3, 4] t[1] = 3 assert not hasattr(t, '_delta_tdb_tt') assert not hasattr(t, '_delta_ut1_utc') def test_subclass(): """Check that we can initialize subclasses with a Time instance.""" # Ref: Issue gh-#7449 and PR gh-#7453. class _Time(Time): pass t1 = Time('1999-01-01T01:01:01') t2 = _Time(t1) assert t2.__class__ == _Time assert t1 == t2 def test_strftime_scalar(): """Test of Time.strftime """ time_string = '2010-09-03 06:00:00' t = Time(time_string) for format in t.FORMATS: t.format = format assert t.strftime('%Y-%m-%d %H:%M:%S') == time_string def test_strftime_array(): tstrings = ['2010-09-03 00:00:00', '2005-09-03 06:00:00', '1995-12-31 23:59:60'] t = Time(tstrings) for format in t.FORMATS: t.format = format assert t.strftime('%Y-%m-%d %H:%M:%S').tolist() == tstrings def test_strftime_array_2(): tstrings = [['1998-01-01 00:00:01', '1998-01-01 00:00:02'], ['1998-01-01 00:00:03', '1995-12-31 23:59:60']] tstrings = np.array(tstrings) t = Time(tstrings) for format in t.FORMATS: t.format = format assert np.all(t.strftime('%Y-%m-%d %H:%M:%S') == tstrings) assert t.strftime('%Y-%m-%d %H:%M:%S').shape == tstrings.shape def test_strftime_leapsecond(): time_string = '1995-12-31 23:59:60' t = Time(time_string) for format in t.FORMATS: t.format = format assert t.strftime('%Y-%m-%d %H:%M:%S') == time_string def test_strptime_scalar(): """Test of Time.strptime """ time_string = '2007-May-04 21:08:12' time_object = Time('2007-05-04 21:08:12') t = Time.strptime(time_string, '%Y-%b-%d %H:%M:%S') assert t == time_object def test_strptime_array(): """Test of Time.strptime """ tstrings = [['1998-Jan-01 00:00:01', '1998-Jan-01 00:00:02'], ['1998-Jan-01 00:00:03', '1998-Jan-01 00:00:04']] tstrings = np.array(tstrings) time_object = Time([['1998-01-01 00:00:01', '1998-01-01 00:00:02'], ['1998-01-01 00:00:03', '1998-01-01 00:00:04']]) t = Time.strptime(tstrings, '%Y-%b-%d %H:%M:%S') assert np.all(t == time_object) assert t.shape == tstrings.shape def test_strptime_badinput(): tstrings = [1, 2, 3] with pytest.raises(TypeError): Time.strptime(tstrings, '%S') def test_strptime_input_bytes_scalar(): time_string = b'2007-May-04 21:08:12' time_object = Time('2007-05-04 21:08:12') t = Time.strptime(time_string, '%Y-%b-%d %H:%M:%S') assert t == time_object def test_strptime_input_bytes_array(): tstrings = [[b'1998-Jan-01 00:00:01', b'1998-Jan-01 00:00:02'], [b'1998-Jan-01 00:00:03', b'1998-Jan-01 00:00:04']] tstrings = np.array(tstrings) time_object = Time([['1998-01-01 00:00:01', '1998-01-01 00:00:02'], ['1998-01-01 00:00:03', '1998-01-01 00:00:04']]) t = Time.strptime(tstrings, '%Y-%b-%d %H:%M:%S') assert np.all(t == time_object) assert t.shape == tstrings.shape def test_strptime_leapsecond(): time_obj1 = Time('1995-12-31T23:59:60', format='isot') time_obj2 = Time.strptime('1995-Dec-31 23:59:60', '%Y-%b-%d %H:%M:%S') assert time_obj1 == time_obj2 def test_strptime_3_digit_year(): time_obj1 = Time('0995-12-31T00:00:00', format='isot', scale='tai') time_obj2 = Time.strptime('0995-Dec-31 00:00:00', '%Y-%b-%d %H:%M:%S', scale='tai') assert time_obj1 == time_obj2 def test_strptime_fracsec_scalar(): time_string = '2007-May-04 21:08:12.123' time_object = Time('2007-05-04 21:08:12.123') t = Time.strptime(time_string, '%Y-%b-%d %H:%M:%S.%f') assert t == time_object def test_strptime_fracsec_array(): """Test of Time.strptime """ tstrings = [['1998-Jan-01 00:00:01.123', '1998-Jan-01 00:00:02.000001'], ['1998-Jan-01 00:00:03.000900', '1998-Jan-01 00:00:04.123456']] tstrings = np.array(tstrings) time_object = Time([['1998-01-01 00:00:01.123', '1998-01-01 00:00:02.000001'], ['1998-01-01 00:00:03.000900', '1998-01-01 00:00:04.123456']]) t = Time.strptime(tstrings, '%Y-%b-%d %H:%M:%S.%f') assert np.all(t == time_object) assert t.shape == tstrings.shape def test_strftime_scalar_fracsec(): """Test of Time.strftime """ time_string = '2010-09-03 06:00:00.123' t = Time(time_string) for format in t.FORMATS: t.format = format assert t.strftime('%Y-%m-%d %H:%M:%S.%f') == time_string def test_strftime_scalar_fracsec_precision(): time_string = '2010-09-03 06:00:00.123123123' t = Time(time_string) assert t.strftime('%Y-%m-%d %H:%M:%S.%f') == '2010-09-03 06:00:00.123' t.precision = 9 assert t.strftime('%Y-%m-%d %H:%M:%S.%f') == '2010-09-03 06:00:00.123123123' def test_strftime_array_fracsec(): tstrings = ['2010-09-03 00:00:00.123000', '2005-09-03 06:00:00.000001', '1995-12-31 23:59:60.000900'] t = Time(tstrings) t.precision = 6 for format in t.FORMATS: t.format = format assert t.strftime('%Y-%m-%d %H:%M:%S.%f').tolist() == tstrings def test_insert_time(): tm = Time([1, 2], format='unix') # Insert a scalar using an auto-parsed string tm2 = tm.insert(1, '1970-01-01 00:01:00') assert np.all(tm2 == Time([1, 60, 2], format='unix')) # Insert scalar using a Time value tm2 = tm.insert(1, Time('1970-01-01 00:01:00')) assert np.all(tm2 == Time([1, 60, 2], format='unix')) # Insert length=1 array with a Time value tm2 = tm.insert(1, [Time('1970-01-01 00:01:00')]) assert np.all(tm2 == Time([1, 60, 2], format='unix')) # Insert length=2 list with float values matching unix format. # Also actually provide axis=0 unlike all other tests. tm2 = tm.insert(1, [10, 20], axis=0) assert np.all(tm2 == Time([1, 10, 20, 2], format='unix')) # Insert length=2 np.array with float values matching unix format tm2 = tm.insert(1, np.array([10, 20])) assert np.all(tm2 == Time([1, 10, 20, 2], format='unix')) # Insert length=2 np.array with float values at the end tm2 = tm.insert(2, np.array([10, 20])) assert np.all(tm2 == Time([1, 2, 10, 20], format='unix')) # Insert length=2 np.array with float values at the beginning # with a negative index tm2 = tm.insert(-2, np.array([10, 20])) assert np.all(tm2 == Time([10, 20, 1, 2], format='unix')) def test_insert_exceptions(): tm = Time(1, format='unix') with pytest.raises(TypeError) as err: tm.insert(0, 50) assert 'cannot insert into scalar' in str(err.value) tm = Time([1, 2], format='unix') with pytest.raises(ValueError) as err: tm.insert(0, 50, axis=1) assert 'axis must be 0' in str(err.value) with pytest.raises(TypeError) as err: tm.insert(slice(None), 50) assert 'obj arg must be an integer' in str(err.value) with pytest.raises(IndexError) as err: tm.insert(-100, 50) assert 'index -100 is out of bounds for axis 0 with size 2' in str(err.value) def test_datetime64_no_format(): dt64 = np.datetime64('2000-01-02T03:04:05.123456789') t = Time(dt64, scale='utc', precision=9) assert t.iso == '2000-01-02 03:04:05.123456789' assert t.datetime64 == dt64 assert t.value == dt64 def test_hash_time(): loc1 = EarthLocation(1 * u.m, 2 * u.m, 3 * u.m) for loc in None, loc1: t = Time([1, 1, 2, 3], format='cxcsec', location=loc) t[3] = np.ma.masked h1 = hash(t[0]) h2 = hash(t[1]) h3 = hash(t[2]) assert h1 == h2 assert h1 != h3 with pytest.raises(TypeError) as exc: hash(t) assert exc.value.args[0] == "unhashable type: 'Time' (must be scalar)" with pytest.raises(TypeError) as exc: hash(t[3]) assert exc.value.args[0] == "unhashable type: 'Time' (value is masked)" t = Time(1, format='cxcsec', location=loc) t2 = Time(1, format='cxcsec') assert hash(t) != hash(t2) t = Time('2000:180', scale='utc') t2 = Time(t, scale='tai') assert t == t2 assert hash(t) != hash(t2) def test_hash_time_delta(): t = TimeDelta([1, 1, 2, 3], format='sec') t[3] = np.ma.masked h1 = hash(t[0]) h2 = hash(t[1]) h3 = hash(t[2]) assert h1 == h2 assert h1 != h3 with pytest.raises(TypeError) as exc: hash(t) assert exc.value.args[0] == "unhashable type: 'TimeDelta' (must be scalar)" with pytest.raises(TypeError) as exc: hash(t[3]) assert exc.value.args[0] == "unhashable type: 'TimeDelta' (value is masked)" def test_get_time_fmt_exception_messages(): with pytest.raises(ValueError) as err: Time(10) assert "No time format was given, and the input is" in str(err.value) with pytest.raises(ValueError) as err: Time('2000:001', format='not-a-format') assert "Format 'not-a-format' is not one of the allowed" in str(err.value) with pytest.raises(ValueError) as err: Time('200') assert 'Input values did not match any of the formats where' in str(err.value) with pytest.raises(ValueError) as err: Time('200', format='iso') assert ('Input values did not match the format class iso:' + os.linesep + 'ValueError: Time 200 does not match iso format') == str(err.value) with pytest.raises(ValueError) as err: Time(200, format='iso') assert ('Input values did not match the format class iso:' + os.linesep + 'TypeError: Input values for iso class must be strings') == str(err.value) def test_ymdhms_defaults(): t1 = Time({'year': 2001}, format='ymdhms') assert t1 == Time('2001-01-01') times_dict_ns = { 'year': [2001, 2002], 'month': [2, 3], 'day': [4, 5], 'hour': [6, 7], 'minute': [8, 9], 'second': [10, 11] } table_ns = Table(times_dict_ns) struct_array_ns = table_ns.as_array() rec_array_ns = struct_array_ns.view(np.recarray) ymdhms_names = ('year', 'month', 'day', 'hour', 'minute', 'second') @pytest.mark.parametrize('tm_input', [table_ns, struct_array_ns, rec_array_ns]) @pytest.mark.parametrize('kwargs', [{}, {'format': 'ymdhms'}]) @pytest.mark.parametrize('as_row', [False, True]) def test_ymdhms_init_from_table_like(tm_input, kwargs, as_row): time_ns = Time(['2001-02-04 06:08:10', '2002-03-05 07:09:11']) if as_row: tm_input = tm_input[0] time_ns = time_ns[0] tm = Time(tm_input, **kwargs) assert np.all(tm == time_ns) assert tm.value.dtype.names == ymdhms_names def test_ymdhms_init_from_dict_array(): times_dict_shape = { 'year': [[2001, 2002], [2003, 2004]], 'month': [2, 3], 'day': 4 } time_shape = Time( [['2001-02-04', '2002-03-04'], ['2003-02-04', '2004-03-04']] ) time = Time(times_dict_shape, format='ymdhms') assert np.all(time == time_shape) assert time.ymdhms.shape == time_shape.shape @pytest.mark.parametrize('kwargs', [{}, {'format': 'ymdhms'}]) def test_ymdhms_init_from_dict_scalar(kwargs): """ Test YMDHMS functionality for a dict input. This includes ensuring that key and attribute access work. For extra fun use a time within a leap second. """ time_dict = { 'year': 2016, 'month': 12, 'day': 31, 'hour': 23, 'minute': 59, 'second': 60.123456789} tm = Time(time_dict, **kwargs) assert tm == Time('2016-12-31T23:59:60.123456789') for attr in time_dict: for value in (tm.value[attr], getattr(tm.value, attr)): if attr == 'second': assert allclose_sec(time_dict[attr], value) else: assert time_dict[attr] == value # Now test initializing from a YMDHMS format time using the object tm_rt = Time(tm) assert tm_rt == tm assert tm_rt.format == 'ymdhms' # Test initializing from a YMDHMS value (np.void, i.e. recarray row) # without specified format. tm_rt = Time(tm.ymdhms) assert tm_rt == tm assert tm_rt.format == 'ymdhms' def test_ymdhms_exceptions(): with pytest.raises(ValueError, match='input must be dict or table-like'): Time(10, format='ymdhms') match = "'wrong' not allowed as YMDHMS key name(s)" # NB: for reasons unknown, using match=match in pytest.raises() fails, so we # fall back to old school ``match in str(err.value)``. with pytest.raises(ValueError) as err: Time({'year': 2019, 'wrong': 1}, format='ymdhms') assert match in str(err.value) match = "for 2 input key names you must supply 'year', 'month'" with pytest.raises(ValueError, match=match): Time({'year': 2019, 'minute': 1}, format='ymdhms') def test_ymdhms_masked(): tm = Time({'year': [2000, 2001]}, format='ymdhms') tm[0] = np.ma.masked assert isinstance(tm.value[0], np.ma.core.mvoid) for name in ymdhms_names: assert tm.value[0][name] is np.ma.masked # Converted from doctest in astropy/test/formats.py for debugging def test_ymdhms_output(): t = Time({'year': 2015, 'month': 2, 'day': 3, 'hour': 12, 'minute': 13, 'second': 14.567}, scale='utc') # NOTE: actually comes back as np.void for some reason # NOTE: not necessarily a python int; might be an int32 assert t.ymdhms.year == 2015 # There are two stages of validation now - one on input into a format, so that # the format conversion code has tidy matched arrays to work with, and the # other when object construction does not go through a format object. Or at # least, the format object is constructed with "from_jd=True". In this case the # normal input validation does not happen but the new input validation does, # and can ensure that strange broadcasting anomalies can't happen. # This form of construction uses from_jd=True. def test_broadcasting_writeable(): t = Time('J2015') + np.linspace(-1, 1, 10) * u.day t[2] = Time(58000, format="mjd") def test_format_subformat_compatibility(): """Test that changing format with out_subfmt defined is not a problem. See #9812, #9810.""" t = Time('2019-12-20', out_subfmt='date_??') assert t.mjd == 58837.0 assert t.yday == '2019:354:00:00' # Preserves out_subfmt t2 = t.replicate(format='mjd') assert t2.out_subfmt == '*' # Changes to default t2 = t.copy(format='mjd') assert t2.out_subfmt == '*' t2 = Time(t, format='mjd') assert t2.out_subfmt == '*' t2 = t.copy(format='yday') assert t2.out_subfmt == 'date_??' assert t2.value == '2019:354:00:00' t.format = 'yday' assert t.value == '2019:354:00:00' assert t.out_subfmt == 'date_??' t = Time('2019-12-20', out_subfmt='date') assert t.mjd == 58837.0 assert t.yday == '2019:354' @pytest.mark.parametrize('fmt_name,fmt_class', TIME_FORMATS.items()) def test_to_value_with_subfmt_for_every_format(fmt_name, fmt_class): """From a starting Time value, test that every valid combination of to_value(format, subfmt) works. See #9812, #9361. """ t = Time('2000-01-01') subfmts = list(subfmt[0] for subfmt in fmt_class.subfmts) + [None, '*'] for subfmt in subfmts: t.to_value(fmt_name, subfmt) @pytest.mark.parametrize('location', [None, (45, 45)]) def test_location_init(location): """Test fix in #9969 for issue #9962 where the location attribute is lost when initializing Time from an existing Time instance of list of Time instances. """ tm = Time('J2010', location=location) # Init from a scalar Time tm2 = Time(tm) assert np.all(tm.location == tm2.location) assert type(tm.location) is type(tm2.location) # noqa # From a list of Times tm2 = Time([tm, tm]) if location is None: assert tm2.location is None else: for loc in tm2.location: assert loc == tm.location assert type(tm.location) is type(tm2.location) # noqa # Effectively the same as a list of Times, but just to be sure that # Table mixin inititialization is working as expected. tm2 = Table([[tm, tm]])['col0'] if location is None: assert tm2.location is None else: for loc in tm2.location: assert loc == tm.location assert type(tm.location) is type(tm2.location) # noqa def test_location_init_fail(): """Test fix in #9969 for issue #9962 where the location attribute is lost when initializing Time from an existing Time instance of list of Time instances. Make sure exception is correct. """ tm = Time('J2010', location=(45, 45)) tm2 = Time('J2010') with pytest.raises(ValueError, match='cannot concatenate times unless all locations'): Time([tm, tm2])
836169c512d115acdc03eb1d45161bca6410c010c2938868b595aa7a9dc5c9ce
import decimal import warnings import functools import contextlib from decimal import Decimal from datetime import datetime, timedelta import pytest from hypothesis import assume, example, given, target from hypothesis.extra.numpy import array_shapes, arrays from hypothesis.strategies import (composite, datetimes, floats, integers, one_of, sampled_from, timedeltas, tuples) import numpy as np import erfa from erfa import ErfaError, ErfaWarning import astropy.units as u from astropy.tests.helper import assert_quantity_allclose from astropy.time import STANDARD_TIME_SCALES, Time, TimeDelta from astropy.time.utils import day_frac, two_sum from astropy.utils import iers allclose_jd = functools.partial(np.allclose, rtol=np.finfo(float).eps, atol=0) allclose_jd2 = functools.partial(np.allclose, rtol=np.finfo(float).eps, atol=np.finfo(float).eps) # 20 ps atol allclose_sec = functools.partial(np.allclose, rtol=np.finfo(float).eps, atol=np.finfo(float).eps * 24 * 3600) tiny = np.finfo(float).eps dt_tiny = TimeDelta(tiny, format='jd') def setup_module(): # Pre-load leap seconds table to avoid flakiness in hypothesis runs. # See https://github.com/astropy/astropy/issues/11030 Time('2020-01-01').ut1 @pytest.fixture(scope='module') def iers_b(): """This is an expensive operation, so we share it between tests using a module-scoped fixture instead of using the context manager form. This is particularly important for Hypothesis, which invokes the decorated test function many times (100 by default; see conftest.py for details). """ with iers.earth_orientation_table.set(iers.IERS_B.open(iers.IERS_B_FILE)): yield "<using IERS-B orientation table>" @contextlib.contextmanager def quiet_erfa(): with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=ErfaWarning) yield def assert_almost_equal(a, b, *, rtol=None, atol=None, label=''): """Assert numbers are almost equal. This version also lets hypothesis know how far apart the inputs are, so that it can work towards a failure and present the worst failure ever seen as well as the simplest, which often just barely exceeds the threshold. """ __tracebackhide__ = True if rtol is None or rtol == 0: thresh = atol elif atol is None: thresh = rtol * (abs(a) + abs(b)) / 2 else: thresh = atol + rtol * (abs(a) + abs(b)) / 2 amb = (a - b) if isinstance(amb, TimeDelta): ambv = amb.to_value(u.s) target(ambv, label=label + " (a-b).to_value(u.s), from TimeDelta") target(-ambv, label=label + " (b-a).to_value(u.s), from TimeDelta") if isinstance(thresh, u.Quantity): amb = amb.to(thresh.unit) else: try: target_value = float(amb) except TypeError: pass else: target(target_value, label=label + " float(a-b)") target(-target_value, label=label + " float(b-a)") assert abs(amb) < thresh # Days that end with leap seconds # Some time scales use a so-called "leap smear" to cope with these, others # have times they can't represent or can represent two different ways. # In any case these days are liable to cause trouble in time conversions. # Note that from_erfa includes some weird non-integer steps before 1970. leap_second_table = iers.LeapSeconds.from_iers_leap_seconds() # Days that contain leap_seconds leap_second_days = leap_second_table["mjd"] - 1 leap_second_deltas = list(zip(leap_second_days[1:], np.diff(leap_second_table["tai_utc"]))) today = Time.now() mjd0 = Time(0, format="mjd") def reasonable_ordinary_jd(): return tuples(floats(2440000, 2470000), floats(-0.5, 0.5)) @composite def leap_second_tricky(draw): mjd = draw(one_of(sampled_from(leap_second_days), sampled_from(leap_second_days + 1), sampled_from(leap_second_days - 1))) return mjd + mjd0.jd1 + mjd0.jd2, draw(floats(0, 1)) def reasonable_jd(): """Pick a reasonable JD. These should be not too far in the past or future (so that date conversion routines don't have to deal with anything too exotic), but they should include leap second days as a special case, and they should include several particularly simple cases (today, the beginning of the MJD scale, a reasonable date) so that hypothesis' example simplification produces obviously simple examples when they trigger problems. """ moments = [(2455000., 0.), (mjd0.jd1, mjd0.jd2), (today.jd1, today.jd2)] return one_of(sampled_from(moments), reasonable_ordinary_jd(), leap_second_tricky()) def unreasonable_ordinary_jd(): """JD pair that might be unordered or far away""" return tuples(floats(-1e7, 1e7), floats(-1e7, 1e7)) def ordered_jd(): """JD pair that is ordered but not necessarily near now""" return tuples(floats(-1e7, 1e7), floats(-0.5, 0.5)) def unreasonable_jd(): return one_of(reasonable_jd(), ordered_jd(), unreasonable_ordinary_jd()) @composite def jd_arrays(draw, jd_values): s = draw(array_shapes()) d = np.dtype([("jd1", float), ("jd2", float)]) jdv = jd_values.map(lambda x: np.array(x, dtype=d)) a = draw(arrays(d, s, elements=jdv)) return a["jd1"], a["jd2"] def unreasonable_delta(): return tuples(floats(-1e7, 1e7), floats(-1e7, 1e7)) def reasonable_delta(): return tuples(floats(-1e4, 1e4), floats(-0.5, 0.5)) # redundant? def test_abs_jd2_always_less_than_half(): """Make jd2 approach +/-0.5, and check that it doesn't go over.""" t1 = Time(2400000.5, [-tiny, +tiny], format='jd') assert np.all(t1.jd1 % 1 == 0) assert np.all(abs(t1.jd2) < 0.5) t2 = Time(2400000., [[0.5 - tiny, 0.5 + tiny], [-0.5 - tiny, -0.5 + tiny]], format='jd') assert np.all(t2.jd1 % 1 == 0) assert np.all(abs(t2.jd2) < 0.5) @given(jd_arrays(unreasonable_jd())) def test_abs_jd2_always_less_than_half_on_construction(jds): jd1, jd2 = jds t = Time(jd1, jd2, format="jd") target(np.amax(np.abs(t.jd2))) assert np.all(t.jd1 % 1 == 0) assert np.all(abs(t.jd2) <= 0.5) assert np.all((abs(t.jd2) < 0.5) | (t.jd1 % 2 == 0)) @given(integers(-10**8, 10**8), sampled_from([-0.5, 0.5])) def test_round_to_even(jd1, jd2): t = Time(jd1, jd2, format="jd") assert (abs(t.jd2) == 0.5) and (t.jd1 % 2 == 0) def test_addition(): """Check that an addition at the limit of precision (2^-52) is seen""" t = Time(2455555., 0.5, format='jd', scale='utc') t_dt = t + dt_tiny assert t_dt.jd1 == t.jd1 and t_dt.jd2 != t.jd2 # Check that the addition is exactly reversed by the corresponding # subtraction t2 = t_dt - dt_tiny assert t2.jd1 == t.jd1 and t2.jd2 == t.jd2 def test_mult_div(): """Test precision with multiply and divide""" dt_small = 6 * dt_tiny # pick a number that will leave remainder if divided by 6. dt_big = TimeDelta(20000., format='jd') dt_big_small_by_6 = (dt_big + dt_small) / 6. dt_frac = dt_big_small_by_6 - TimeDelta(3333., format='jd') assert allclose_jd2(dt_frac.jd2, 0.33333333333333354) def test_init_variations(): """Check that 3 ways of specifying a time + small offset are equivalent""" dt_tiny_sec = dt_tiny.jd2 * 86400. t1 = Time(1e11, format='cxcsec') + dt_tiny t2 = Time(1e11, dt_tiny_sec, format='cxcsec') t3 = Time(dt_tiny_sec, 1e11, format='cxcsec') assert t1.jd1 == t2.jd1 assert t1.jd2 == t3.jd2 assert t1.jd1 == t2.jd1 assert t1.jd2 == t3.jd2 def test_precision_exceeds_64bit(): """ Check that Time object really holds more precision than float64 by looking at the (naively) summed 64-bit result and asserting equality at the bit level. """ t1 = Time(1.23456789e11, format='cxcsec') t2 = t1 + dt_tiny assert t1.jd == t2.jd def test_through_scale_change(): """Check that precision holds through scale change (cxcsec is TT)""" t0 = Time(1.0, format='cxcsec') t1 = Time(1.23456789e11, format='cxcsec') dt_tt = t1 - t0 dt_tai = t1.tai - t0.tai assert allclose_jd(dt_tt.jd1, dt_tai.jd1) assert allclose_jd2(dt_tt.jd2, dt_tai.jd2) def test_iso_init(): """Check when initializing from ISO date""" t1 = Time('2000:001:00:00:00.00000001', scale='tai') t2 = Time('3000:001:13:00:00.00000002', scale='tai') dt = t2 - t1 assert allclose_jd2(dt.jd2, 13. / 24. + 1e-8 / 86400. - 1.0) def test_jd1_is_mult_of_one(): """ Check that jd1 is a multiple of 1. """ t1 = Time('2000:001:00:00:00.00000001', scale='tai') assert np.round(t1.jd1) == t1.jd1 t1 = Time(1.23456789, 12345678.90123456, format='jd', scale='tai') assert np.round(t1.jd1) == t1.jd1 def test_precision_neg(): """ Check precision when jd1 is negative. This used to fail because ERFA routines use a test like jd1 > jd2 to decide which component to update. It was updated to abs(jd1) > abs(jd2) in erfa 1.6 (sofa 20190722). """ t1 = Time(-100000.123456, format='jd', scale='tt') assert np.round(t1.jd1) == t1.jd1 t1_tai = t1.tai assert np.round(t1_tai.jd1) == t1_tai.jd1 def test_precision_epoch(): """ Check that input via epoch also has full precision, i.e., against regression on https://github.com/astropy/astropy/pull/366 """ t_utc = Time(range(1980, 2001), format='jyear', scale='utc') t_tai = Time(range(1980, 2001), format='jyear', scale='tai') dt = t_utc - t_tai assert allclose_sec(dt.sec, np.round(dt.sec)) def test_leap_seconds_rounded_correctly(): """Regression tests against #2083, where a leap second was rounded incorrectly by the underlying ERFA routine.""" with iers.conf.set_temp('auto_download', False): t = Time(['2012-06-30 23:59:59.413', '2012-07-01 00:00:00.413'], scale='ut1', precision=3).utc assert np.all(t.iso == np.array(['2012-06-30 23:59:60.000', '2012-07-01 00:00:00.000'])) # with the bug, both yielded '2012-06-30 23:59:60.000' @given(integers(-2**52+2, 2**52-2), floats(-1, 1)) @example(i=65536, f=3.637978807091714e-12) def test_two_sum(i, f): with decimal.localcontext(decimal.Context(prec=40)): a = Decimal(i) + Decimal(f) s, r = two_sum(i, f) b = Decimal(s) + Decimal(r) assert_almost_equal(a, b, atol=Decimal(tiny), rtol=Decimal(0)) @given(floats(), floats()) def test_two_sum_symmetric(f1, f2): np.testing.assert_equal(two_sum(f1, f2), two_sum(f2, f1)) @given(floats(allow_nan=False, allow_infinity=False), floats(allow_nan=False, allow_infinity=False)) @example(f1=8.988465674311579e+307, f2=8.98846567431158e+307) @example(f1=8.988465674311579e+307, f2=-8.98846567431158e+307) @example(f1=-8.988465674311579e+307, f2=-8.98846567431158e+307) def test_two_sum_size(f1, f2): r1, r2 = two_sum(f1, f2) assert (abs(r1) > abs(r2) / np.finfo(float).eps or r1 == r2 == 0 or not np.isfinite(f1 + f2)) @given(integers(-2**52+2, 2**52-2), floats(-1, 1)) @example(i=65536, f=3.637978807091714e-12) def test_day_frac_harmless(i, f): with decimal.localcontext(decimal.Context(prec=40)): a = Decimal(i) + Decimal(f) i_d, f_d = day_frac(i, f) a_d = Decimal(i_d) + Decimal(f_d) assert_almost_equal(a, a_d, atol=Decimal(tiny), rtol=Decimal(0)) @given(integers(-2**52+2, 2**52-2), floats(-0.5, 0.5)) @example(i=65536, f=3.637978807091714e-12) def test_day_frac_exact(i, f): assume(abs(f) < 0.5 or i % 2 == 0) i_d, f_d = day_frac(i, f) assert i == i_d assert f == f_d @given(integers(-2**52+2, 2**52-2), floats(-1, 1)) @example(i=65536, f=3.637978807091714e-12) def test_day_frac_idempotent(i, f): i_d, f_d = day_frac(i, f) assert (i_d, f_d) == day_frac(i_d, f_d) @given(integers(-2**52+2, 2**52-2), floats(-1, 1)) @example(i=65536, f=3.637978807091714e-12) def test_mjd_initialization_precise(i, f): t = Time(val=i, val2=f, format="mjd", scale="tai") jd1, jd2 = day_frac(i + erfa.DJM0, f) jd1_t, jd2_t = day_frac(t.jd1, t.jd2) assert (abs((jd1 - jd1_t) + (jd2 - jd2_t)) * u.day).to(u.ns) < 1 * u.ns @given(jd_arrays(unreasonable_jd())) def test_day_frac_always_less_than_half(jds): jd1, jd2 = jds t_jd1, t_jd2 = day_frac(jd1, jd2) assert np.all(t_jd1 % 1 == 0) assert np.all(abs(t_jd2) <= 0.5) assert np.all((abs(t_jd2) < 0.5) | (t_jd1 % 2 == 0)) @given(integers(-10**8, 10**8), sampled_from([-0.5, 0.5])) def test_day_frac_round_to_even(jd1, jd2): t_jd1, t_jd2 = day_frac(jd1, jd2) assert (abs(t_jd2) == 0.5) and (t_jd1 % 2 == 0) @given(scale=sampled_from(STANDARD_TIME_SCALES), jds=unreasonable_jd()) @example(scale="tai", jds=(0.0, 0.0)) @example(scale="tai", jds=(0.0, -31738.500000000346)) def test_resolution_never_decreases(scale, jds): jd1, jd2 = jds assume(not scale == 'utc' or 2440000 < jd1 + jd2 < 2460000) t = Time(jd1, jd2, format="jd", scale=scale) with quiet_erfa(): assert t != t + dt_tiny @given(reasonable_jd()) def test_resolution_never_decreases_utc(jds): """UTC is very unhappy with unreasonable times""" jd1, jd2 = jds t = Time(jd1, jd2, format="jd", scale="utc") with quiet_erfa(): assert t != t + dt_tiny @given(scale1=sampled_from(STANDARD_TIME_SCALES), scale2=sampled_from(STANDARD_TIME_SCALES), jds=unreasonable_jd()) @example(scale1='tcg', scale2='ut1', jds=(2445149.5, 0.47187700984387526)) @example(scale1='tai', scale2='tcb', jds=(2441316.5, 0.0)) @example(scale1='tai', scale2='tcb', jds=(0.0, 0.0)) def test_conversion_preserves_jd1_jd2_invariant(iers_b, scale1, scale2, jds): jd1, jd2 = jds t = Time(jd1, jd2, scale=scale1, format="jd") try: with quiet_erfa(): t2 = getattr(t, scale2) except iers.IERSRangeError: # UT1 conversion needs IERS data assume(False) except ErfaError: assume(False) assert t2.jd1 % 1 == 0 assert abs(t2.jd2) <= 0.5 assert abs(t2.jd2) < 0.5 or t2.jd1 % 2 == 0 @given(scale1=sampled_from(STANDARD_TIME_SCALES), scale2=sampled_from(STANDARD_TIME_SCALES), jds=unreasonable_jd()) @example(scale1='tai', scale2='utc', jds=(0.0, 0.0)) def test_conversion_never_loses_precision(iers_b, scale1, scale2, jds): """Check that time ordering remains if we convert to another scale. Here, since scale differences can involve multiplication, we allow for losing one ULP, i.e., we test that two times that differ by two ULP will keep the same order if changed to another scale. """ jd1, jd2 = jds t = Time(jd1, jd2, scale=scale1, format="jd") # Near-zero UTC JDs degrade accuracy; not clear why, # but also not so relevant, so ignoring. if (scale1 == 'utc' or scale2 == 'utc') and abs(jd1+jd2) < 1: tiny = 100*u.us else: tiny = 2*dt_tiny try: with quiet_erfa(): t2 = t + tiny assert getattr(t, scale2) < getattr(t2, scale2) except iers.IERSRangeError: # UT1 conversion needs IERS data assume(scale1 != 'ut1' or 2440000 < jd1 + jd2 < 2458000) assume(scale2 != 'ut1' or 2440000 < jd1 + jd2 < 2458000) raise except ErfaError: # If the generated date is too early to compute a UTC julian date, # and we're not converting between scales which are known to be safe, # tell Hypothesis that this example is invalid and to try another. # See https://docs.astropy.org/en/latest/time/index.html#time-scale barycentric = {scale1, scale2}.issubset({'tcb', 'tdb'}) geocentric = {scale1, scale2}.issubset({'tai', 'tt', 'tcg'}) assume(jd1 + jd2 >= -31738.5 or geocentric or barycentric) raise @given(sampled_from(leap_second_deltas), floats(0.1, 0.9)) def test_leap_stretch_mjd(d, f): mjd, delta = d t0 = Time(mjd, format="mjd", scale="utc") th = Time(mjd + f, format="mjd", scale="utc") t1 = Time(mjd + 1, format="mjd", scale="utc") assert_quantity_allclose((t1 - t0).to(u.s), (1 * u.day + delta * u.s)) assert_quantity_allclose((th - t0).to(u.s), f * (1 * u.day + delta * u.s)) assert_quantity_allclose((t1 - th).to(u.s), (1 - f) * (1 * u.day + delta * u.s)) @given(scale=sampled_from(STANDARD_TIME_SCALES), jds=unreasonable_jd(), delta=floats(-10000, 10000)) @example(scale='utc', jds=(0.0, 2.2204460492503136e-13), delta=6.661338147750941e-13) @example(scale='utc', jds=(2441682.5, 2.2204460492503136e-16), delta=7.327471962526035e-12) @example(scale='utc', jds=(0.0, 5.787592627370942e-13), delta=0.0) def test_jd_add_subtract_round_trip(scale, jds, delta): jd1, jd2 = jds if scale == 'utc' and abs(jd1+jd2) < 1: # Near-zero UTC JDs degrade accuracy; not clear why, # but also not so relevant, so ignoring. thresh = 100*u.us else: thresh = 2*dt_tiny t = Time(jd1, jd2, scale=scale, format="jd") try: with quiet_erfa(): t2 = t + delta*u.day if abs(delta) >= np.finfo(float).eps: assert t2 != t t3 = t2 - delta*u.day assert_almost_equal(t3, t, atol=thresh, rtol=0) except ErfaError: assume(scale != 'utc' or 2440000 < jd1+jd2 < 2460000) raise @given(scale=sampled_from(STANDARD_TIME_SCALES), jds=reasonable_jd(), delta=floats(-3*tiny, 3*tiny)) @example(scale='tai', jds=(0.0, 3.5762786865234384), delta=2.220446049250313e-16) def test_time_argminmaxsort(scale, jds, delta): jd1, jd2 = jds t = Time(jd1, jd2+np.array([0, delta]), scale=scale, format="jd") imin = t.argmin() imax = t.argmax() isort = t.argsort() diff = (t.jd1[1]-t.jd1[0]) + (t.jd2[1]-t.jd2[0]) if diff < 0: # item 1 smaller assert delta < 0 assert imin == 1 and imax == 0 and np.all(isort == [1, 0]) elif diff == 0: # identical within precision assert abs(delta) <= tiny assert imin == 0 and imax == 0 and np.all(isort == [0, 1]) else: assert delta > 0 assert imin == 0 and imax == 1 and np.all(isort == [0, 1]) @given(sampled_from(STANDARD_TIME_SCALES), unreasonable_jd(), unreasonable_jd()) @example(scale='utc', jds_a=(2455000.0, 0.0), jds_b=(2443144.5, 0.5000462962962965)) @example(scale='utc', jds_a=(2459003.0, 0.267502885949074), jds_b=(2454657.001045462, 0.49895453779026877)) def test_timedelta_full_precision(scale, jds_a, jds_b): jd1_a, jd2_a = jds_a jd1_b, jd2_b = jds_b assume(scale != 'utc' or (2440000 < jd1_a+jd2_a < 2460000 and 2440000 < jd1_b+jd2_b < 2460000)) if scale == 'utc': # UTC subtraction implies a scale change, so possible rounding errors. tiny = 2 * dt_tiny else: tiny = dt_tiny t_a = Time(jd1_a, jd2_a, scale=scale, format="jd") t_b = Time(jd1_b, jd2_b, scale=scale, format="jd") dt = t_b - t_a assert dt != (t_b + tiny) - t_a with quiet_erfa(): assert_almost_equal(t_b-dt/2, t_a+dt/2, atol=2*dt_tiny, rtol=0, label="midpoint") assert_almost_equal(t_b+dt, t_a+2*dt, atol=2*dt_tiny, rtol=0, label="up") assert_almost_equal(t_b-2*dt, t_a-dt, atol=2*dt_tiny, rtol=0, label="down") @given(scale=sampled_from(STANDARD_TIME_SCALES), jds_a=unreasonable_jd(), jds_b=unreasonable_jd(), x=integers(1, 100), y=integers(1, 100)) def test_timedelta_full_precision_arithmetic(scale, jds_a, jds_b, x, y): jd1_a, jd2_a = jds_a jd1_b, jd2_b = jds_b t_a = Time(jd1_a, jd2_a, scale=scale, format="jd") t_b = Time(jd1_b, jd2_b, scale=scale, format="jd") with quiet_erfa(): try: dt = t_b - t_a dt_x = x*dt/(x+y) dt_y = y*dt/(x+y) assert_almost_equal(dt_x + dt_y, dt, atol=(x+y)*dt_tiny, rtol=0) except ErfaError: assume(scale != 'utc' or (2440000 < jd1_a+jd2_a < 2460000 and 2440000 < jd1_b+jd2_b < 2460000)) raise @given(scale1=sampled_from(STANDARD_TIME_SCALES), scale2=sampled_from(STANDARD_TIME_SCALES), jds_a=reasonable_jd(), jds_b=reasonable_jd()) def test_timedelta_conversion(scale1, scale2, jds_a, jds_b): jd1_a, jd2_a = jds_a jd1_b, jd2_b = jds_b # not translation invariant so can't convert TimeDelta assume('utc' not in [scale1, scale2]) # Conversions a problem but within UT1 it should work assume(('ut1' not in [scale1, scale2]) or scale1 == scale2) t_a = Time(jd1_a, jd2_a, scale=scale1, format="jd") t_b = Time(jd1_b, jd2_b, scale=scale2, format="jd") with quiet_erfa(): dt = t_b - t_a t_a_2 = getattr(t_a, scale2) t_b_2 = getattr(t_b, scale2) dt_2 = getattr(dt, scale2) assert_almost_equal(t_b_2 - t_a_2, dt_2, atol=dt_tiny, rtol=0, label="converted") # Implicit conversion assert_almost_equal(t_b_2 - t_a_2, dt, atol=dt_tiny, rtol=0, label="not converted") # UTC disagrees when there are leap seconds _utc_bad = [(pytest.param(s, marks=pytest.mark.xfail) if s == 'utc' else s) for s in STANDARD_TIME_SCALES] @given(datetimes(), datetimes()) # datetimes have microsecond resolution @example(dt1=datetime(1235, 1, 1, 0, 0), dt2=datetime(9950, 1, 1, 0, 0, 0, 890773)) @pytest.mark.parametrize("scale", _utc_bad) def test_datetime_difference_agrees_with_timedelta(scale, dt1, dt2): t1 = Time(dt1, scale=scale) t2 = Time(dt2, scale=scale) assert_almost_equal(t2-t1, TimeDelta(dt2-dt1, scale=None if scale == 'utc' else scale), atol=2*u.us) @given(days=integers(-3000*365, 3000*365), microseconds=integers(0, 24*60*60*1000000)) @pytest.mark.parametrize("scale", _utc_bad) def test_datetime_to_timedelta(scale, days, microseconds): td = timedelta(days=days, microseconds=microseconds) assert (TimeDelta(td, scale=scale) == TimeDelta(days, microseconds/(86400*1e6), scale=scale, format="jd")) @given(days=integers(-3000*365, 3000*365), microseconds=integers(0, 24*60*60*1000000)) @pytest.mark.parametrize("scale", _utc_bad) def test_datetime_timedelta_roundtrip(scale, days, microseconds): td = timedelta(days=days, microseconds=microseconds) assert td == TimeDelta(td, scale=scale).value @given(days=integers(-3000*365, 3000*365), day_frac=floats(0, 1)) @example(days=262144, day_frac=2.314815006343452e-11) @example(days=1048576, day_frac=1.157407503171726e-10) @pytest.mark.parametrize("scale", _utc_bad) def test_timedelta_datetime_roundtrip(scale, days, day_frac): td = TimeDelta(days, day_frac, format="jd", scale=scale) td.format = "datetime" assert_almost_equal(td, TimeDelta(td.value, scale=scale), atol=2*u.us) @given(integers(-3000*365, 3000*365), floats(0, 1)) @example(days=262144, day_frac=2.314815006343452e-11) @pytest.mark.parametrize("scale", _utc_bad) def test_timedelta_from_parts(scale, days, day_frac): kwargs = dict(format="jd", scale=scale) whole = TimeDelta(days, day_frac, **kwargs) from_parts = TimeDelta(days, **kwargs) + TimeDelta(day_frac, **kwargs) assert whole == from_parts def test_datetime_difference_agrees_with_timedelta_no_hypothesis(): scale = "tai" dt1 = datetime(1235, 1, 1, 0, 0) dt2 = datetime(9950, 1, 1, 0, 0, 0, 890773) t1 = Time(dt1, scale=scale) t2 = Time(dt2, scale=scale) assert(abs((t2-t1) - TimeDelta(dt2-dt1, scale=scale)) < 1*u.us) # datetimes have microsecond resolution @given(datetimes(), timedeltas()) @example(dt=datetime(2000, 1, 1, 0, 0), td=timedelta(days=-397683, microseconds=2)) @example(dt=datetime(2179, 1, 1, 0, 0), td=timedelta(days=-795365, microseconds=53)) @example(dt=datetime(2000, 1, 1, 0, 0), td=timedelta(days=1590729, microseconds=10)) @example(dt=datetime(4357, 1, 1, 0, 0), td=timedelta(days=-1590729, microseconds=107770)) @example(dt=datetime(4357, 1, 1, 0, 0, 0, 29), td=timedelta(days=-1590729, microseconds=746292)) @pytest.mark.parametrize("scale", _utc_bad) def test_datetime_timedelta_sum(scale, dt, td): try: dt + td except OverflowError: assume(False) dt_a = Time(dt, scale=scale) td_a = TimeDelta(td, scale=None if scale == 'utc' else scale) assert_almost_equal(dt_a+td_a, Time(dt+td, scale=scale), atol=2*u.us) @given(jds=reasonable_jd(), lat1=floats(-90, 90), lat2=floats(-90, 90), lon=floats(-180, 180)) @pytest.mark.parametrize("kind", ["apparent", "mean"]) def test_sidereal_lat_independent(iers_b, kind, jds, lat1, lat2, lon): jd1, jd2 = jds t1 = Time(jd1, jd2, scale="ut1", format="jd", location=(lon, lat1)) t2 = Time(jd1, jd2, scale="ut1", format="jd", location=(lon, lat2)) try: assert_almost_equal(t1.sidereal_time(kind), t2.sidereal_time(kind), atol=1*u.uas) except iers.IERSRangeError: assume(False) @given(jds=reasonable_jd(), lat=floats(-90, 90), lon=floats(-180, 180), lon_delta=floats(-360, 360)) @pytest.mark.parametrize("kind", ["apparent", "mean"]) def test_sidereal_lon_independent(iers_b, kind, jds, lat, lon, lon_delta): jd1, jd2 = jds t1 = Time(jd1, jd2, scale="ut1", format="jd", location=(lon, lat)) t2 = Time(jd1, jd2, scale="ut1", format="jd", location=(lon+lon_delta, lat)) try: diff = t1.sidereal_time(kind) + lon_delta*u.degree - t2.sidereal_time(kind) except iers.IERSRangeError: assume(False) else: expected_degrees = (diff.to_value(u.degree) + 180) % 360 assert_almost_equal(expected_degrees, 180, atol=1/(60*60*1000))
d4af71513c067381ba72440689d28bada4affb3e71ec83b4b155937bd2cdefd8
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest from astropy import units as u from astropy.coordinates import EarthLocation, SkyCoord, solar_system_ephemeris from astropy.time import Time, TimeDelta from astropy.utils import iers from astropy.utils.compat.optional_deps import HAS_JPLEPHEM # noqa class TestHelioBaryCentric: """ Verify time offsets to the solar system barycentre and the heliocentre. Uses the WHT observing site. Tests are against values returned at time of initial creation of these routines. They agree to an independent SLALIB based implementation to 20 microseconds. """ @classmethod def setup_class(cls): cls.orig_auto_download = iers.conf.auto_download iers.conf.auto_download = False @classmethod def teardown_class(cls): iers.conf.auto_download = cls.orig_auto_download def setup(self): wht = EarthLocation(342.12 * u.deg, 28.758333333333333 * u.deg, 2327 * u.m) self.obstime = Time("2013-02-02T23:00", location=wht) self.obstime2 = Time("2013-08-02T23:00", location=wht) self.obstimeArr = Time(["2013-02-02T23:00", "2013-08-02T23:00"], location=wht) self.star = SkyCoord("08:08:08 +32:00:00", unit=(u.hour, u.degree), frame='icrs') def test_heliocentric(self): hval = self.obstime.light_travel_time(self.star, 'heliocentric') assert isinstance(hval, TimeDelta) assert hval.scale == 'tdb' assert abs(hval - 461.43037870502235 * u.s) < 1. * u.us def test_barycentric(self): bval = self.obstime.light_travel_time(self.star, 'barycentric') assert isinstance(bval, TimeDelta) assert bval.scale == 'tdb' assert abs(bval - 460.58538779827836 * u.s) < 1. * u.us def test_arrays(self): bval1 = self.obstime.light_travel_time(self.star, 'barycentric') bval2 = self.obstime2.light_travel_time(self.star, 'barycentric') bval_arr = self.obstimeArr.light_travel_time(self.star, 'barycentric') hval1 = self.obstime.light_travel_time(self.star, 'heliocentric') hval2 = self.obstime2.light_travel_time(self.star, 'heliocentric') hval_arr = self.obstimeArr.light_travel_time(self.star, 'heliocentric') assert hval_arr[0] - hval1 < 1. * u.us assert hval_arr[1] - hval2 < 1. * u.us assert bval_arr[0] - bval1 < 1. * u.us assert bval_arr[1] - bval2 < 1. * u.us @pytest.mark.remote_data @pytest.mark.skipif('not HAS_JPLEPHEM') def test_ephemerides(self): bval1 = self.obstime.light_travel_time(self.star, 'barycentric') with solar_system_ephemeris.set('jpl'): bval2 = self.obstime.light_travel_time(self.star, 'barycentric', ephemeris='jpl') # should differ by less than 0.1 ms, but not be the same assert abs(bval1 - bval2) < 1. * u.ms assert abs(bval1 - bval2) > 1. * u.us
b1376f9171935231e00d05d80fa6fcb680186949231c001985c38210a3313ca6
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pickle import numpy as np from astropy.time import Time class TestPickle: """Basic pickle test of time""" def test_pickle(self): times = ['1999-01-01 00:00:00.123456789', '2010-01-01 00:00:00'] t1 = Time(times, scale='utc') for prot in range(pickle.HIGHEST_PROTOCOL): t1d = pickle.dumps(t1, prot) t1l = pickle.loads(t1d) assert np.all(t1l == t1) t2 = Time('2012-06-30 12:00:00', scale='utc') for prot in range(pickle.HIGHEST_PROTOCOL): t2d = pickle.dumps(t2, prot) t2l = pickle.loads(t2d) assert t2l == t2
a26abdde5ad5426b52ee90ca5a406a2c36218ba3e5951711c5ce2fa21df018dc
# Licensed under a 3-clause BSD style license - see LICENSE.rst from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timedelta import pytest import erfa from astropy.utils import iers from astropy.utils.exceptions import AstropyWarning import astropy.time.core from astropy.time import update_leap_seconds, Time class TestUpdateLeapSeconds: def setup(self): self.built_in = iers.LeapSeconds.from_iers_leap_seconds() self.erfa_ls = iers.LeapSeconds.from_erfa() now = datetime.now() self.good_enough = now + timedelta(150) def teardown(self): self.erfa_ls.update_erfa_leap_seconds(initialize_erfa=True) def test_auto_update_leap_seconds(self): # Sanity check. assert erfa.dat(2018, 1, 1, 0.) == 37.0 # Set expired leap seconds expired = self.erfa_ls[self.erfa_ls['year'] < 2017] expired.update_erfa_leap_seconds(initialize_erfa='empty') # Check the 2017 leap second is indeed missing. assert erfa.dat(2018, 1, 1, 0.) == 36.0 # Update with missing leap seconds. n_update = update_leap_seconds([iers.IERS_LEAP_SECOND_FILE]) assert n_update >= 1 assert erfa.leap_seconds.expires == self.built_in.expires assert erfa.dat(2018, 1, 1, 0.) == 37.0 # Doing it again does not change anything n_update2 = update_leap_seconds([iers.IERS_LEAP_SECOND_FILE]) assert n_update2 == 0 assert erfa.dat(2018, 1, 1, 0.) == 37.0 @pytest.mark.remote_data def test_never_expired_if_connected(self): assert self.erfa_ls.expires > datetime.now() assert self.erfa_ls.expires >= self.good_enough @pytest.mark.remote_data def test_auto_update_always_good(self): self.erfa_ls.update_erfa_leap_seconds(initialize_erfa='only') update_leap_seconds() assert not erfa.leap_seconds.expired assert erfa.leap_seconds.expires > self.good_enough def test_auto_update_bad_file(self): with pytest.warns(AstropyWarning, match='FileNotFound'): update_leap_seconds(['nonsense']) def test_auto_update_corrupt_file(self, tmpdir): bad_file = str(tmpdir.join('no_expiration')) with open(iers.IERS_LEAP_SECOND_FILE) as fh: lines = fh.readlines() with open(bad_file, 'w') as fh: fh.write('\n'.join([line for line in lines if not line.startswith('#')])) with pytest.warns(AstropyWarning, match='ValueError.*did not find expiration'): update_leap_seconds([bad_file]) def test_auto_update_expired_file(self, tmpdir): # Set up expired ERFA leap seconds. expired = self.erfa_ls[self.erfa_ls['year'] < 2017] expired.update_erfa_leap_seconds(initialize_erfa='empty') # Create similarly expired file. expired_file = str(tmpdir.join('expired.dat')) with open(expired_file, 'w') as fh: fh.write('\n'.join(['# File expires on 28 June 2010'] + [str(item) for item in expired])) with pytest.warns(iers.IERSStaleWarning): update_leap_seconds(['erfa', expired_file]) def test_init_thread_safety(self, monkeypatch): # Set up expired ERFA leap seconds. expired = self.erfa_ls[self.erfa_ls['year'] < 2017] expired.update_erfa_leap_seconds(initialize_erfa='empty') # Force re-initialization, even if another test already did it monkeypatch.setattr(astropy.time.core, '_LEAP_SECONDS_CHECK', astropy.time.core._LeapSecondsCheck.NOT_STARTED) workers = 4 with ThreadPoolExecutor(max_workers=workers) as executor: futures = [executor.submit(lambda: str(Time('2019-01-01 00:00:00.000').tai)) for i in range(workers)] results = [future.result() for future in futures] assert results == ['2019-01-01 00:00:37.000'] * workers
788cea655430d6b91280e438295cd1078bdc85bd2482369ee2daed7400074ec9
# Licensed under a 3-clause BSD style license - see LICENSE.rst import functools import pytest import numpy as np from astropy.time import Time from astropy.utils.iers import conf as iers_conf from astropy.utils.iers import iers # used in testing allclose_jd = functools.partial(np.allclose, rtol=0, atol=1e-9) allclose_sec = functools.partial(np.allclose, rtol=1e-15, atol=1e-4) # 0.1 ms atol; IERS-B files change at that level. try: iers.IERS_A.open() # check if IERS_A is available except OSError: HAS_IERS_A = False else: HAS_IERS_A = True def do_ut1_prediction_tst(iers_type): tnow = Time.now() iers_tab = iers_type.open() tnow.delta_ut1_utc, status = iers_tab.ut1_utc(tnow, return_status=True) assert status == iers.FROM_IERS_A_PREDICTION tnow_ut1_jd = tnow.ut1.jd assert tnow_ut1_jd != tnow.jd delta_ut1_utc = tnow.delta_ut1_utc with iers.earth_orientation_table.set(iers_type.open()): delta2, status2 = tnow.get_delta_ut1_utc(return_status=True) assert status2 == status assert delta2.to_value('s') == delta_ut1_utc tnow_ut1 = tnow.ut1 assert tnow_ut1._delta_ut1_utc == delta_ut1_utc assert tnow_ut1.jd != tnow.jd @pytest.mark.remote_data class TestTimeUT1Remote: def setup_class(cls): # Need auto_download so that IERS_B won't be loaded and cause tests to # fail. iers_conf.auto_download = True def teardown_class(cls): # This setting is to be consistent with astropy/conftest.py iers_conf.auto_download = False def test_utc_to_ut1(self): "Test conversion of UTC to UT1, making sure to include a leap second""" t = Time(['2012-06-30 12:00:00', '2012-06-30 23:59:59', '2012-06-30 23:59:60', '2012-07-01 00:00:00', '2012-07-01 12:00:00'], scale='utc') t_ut1_jd = t.ut1.jd t_comp = np.array([2456108.9999932079, 2456109.4999816339, 2456109.4999932083, 2456109.5000047823, 2456110.0000047833]) assert allclose_jd(t_ut1_jd, t_comp) t_back = t.ut1.utc assert allclose_jd(t.jd, t_back.jd) tnow = Time.now() tnow.ut1 def test_ut1_iers_auto(self): do_ut1_prediction_tst(iers.IERS_Auto) class TestTimeUT1: """Test Time.ut1 using IERS tables""" def test_ut1_to_utc(self): """Also test the reverse, around the leap second (round-trip test closes #2077)""" with iers_conf.set_temp('auto_download', False): t = Time(['2012-06-30 12:00:00', '2012-06-30 23:59:59', '2012-07-01 00:00:00', '2012-07-01 00:00:01', '2012-07-01 12:00:00'], scale='ut1') t_utc_jd = t.utc.jd t_comp = np.array([2456109.0000010049, 2456109.4999836441, 2456109.4999952177, 2456109.5000067917, 2456109.9999952167]) assert allclose_jd(t_utc_jd, t_comp) t_back = t.utc.ut1 assert allclose_jd(t.jd, t_back.jd) def test_empty_ut1(self): """Testing for a zero-length Time object from UTC to UT1 when an empty array is passed""" from astropy import units as u with iers_conf.set_temp('auto_download', False): t = Time(['2012-06-30 12:00:00']) + np.arange(24) * u.hour t_empty = t[[]].ut1 assert isinstance(t_empty, Time) assert t_empty.scale == 'ut1' assert t_empty.size == 0 def test_delta_ut1_utc(self): """Accessing delta_ut1_utc should try to get it from IERS (closes #1924 partially)""" with iers_conf.set_temp('auto_download', False): t = Time('2012-06-30 12:00:00', scale='utc') assert not hasattr(t, '_delta_ut1_utc') # accessing delta_ut1_utc calculates it assert allclose_sec(t.delta_ut1_utc, -0.58682110003124965) # and keeps it around assert allclose_sec(t._delta_ut1_utc, -0.58682110003124965) class TestTimeUT1SpecificIERSTable: @pytest.mark.skipif('not HAS_IERS_A') def test_ut1_iers_A(self): do_ut1_prediction_tst(iers.IERS_A) def test_ut1_iers_B(self): tnow = Time.now() iers_b = iers.IERS_B.open() delta1, status1 = tnow.get_delta_ut1_utc(iers_b, return_status=True) assert status1 == iers.TIME_BEYOND_IERS_RANGE with iers.earth_orientation_table.set(iers.IERS_B.open()): delta2, status2 = tnow.get_delta_ut1_utc(return_status=True) assert status2 == status1 with pytest.raises(iers.IERSRangeError): tnow.ut1
3771fc9f53d7985e453a4bd8a46274c8a382c65f89ca6cbdc74211c6376b44ea
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest from astropy.time import Time class TestGuess: """Test guessing the input value format""" def test_guess1(self): times = ['1999-01-01 00:00:00.123456789', '2010-01-01 00:00:00'] t = Time(times, scale='utc') assert (repr(t) == "<Time object: scale='utc' format='iso' " "value=['1999-01-01 00:00:00.123' '2010-01-01 00:00:00.000']>") def test_guess2(self): times = ['1999-01-01 00:00:00.123456789', '2010-01 00:00:00'] with pytest.raises(ValueError): Time(times, scale='utc') def test_guess3(self): times = ['1999:001:00:00:00.123456789', '2010:001'] t = Time(times, scale='utc') assert (repr(t) == "<Time object: scale='utc' format='yday' " "value=['1999:001:00:00:00.123' '2010:001:00:00:00.000']>") def test_guess4(self): times = [10, 20] with pytest.raises(ValueError): Time(times, scale='utc')
d224a387c65aeea953c3eb8cbe4cbbe2bdab1249addf4bcde6f5a0f91c3e80b4
# Licensed under a 3-clause BSD style license - see LICENSE.rst import functools import pytest import numpy as np from astropy.time import Time, TimeDelta from astropy import units as u from astropy.table import Column allclose_sec = functools.partial(np.allclose, rtol=2. ** -52, atol=2. ** -52 * 24 * 3600) # 20 ps atol class TestTimeQuantity: """Test Interaction of Time with Quantities""" def test_valid_quantity_input(self): """Test Time formats that are allowed to take quantity input.""" q = 2450000.125 * u.day t1 = Time(q, format='jd', scale='utc') assert t1.value == q.value q2 = q.to(u.second) t2 = Time(q2, format='jd', scale='utc') assert t2.value == q.value == q2.to_value(u.day) q3 = q - 2400000.5 * u.day t3 = Time(q3, format='mjd', scale='utc') assert t3.value == q3.value # test we can deal with two quantity arguments, with different units qs = 24. * 36. * u.second t4 = Time(q3, qs, format='mjd', scale='utc') assert t4.value == (q3 + qs).to_value(u.day) qy = 1990. * u.yr ty1 = Time(qy, format='jyear', scale='utc') assert ty1.value == qy.value ty2 = Time(qy.to(u.day), format='jyear', scale='utc') assert ty2.value == qy.value qy2 = 10. * u.yr tcxc = Time(qy2, format='cxcsec') assert tcxc.value == qy2.to_value(u.second) tgps = Time(qy2, format='gps') assert tgps.value == qy2.to_value(u.second) tunix = Time(qy2, format='unix') assert tunix.value == qy2.to_value(u.second) qd = 2000. * 365. * u.day tplt = Time(qd, format='plot_date', scale='utc') assert tplt.value == qd.value def test_invalid_quantity_input(self): with pytest.raises(u.UnitsError): Time(2450000. * u.m, format='jd', scale='utc') with pytest.raises(u.UnitsError): Time(2450000. * u.dimensionless_unscaled, format='jd', scale='utc') def test_column_with_and_without_units(self): """Ensure a Column without a unit is treated as an array [#3648]""" a = np.arange(50000., 50010.) ta = Time(a, format='mjd') c1 = Column(np.arange(50000., 50010.), name='mjd') tc1 = Time(c1, format='mjd') assert np.all(ta == tc1) c2 = Column(np.arange(50000., 50010.), name='mjd', unit='day') tc2 = Time(c2, format='mjd') assert np.all(ta == tc2) c3 = Column(np.arange(50000., 50010.), name='mjd', unit='m') with pytest.raises(u.UnitsError): Time(c3, format='mjd') def test_no_quantity_input_allowed(self): """Time formats that are not allowed to take Quantity input.""" qy = 1990. * u.yr for fmt in ('iso', 'yday', 'datetime', 'byear', 'byear_str', 'jyear_str'): with pytest.raises(ValueError): Time(qy, format=fmt, scale='utc') def test_valid_quantity_operations(self): """Check that adding a time-valued quantity to a Time gives a Time""" t0 = Time(100000., format='cxcsec') q1 = 10. * u.second t1 = t0 + q1 assert isinstance(t1, Time) assert t1.value == t0.value + q1.to_value(u.second) q2 = 1. * u.day t2 = t0 - q2 assert allclose_sec(t2.value, t0.value - q2.to_value(u.second)) # check broadcasting q3 = np.arange(15.).reshape(3, 5) * u.hour t3 = t0 - q3 assert t3.shape == q3.shape assert allclose_sec(t3.value, t0.value - q3.to_value(u.second)) def test_invalid_quantity_operations(self): """Check that comparisons of Time with quantities does not work (even for time-like, since we cannot compare Time to TimeDelta)""" with pytest.raises(TypeError): Time(100000., format='cxcsec') > 10. * u.m with pytest.raises(TypeError): Time(100000., format='cxcsec') > 10. * u.second class TestTimeDeltaQuantity: """Test interaction of TimeDelta with Quantities""" def test_valid_quantity_input(self): """Test that TimeDelta can take quantity input.""" q = 500.25 * u.day dt1 = TimeDelta(q, format='jd') assert dt1.value == q.value dt2 = TimeDelta(q, format='sec') assert dt2.value == q.to_value(u.second) dt3 = TimeDelta(q) assert dt3.value == q.value def test_invalid_quantity_input(self): with pytest.raises(u.UnitsError): TimeDelta(2450000. * u.m, format='jd') with pytest.raises(u.UnitsError): Time(2450000. * u.dimensionless_unscaled, format='jd', scale='utc') with pytest.raises(TypeError): TimeDelta(100, format='sec') > 10. * u.m def test_quantity_output(self): q = 500.25 * u.day dt = TimeDelta(q) assert dt.to(u.day) == q assert dt.to_value(u.day) == q.value assert dt.to_value('day') == q.value assert dt.to(u.second).value == q.to_value(u.second) assert dt.to_value(u.second) == q.to_value(u.second) assert dt.to_value('s') == q.to_value(u.second) # Following goes through "format", but should be the same. assert dt.to_value('sec') == q.to_value(u.second) def test_quantity_output_errors(self): dt = TimeDelta(250., format='sec') with pytest.raises(u.UnitsError): dt.to(u.m) with pytest.raises(u.UnitsError): dt.to_value(u.m) with pytest.raises(u.UnitsError): dt.to_value(unit=u.m) with pytest.raises(ValueError, match=("not one of the known formats.*" "failed to parse as a unit")): dt.to_value('parrot') with pytest.raises(TypeError): dt.to_value('sec', unit=u.s) with pytest.raises(TypeError): # TODO: would be nice to make this work! dt.to_value(u.s, subfmt='str') def test_valid_quantity_operations1(self): """Check adding/substracting/comparing a time-valued quantity works with a TimeDelta. Addition/subtraction should give TimeDelta""" t0 = TimeDelta(106400., format='sec') q1 = 10. * u.second t1 = t0 + q1 assert isinstance(t1, TimeDelta) assert t1.value == t0.value + q1.to_value(u.second) q2 = 1. * u.day t2 = t0 - q2 assert isinstance(t2, TimeDelta) assert allclose_sec(t2.value, t0.value - q2.to_value(u.second)) # now comparisons assert t0 > q1 assert t0 < 1. * u.yr # and broadcasting q3 = np.arange(12.).reshape(4, 3) * u.hour t3 = t0 + q3 assert isinstance(t3, TimeDelta) assert t3.shape == q3.shape assert allclose_sec(t3.value, t0.value + q3.to_value(u.second)) def test_valid_quantity_operations2(self): """Check that TimeDelta is treated as a quantity where possible.""" t0 = TimeDelta(100000., format='sec') f = 1. / t0 assert isinstance(f, u.Quantity) assert f.unit == 1. / u.day g = 10. * u.m / u.second**2 v = t0 * g assert isinstance(v, u.Quantity) assert u.allclose(v, t0.sec * g.value * u.m / u.second) q = np.log10(t0 / u.second) assert isinstance(q, u.Quantity) assert q.value == np.log10(t0.sec) s = 1. * u.m v = s / t0 assert isinstance(v, u.Quantity) assert u.allclose(v, 1. / t0.sec * u.m / u.s) t = 1. * u.s t2 = t0 * t assert isinstance(t2, u.Quantity) assert u.allclose(t2, t0.sec * u.s ** 2) t3 = [1] / t0 assert isinstance(t3, u.Quantity) assert u.allclose(t3, 1 / (t0.sec * u.s)) # broadcasting t1 = TimeDelta(np.arange(100000., 100012.).reshape(6, 2), format='sec') f = np.array([1., 2.]) * u.cycle * u.Hz phase = f * t1 assert isinstance(phase, u.Quantity) assert phase.shape == t1.shape assert u.allclose(phase, t1.sec * f.value * u.cycle) q = t0 * t1 assert isinstance(q, u.Quantity) assert np.all(q == t0.to(u.day) * t1.to(u.day)) q = t1 / t0 assert isinstance(q, u.Quantity) assert np.all(q == t1.to(u.day) / t0.to(u.day)) def test_valid_quantity_operations3(self): """Test a TimeDelta remains one if possible.""" t0 = TimeDelta(10., format='jd') q = 10. * u.one t1 = q * t0 assert isinstance(t1, TimeDelta) assert t1 == TimeDelta(100., format='jd') t2 = t0 * q assert isinstance(t2, TimeDelta) assert t2 == TimeDelta(100., format='jd') t3 = t0 / q assert isinstance(t3, TimeDelta) assert t3 == TimeDelta(1., format='jd') q2 = 1. * u.percent t4 = t0 * q2 assert isinstance(t4, TimeDelta) assert abs(t4 - TimeDelta(0.1, format='jd')) < 1. * u.ns q3 = 1. * u.hr / (36. * u.s) t5 = q3 * t0 assert isinstance(t4, TimeDelta) assert abs(t5 - TimeDelta(1000., format='jd')) < 1. * u.ns # Test multiplication with a unit. t6 = t0 * u.one assert isinstance(t6, TimeDelta) assert t6 == TimeDelta(10., format='jd') t7 = u.one * t0 assert isinstance(t7, TimeDelta) assert t7 == TimeDelta(10., format='jd') t8 = t0 * '' assert isinstance(t8, TimeDelta) assert t8 == TimeDelta(10., format='jd') t9 = '' * t0 assert isinstance(t9, TimeDelta) assert t9 == TimeDelta(10., format='jd') t10 = t0 / u.one assert isinstance(t10, TimeDelta) assert t6 == TimeDelta(10., format='jd') t11 = t0 / '' assert isinstance(t11, TimeDelta) assert t11 == TimeDelta(10., format='jd') t12 = t0 / [1] assert isinstance(t12, TimeDelta) assert t12 == TimeDelta(10., format='jd') t13 = [1] * t0 assert isinstance(t13, TimeDelta) assert t13 == TimeDelta(10., format='jd') def test_invalid_quantity_operations(self): """Check comparisons of TimeDelta with non-time quantities fails.""" with pytest.raises(TypeError): TimeDelta(100000., format='sec') > 10. * u.m def test_invalid_quantity_operations2(self): """Check that operations with non-time/quantity fail.""" td = TimeDelta(100000., format='sec') with pytest.raises(TypeError): td * object() with pytest.raises(TypeError): td / object() def test_invalid_quantity_broadcast(self): """Check broadcasting rules in interactions with Quantity.""" t0 = TimeDelta(np.arange(12.).reshape(4, 3), format='sec') with pytest.raises(ValueError): t0 + np.arange(4.) * u.s class TestDeltaAttributes: def test_delta_ut1_utc(self): t = Time('2010-01-01 00:00:00', format='iso', scale='utc', precision=6) t.delta_ut1_utc = 0.3 * u.s assert t.ut1.iso == '2010-01-01 00:00:00.300000' t.delta_ut1_utc = 0.4 / 60. * u.minute assert t.ut1.iso == '2010-01-01 00:00:00.400000' with pytest.raises(u.UnitsError): t.delta_ut1_utc = 0.4 * u.m # Also check that a TimeDelta works. t.delta_ut1_utc = TimeDelta(0.3, format='sec') assert t.ut1.iso == '2010-01-01 00:00:00.300000' t.delta_ut1_utc = TimeDelta(0.5 / 24. / 3600., format='jd') assert t.ut1.iso == '2010-01-01 00:00:00.500000' def test_delta_tdb_tt(self): t = Time('2010-01-01 00:00:00', format='iso', scale='tt', precision=6) t.delta_tdb_tt = 20. * u.second assert t.tdb.iso == '2010-01-01 00:00:20.000000' t.delta_tdb_tt = 30. / 60. * u.minute assert t.tdb.iso == '2010-01-01 00:00:30.000000' with pytest.raises(u.UnitsError): t.delta_tdb_tt = 0.4 * u.m # Also check that a TimeDelta works. t.delta_tdb_tt = TimeDelta(40., format='sec') assert t.tdb.iso == '2010-01-01 00:00:40.000000' t.delta_tdb_tt = TimeDelta(50. / 24. / 3600., format='jd') assert t.tdb.iso == '2010-01-01 00:00:50.000000' @pytest.mark.parametrize('q1, q2', ((5e8 * u.s, None), (5e17 * u.ns, None), (4e8 * u.s, 1e17 * u.ns), (4e14 * u.us, 1e17 * u.ns))) def test_quantity_conversion_rounding(q1, q2): """Check that no rounding errors are incurred by unit conversion. This occurred before as quantities in seconds were converted to days before trying to split them into two-part doubles. See gh-7622. """ t = Time('2001-01-01T00:00:00.', scale='tai') expected = Time('2016-11-05T00:53:20.', scale='tai') if q2 is None: t0 = t + q1 else: t0 = t + q1 + q2 assert abs(t0 - expected) < 20 * u.ps dt1 = TimeDelta(q1, q2) t1 = t + dt1 assert abs(t1 - expected) < 20 * u.ps dt2 = TimeDelta(q1, q2, format='sec') t2 = t + dt2 assert abs(t2 - expected) < 20 * u.ps
4d7d8df3270a0a28fc5054107f661bf7285441844bf572c67c775001a778fd2f
# Licensed under a 3-clause BSD style license - see LICENSE.rst import operator import pytest import numpy as np from astropy.time import Time, TimeDelta import astropy.units as u class TestTimeComparisons: """Test Comparisons of Time and TimeDelta classes""" def setup(self): self.t1 = Time(np.arange(49995, 50005), format='mjd', scale='utc') self.t2 = Time(np.arange(49000, 51000, 200), format='mjd', scale='utc') def test_miscompares(self): """ If an incompatible object is compared to a Time object, == should return False and != should return True. All other comparison operators should raise a TypeError. """ t1 = Time('J2000', scale='utc') for op, op_str in ((operator.ge, '>='), (operator.gt, '>'), (operator.le, '<='), (operator.lt, '<')): with pytest.raises(TypeError): op(t1, None) # Keep == and != as they are specifically meant to test Time.__eq__ # and Time.__ne__ assert (t1 == None) is False # noqa assert (t1 != None) is True # noqa def test_time(self): t1_lt_t2 = self.t1 < self.t2 assert np.all(t1_lt_t2 == np.array([False, False, False, False, False, False, True, True, True, True])) t1_ge_t2 = self.t1 >= self.t2 assert np.all(t1_ge_t2 != t1_lt_t2) t1_le_t2 = self.t1 <= self.t2 assert np.all(t1_le_t2 == np.array([False, False, False, False, False, True, True, True, True, True])) t1_gt_t2 = self.t1 > self.t2 assert np.all(t1_gt_t2 != t1_le_t2) t1_eq_t2 = self.t1 == self.t2 assert np.all(t1_eq_t2 == np.array([False, False, False, False, False, True, False, False, False, False])) t1_ne_t2 = self.t1 != self.t2 assert np.all(t1_ne_t2 != t1_eq_t2) t1_0_gt_t2_0 = self.t1[0] > self.t2[0] assert t1_0_gt_t2_0 is True t1_0_gt_t2 = self.t1[0] > self.t2 assert np.all(t1_0_gt_t2 == np.array([True, True, True, True, True, False, False, False, False, False])) t1_gt_t2_0 = self.t1 > self.t2[0] assert np.all(t1_gt_t2_0 == np.array([True, True, True, True, True, True, True, True, True, True])) def test_time_boolean(self): t1_0_gt_t2_0 = self.t1[0] > self.t2[0] assert t1_0_gt_t2_0 is True def test_timedelta(self): dt = self.t2 - self.t1 with pytest.raises(TypeError): self.t1 > dt dt_gt_td0 = dt > TimeDelta(0., format='sec') assert np.all(dt_gt_td0 == np.array([False, False, False, False, False, False, True, True, True, True])) @pytest.mark.parametrize('swap', [True, False]) @pytest.mark.parametrize('time_delta', [True, False]) def test_isclose_time(swap, time_delta): """Test functionality of Time.isclose() method. Run every test with 2 args in original order and swapped, and using Quantity or TimeDelta for atol (when provided).""" def isclose_swap(t1, t2, **kwargs): if swap: t1, t2 = t2, t1 if 'atol' in kwargs and time_delta: kwargs['atol'] = TimeDelta(kwargs['atol']) return t1.isclose(t2, **kwargs) # Start with original demonstration from #8742. In this issue both t2 == t1 # and t3 == t1 give False, but this may change with a newer ERFA. t1 = Time("2018-07-24T10:41:56.807015240") t2 = t1 + 0.0 * u.s t3 = t1 + TimeDelta(0.0 * u.s) assert isclose_swap(t1, t2) assert isclose_swap(t1, t3) t2 = t1 + 1 * u.s assert isclose_swap(t1, t2, atol=1.5 / 86400 * u.day) # Test different unit assert not isclose_swap(t1, t2, atol=0.5 / 86400 * u.day) t2 = t1 + [-1, 0, 2] * u.s assert np.all(isclose_swap(t1, t2, atol=1.5 * u.s) == [True, True, False]) t2 = t1 + 3 * np.finfo(float).eps * u.day assert not isclose_swap(t1, t2) def test_isclose_time_exceptions(): t1 = Time('2020:001') t2 = t1 + 1 * u.s match = "'other' argument must support subtraction with Time" with pytest.raises(TypeError, match=match): t1.isclose(1.5) match = "'atol' argument must be a Quantity or TimeDelta instance, got float instead" with pytest.raises(TypeError, match=match): t1.isclose(t2, 1.5) @pytest.mark.parametrize('swap', [True, False]) @pytest.mark.parametrize('time_delta', [True, False]) @pytest.mark.parametrize('other_quantity', [True, False]) def test_isclose_timedelta(swap, time_delta, other_quantity): """Test functionality of TimeDelta.isclose() method. Run every test with 2 args in original order and swapped, and using Quantity or TimeDelta for atol (when provided), and using Quantity or TimeDelta for the other argument.""" def isclose_swap(t1, t2, **kwargs): if swap: t1, t2 = t2, t1 if 'atol' in kwargs and time_delta: kwargs['atol'] = TimeDelta(kwargs['atol']) return t1.isclose(t2, **kwargs) def isclose_other_quantity(t1, t2, **kwargs): if other_quantity: t2 = t2.to(u.day) if 'atol' in kwargs and time_delta: kwargs['atol'] = TimeDelta(kwargs['atol']) return t1.isclose(t2, **kwargs) t1 = TimeDelta(1.0 * u.s) t2 = t1 + 0.0 * u.s t3 = t1 + TimeDelta(0.0 * u.s) assert isclose_swap(t1, t2) assert isclose_swap(t1, t3) assert isclose_other_quantity(t1, t2) assert isclose_other_quantity(t1, t3) t2 = t1 + 1 * u.s assert isclose_swap(t1, t2, atol=1.5 / 86400 * u.day) assert not isclose_swap(t1, t2, atol=0.5 / 86400 * u.day) assert isclose_other_quantity(t1, t2, atol=1.5 / 86400 * u.day) assert not isclose_other_quantity(t1, t2, atol=0.5 / 86400 * u.day) t1 = TimeDelta(0 * u.s) t2 = t1 + [-1, 0, 2] * u.s assert np.all(isclose_swap(t1, t2, atol=1.5 * u.s) == [True, True, False]) assert np.all(isclose_other_quantity(t1, t2, atol=1.5 * u.s) == [True, True, False]) # Check with rtol # 1 * 0.6 + 0.5 = 1.1 --> 1 <= 1.1 --> True # 0 * 0.6 + 0.5 = 0.5 --> 0 <= 0.5 --> True # 2 * 0.6 + 0.5 = 1.7 --> 2 <= 1.7 --> False assert np.all(t1.isclose(t2, atol=0.5 * u.s, rtol=0.6) == [True, True, False]) t2 = t1 + 2 * np.finfo(float).eps * u.day assert not isclose_swap(t1, t2) assert not isclose_other_quantity(t1, t2) def test_isclose_timedelta_exceptions(): t1 = TimeDelta(1 * u.s) t2 = t1 + 1 * u.s match = "other' argument must support conversion to days" with pytest.raises(TypeError, match=match): t1.isclose(1.5) match = "'atol' argument must be a Quantity or TimeDelta instance, got float instead" with pytest.raises(TypeError, match=match): t1.isclose(t2, 1.5)
280186d23a5de0e9a6f9c04aa4b0fcd588812b2a9b03c58e342b6461868a907c
# Licensed under a 3-clause BSD style license - see LICENSE.rst import warnings import itertools import copy import pytest import numpy as np from astropy.time import Time from astropy.utils import iers from astropy.units.quantity_helper.function_helpers import ARRAY_FUNCTION_ENABLED needs_array_function = pytest.mark.xfail( not ARRAY_FUNCTION_ENABLED, reason="Needs __array_function__ support") def assert_time_all_equal(t1, t2): """Checks equality of shape and content.""" assert t1.shape == t2.shape assert np.all(t1 == t2) class ShapeSetup: def setup_class(cls): mjd = np.arange(50000, 50010) frac = np.arange(0., 0.999, 0.2) frac_masked = np.ma.array(frac) frac_masked[1] = np.ma.masked cls.t0 = { 'not_masked': Time(mjd[:, np.newaxis] + frac, format='mjd', scale='utc'), 'masked': Time(mjd[:, np.newaxis] + frac_masked, format='mjd', scale='utc') } cls.t1 = { 'not_masked': Time(mjd[:, np.newaxis] + frac, format='mjd', scale='utc', location=('45d', '50d')), 'masked': Time(mjd[:, np.newaxis] + frac_masked, format='mjd', scale='utc', location=('45d', '50d')), } cls.t2 = { 'not_masked': Time(mjd[:, np.newaxis] + frac, format='mjd', scale='utc', location=(np.arange(len(frac)), np.arange(len(frac)))), 'masked': Time(mjd[:, np.newaxis] + frac_masked, format='mjd', scale='utc', location=(np.arange(len(frac_masked)), np.arange(len(frac_masked)))), } def create_data(self, use_mask): self.t0 = self.__class__.t0[use_mask] self.t1 = self.__class__.t1[use_mask] self.t2 = self.__class__.t2[use_mask] @pytest.mark.parametrize('use_mask', ('masked', 'not_masked')) class TestManipulation(ShapeSetup): """Manipulation of Time objects, ensuring attributes are done correctly.""" def test_ravel(self, use_mask): self.create_data(use_mask) t0_ravel = self.t0.ravel() assert t0_ravel.shape == (self.t0.size,) assert np.all(t0_ravel.jd1 == self.t0.jd1.ravel()) assert np.may_share_memory(t0_ravel.jd1, self.t0.jd1) assert t0_ravel.location is None t1_ravel = self.t1.ravel() assert t1_ravel.shape == (self.t1.size,) assert np.all(t1_ravel.jd1 == self.t1.jd1.ravel()) assert np.may_share_memory(t1_ravel.jd1, self.t1.jd1) assert t1_ravel.location is self.t1.location t2_ravel = self.t2.ravel() assert t2_ravel.shape == (self.t2.size,) assert np.all(t2_ravel.jd1 == self.t2.jd1.ravel()) assert np.may_share_memory(t2_ravel.jd1, self.t2.jd1) assert t2_ravel.location.shape == t2_ravel.shape # Broadcasting and ravelling cannot be done without a copy. assert not np.may_share_memory(t2_ravel.location, self.t2.location) def test_flatten(self, use_mask): self.create_data(use_mask) t0_flatten = self.t0.flatten() assert t0_flatten.shape == (self.t0.size,) assert t0_flatten.location is None # Flatten always makes a copy. assert not np.may_share_memory(t0_flatten.jd1, self.t0.jd1) t1_flatten = self.t1.flatten() assert t1_flatten.shape == (self.t1.size,) assert not np.may_share_memory(t1_flatten.jd1, self.t1.jd1) assert t1_flatten.location is not self.t1.location assert t1_flatten.location == self.t1.location t2_flatten = self.t2.flatten() assert t2_flatten.shape == (self.t2.size,) assert not np.may_share_memory(t2_flatten.jd1, self.t2.jd1) assert t2_flatten.location.shape == t2_flatten.shape assert not np.may_share_memory(t2_flatten.location, self.t2.location) def test_transpose(self, use_mask): self.create_data(use_mask) t0_transpose = self.t0.transpose() assert t0_transpose.shape == (5, 10) assert np.all(t0_transpose.jd1 == self.t0.jd1.transpose()) assert np.may_share_memory(t0_transpose.jd1, self.t0.jd1) assert t0_transpose.location is None t1_transpose = self.t1.transpose() assert t1_transpose.shape == (5, 10) assert np.all(t1_transpose.jd1 == self.t1.jd1.transpose()) assert np.may_share_memory(t1_transpose.jd1, self.t1.jd1) assert t1_transpose.location is self.t1.location t2_transpose = self.t2.transpose() assert t2_transpose.shape == (5, 10) assert np.all(t2_transpose.jd1 == self.t2.jd1.transpose()) assert np.may_share_memory(t2_transpose.jd1, self.t2.jd1) assert t2_transpose.location.shape == t2_transpose.shape assert np.may_share_memory(t2_transpose.location, self.t2.location) # Only one check on T, since it just calls transpose anyway. t2_T = self.t2.T assert t2_T.shape == (5, 10) assert np.all(t2_T.jd1 == self.t2.jd1.T) assert np.may_share_memory(t2_T.jd1, self.t2.jd1) assert t2_T.location.shape == t2_T.location.shape assert np.may_share_memory(t2_T.location, self.t2.location) def test_diagonal(self, use_mask): self.create_data(use_mask) t0_diagonal = self.t0.diagonal() assert t0_diagonal.shape == (5,) assert np.all(t0_diagonal.jd1 == self.t0.jd1.diagonal()) assert t0_diagonal.location is None assert np.may_share_memory(t0_diagonal.jd1, self.t0.jd1) t1_diagonal = self.t1.diagonal() assert t1_diagonal.shape == (5,) assert np.all(t1_diagonal.jd1 == self.t1.jd1.diagonal()) assert t1_diagonal.location is self.t1.location assert np.may_share_memory(t1_diagonal.jd1, self.t1.jd1) t2_diagonal = self.t2.diagonal() assert t2_diagonal.shape == (5,) assert np.all(t2_diagonal.jd1 == self.t2.jd1.diagonal()) assert t2_diagonal.location.shape == t2_diagonal.shape assert np.may_share_memory(t2_diagonal.jd1, self.t2.jd1) assert np.may_share_memory(t2_diagonal.location, self.t2.location) def test_swapaxes(self, use_mask): self.create_data(use_mask) t0_swapaxes = self.t0.swapaxes(0, 1) assert t0_swapaxes.shape == (5, 10) assert np.all(t0_swapaxes.jd1 == self.t0.jd1.swapaxes(0, 1)) assert np.may_share_memory(t0_swapaxes.jd1, self.t0.jd1) assert t0_swapaxes.location is None t1_swapaxes = self.t1.swapaxes(0, 1) assert t1_swapaxes.shape == (5, 10) assert np.all(t1_swapaxes.jd1 == self.t1.jd1.swapaxes(0, 1)) assert np.may_share_memory(t1_swapaxes.jd1, self.t1.jd1) assert t1_swapaxes.location is self.t1.location t2_swapaxes = self.t2.swapaxes(0, 1) assert t2_swapaxes.shape == (5, 10) assert np.all(t2_swapaxes.jd1 == self.t2.jd1.swapaxes(0, 1)) assert np.may_share_memory(t2_swapaxes.jd1, self.t2.jd1) assert t2_swapaxes.location.shape == t2_swapaxes.shape assert np.may_share_memory(t2_swapaxes.location, self.t2.location) def test_reshape(self, use_mask): self.create_data(use_mask) t0_reshape = self.t0.reshape(5, 2, 5) assert t0_reshape.shape == (5, 2, 5) assert np.all(t0_reshape.jd1 == self.t0._time.jd1.reshape(5, 2, 5)) assert np.all(t0_reshape.jd2 == self.t0._time.jd2.reshape(5, 2, 5)) assert np.may_share_memory(t0_reshape.jd1, self.t0.jd1) assert np.may_share_memory(t0_reshape.jd2, self.t0.jd2) assert t0_reshape.location is None t1_reshape = self.t1.reshape(2, 5, 5) assert t1_reshape.shape == (2, 5, 5) assert np.all(t1_reshape.jd1 == self.t1.jd1.reshape(2, 5, 5)) assert np.may_share_memory(t1_reshape.jd1, self.t1.jd1) assert t1_reshape.location is self.t1.location # For reshape(5, 2, 5), the location array can remain the same. t2_reshape = self.t2.reshape(5, 2, 5) assert t2_reshape.shape == (5, 2, 5) assert np.all(t2_reshape.jd1 == self.t2.jd1.reshape(5, 2, 5)) assert np.may_share_memory(t2_reshape.jd1, self.t2.jd1) assert t2_reshape.location.shape == t2_reshape.shape assert np.may_share_memory(t2_reshape.location, self.t2.location) # But for reshape(5, 5, 2), location has to be broadcast and copied. t2_reshape2 = self.t2.reshape(5, 5, 2) assert t2_reshape2.shape == (5, 5, 2) assert np.all(t2_reshape2.jd1 == self.t2.jd1.reshape(5, 5, 2)) assert np.may_share_memory(t2_reshape2.jd1, self.t2.jd1) assert t2_reshape2.location.shape == t2_reshape2.shape assert not np.may_share_memory(t2_reshape2.location, self.t2.location) t2_reshape_t = self.t2.reshape(10, 5).T assert t2_reshape_t.shape == (5, 10) assert np.may_share_memory(t2_reshape_t.jd1, self.t2.jd1) assert t2_reshape_t.location.shape == t2_reshape_t.shape assert np.may_share_memory(t2_reshape_t.location, self.t2.location) # Finally, reshape in a way that cannot be a view. t2_reshape_t_reshape = t2_reshape_t.reshape(10, 5) assert t2_reshape_t_reshape.shape == (10, 5) assert not np.may_share_memory(t2_reshape_t_reshape.jd1, self.t2.jd1) assert (t2_reshape_t_reshape.location.shape == t2_reshape_t_reshape.shape) assert not np.may_share_memory(t2_reshape_t_reshape.location, t2_reshape_t.location) def test_squeeze(self, use_mask): self.create_data(use_mask) t0_squeeze = self.t0.reshape(5, 1, 2, 1, 5).squeeze() assert t0_squeeze.shape == (5, 2, 5) assert np.all(t0_squeeze.jd1 == self.t0.jd1.reshape(5, 2, 5)) assert np.may_share_memory(t0_squeeze.jd1, self.t0.jd1) assert t0_squeeze.location is None t1_squeeze = self.t1.reshape(1, 5, 1, 2, 5).squeeze() assert t1_squeeze.shape == (5, 2, 5) assert np.all(t1_squeeze.jd1 == self.t1.jd1.reshape(5, 2, 5)) assert np.may_share_memory(t1_squeeze.jd1, self.t1.jd1) assert t1_squeeze.location is self.t1.location t2_squeeze = self.t2.reshape(1, 1, 5, 2, 5, 1, 1).squeeze() assert t2_squeeze.shape == (5, 2, 5) assert np.all(t2_squeeze.jd1 == self.t2.jd1.reshape(5, 2, 5)) assert np.may_share_memory(t2_squeeze.jd1, self.t2.jd1) assert t2_squeeze.location.shape == t2_squeeze.shape assert np.may_share_memory(t2_squeeze.location, self.t2.location) def test_add_dimension(self, use_mask): self.create_data(use_mask) t0_adddim = self.t0[:, np.newaxis, :] assert t0_adddim.shape == (10, 1, 5) assert np.all(t0_adddim.jd1 == self.t0.jd1[:, np.newaxis, :]) assert np.may_share_memory(t0_adddim.jd1, self.t0.jd1) assert t0_adddim.location is None t1_adddim = self.t1[:, :, np.newaxis] assert t1_adddim.shape == (10, 5, 1) assert np.all(t1_adddim.jd1 == self.t1.jd1[:, :, np.newaxis]) assert np.may_share_memory(t1_adddim.jd1, self.t1.jd1) assert t1_adddim.location is self.t1.location t2_adddim = self.t2[:, :, np.newaxis] assert t2_adddim.shape == (10, 5, 1) assert np.all(t2_adddim.jd1 == self.t2.jd1[:, :, np.newaxis]) assert np.may_share_memory(t2_adddim.jd1, self.t2.jd1) assert t2_adddim.location.shape == t2_adddim.shape assert np.may_share_memory(t2_adddim.location, self.t2.location) def test_take(self, use_mask): self.create_data(use_mask) t0_take = self.t0.take((5, 2)) assert t0_take.shape == (2,) assert np.all(t0_take.jd1 == self.t0._time.jd1.take((5, 2))) assert t0_take.location is None t1_take = self.t1.take((2, 4), axis=1) assert t1_take.shape == (10, 2) assert np.all(t1_take.jd1 == self.t1.jd1.take((2, 4), axis=1)) assert t1_take.location is self.t1.location t2_take = self.t2.take((1, 3, 7), axis=0) assert t2_take.shape == (3, 5) assert np.all(t2_take.jd1 == self.t2.jd1.take((1, 3, 7), axis=0)) assert t2_take.location.shape == t2_take.shape t2_take2 = self.t2.take((5, 15)) assert t2_take2.shape == (2,) assert np.all(t2_take2.jd1 == self.t2.jd1.take((5, 15))) assert t2_take2.location.shape == t2_take2.shape def test_broadcast_via_apply(self, use_mask): """Test using a callable method.""" self.create_data(use_mask) t0_broadcast = self.t0._apply(np.broadcast_to, shape=(3, 10, 5)) assert t0_broadcast.shape == (3, 10, 5) assert np.all(t0_broadcast.jd1 == self.t0.jd1) assert np.may_share_memory(t0_broadcast.jd1, self.t0.jd1) assert t0_broadcast.location is None t1_broadcast = self.t1._apply(np.broadcast_to, shape=(3, 10, 5)) assert t1_broadcast.shape == (3, 10, 5) assert np.all(t1_broadcast.jd1 == self.t1.jd1) assert np.may_share_memory(t1_broadcast.jd1, self.t1.jd1) assert t1_broadcast.location is self.t1.location t2_broadcast = self.t2._apply(np.broadcast_to, shape=(3, 10, 5)) assert t2_broadcast.shape == (3, 10, 5) assert np.all(t2_broadcast.jd1 == self.t2.jd1) assert np.may_share_memory(t2_broadcast.jd1, self.t2.jd1) assert t2_broadcast.location.shape == t2_broadcast.shape assert np.may_share_memory(t2_broadcast.location, self.t2.location) @pytest.mark.parametrize('use_mask', ('masked', 'not_masked')) class TestSetShape(ShapeSetup): def test_shape_setting(self, use_mask): # Shape-setting should be on the object itself, since copying removes # zero-strides due to broadcasting. Hence, this should be the only # test in this class. self.create_data(use_mask) t0_reshape = self.t0.copy() mjd = t0_reshape.mjd # Creates a cache of the mjd attribute t0_reshape.shape = (5, 2, 5) assert t0_reshape.shape == (5, 2, 5) assert mjd.shape != t0_reshape.mjd.shape # Cache got cleared assert np.all(t0_reshape.jd1 == self.t0._time.jd1.reshape(5, 2, 5)) assert np.all(t0_reshape.jd2 == self.t0._time.jd2.reshape(5, 2, 5)) assert t0_reshape.location is None # But if the shape doesn't work, one should get an error. t0_reshape_t = t0_reshape.T with pytest.raises(ValueError): t0_reshape_t.shape = (12,) # Wrong number of elements. with pytest.raises(AttributeError): t0_reshape_t.shape = (10, 5) # Cannot be done without copy. # check no shape was changed. assert t0_reshape_t.shape == t0_reshape.T.shape assert t0_reshape_t.jd1.shape == t0_reshape.T.shape assert t0_reshape_t.jd2.shape == t0_reshape.T.shape t1_reshape = self.t1.copy() t1_reshape.shape = (2, 5, 5) assert t1_reshape.shape == (2, 5, 5) assert np.all(t1_reshape.jd1 == self.t1.jd1.reshape(2, 5, 5)) # location is a single element, so its shape should not change. assert t1_reshape.location.shape == () # For reshape(5, 2, 5), the location array can remain the same. # Note that we need to work directly on self.t2 here, since any # copy would cause location to have the full shape. self.t2.shape = (5, 2, 5) assert self.t2.shape == (5, 2, 5) assert self.t2.jd1.shape == (5, 2, 5) assert self.t2.jd2.shape == (5, 2, 5) assert self.t2.location.shape == (5, 2, 5) assert self.t2.location.strides == (0, 0, 24) # But for reshape(50), location would need to be copied, so this # should fail. oldshape = self.t2.shape with pytest.raises(AttributeError): self.t2.shape = (50,) # check no shape was changed. assert self.t2.jd1.shape == oldshape assert self.t2.jd2.shape == oldshape assert self.t2.location.shape == oldshape @pytest.mark.parametrize('use_mask', ('masked', 'not_masked')) class TestShapeFunctions(ShapeSetup): @needs_array_function def test_broadcast(self, use_mask): """Test as supported numpy function.""" self.create_data(use_mask) t0_broadcast = np.broadcast_to(self.t0, shape=(3, 10, 5)) assert t0_broadcast.shape == (3, 10, 5) assert np.all(t0_broadcast.jd1 == self.t0.jd1) assert np.may_share_memory(t0_broadcast.jd1, self.t0.jd1) assert t0_broadcast.location is None t1_broadcast = np.broadcast_to(self.t1, shape=(3, 10, 5)) assert t1_broadcast.shape == (3, 10, 5) assert np.all(t1_broadcast.jd1 == self.t1.jd1) assert np.may_share_memory(t1_broadcast.jd1, self.t1.jd1) assert t1_broadcast.location is self.t1.location t2_broadcast = np.broadcast_to(self.t2, shape=(3, 10, 5)) assert t2_broadcast.shape == (3, 10, 5) assert np.all(t2_broadcast.jd1 == self.t2.jd1) assert np.may_share_memory(t2_broadcast.jd1, self.t2.jd1) assert t2_broadcast.location.shape == t2_broadcast.shape assert np.may_share_memory(t2_broadcast.location, self.t2.location) @needs_array_function def test_atleast_1d(self, use_mask): self.create_data(use_mask) t00 = self.t0.ravel()[0] assert t00.ndim == 0 t00_1d = np.atleast_1d(t00) assert t00_1d.ndim == 1 assert_time_all_equal(t00[np.newaxis], t00_1d) # Actual jd1 will not share memory, as cast to scalar. assert np.may_share_memory(t00_1d._time.jd1, t00._time.jd1) @needs_array_function def test_atleast_2d(self, use_mask): self.create_data(use_mask) t0r = self.t0.ravel() assert t0r.ndim == 1 t0r_2d = np.atleast_2d(t0r) assert t0r_2d.ndim == 2 assert_time_all_equal(t0r[np.newaxis], t0r_2d) assert np.may_share_memory(t0r_2d.jd1, t0r.jd1) @needs_array_function def test_atleast_3d(self, use_mask): self.create_data(use_mask) assert self.t0.ndim == 2 t0_3d, t1_3d = np.atleast_3d(self.t0, self.t1) assert t0_3d.ndim == t1_3d.ndim == 3 assert_time_all_equal(self.t0[:, :, np.newaxis], t0_3d) assert_time_all_equal(self.t1[:, :, np.newaxis], t1_3d) assert np.may_share_memory(t0_3d.jd2, self.t0.jd2) def test_move_axis(self, use_mask): # Goes via transpose so works without __array_function__ as well. self.create_data(use_mask) t0_10 = np.moveaxis(self.t0, 0, 1) assert t0_10.shape == (self.t0.shape[1], self.t0.shape[0]) assert_time_all_equal(self.t0.T, t0_10) assert np.may_share_memory(t0_10.jd1, self.t0.jd1) def test_roll_axis(self, use_mask): # Goes via transpose so works without __array_function__ as well. self.create_data(use_mask) t0_10 = np.rollaxis(self.t0, 1) assert t0_10.shape == (self.t0.shape[1], self.t0.shape[0]) assert_time_all_equal(self.t0.T, t0_10) assert np.may_share_memory(t0_10.jd1, self.t0.jd1) @needs_array_function def test_fliplr(self, use_mask): self.create_data(use_mask) t0_lr = np.fliplr(self.t0) assert_time_all_equal(self.t0[:, ::-1], t0_lr) assert np.may_share_memory(t0_lr.jd2, self.t0.jd2) @needs_array_function def test_rot90(self, use_mask): self.create_data(use_mask) t0_270 = np.rot90(self.t0, 3) assert_time_all_equal(self.t0.T[:, ::-1], t0_270) assert np.may_share_memory(t0_270.jd2, self.t0.jd2) @needs_array_function def test_roll(self, use_mask): self.create_data(use_mask) t0r = np.roll(self.t0, 1, axis=0) assert_time_all_equal(t0r[1:], self.t0[:-1]) assert_time_all_equal(t0r[0], self.t0[-1]) @needs_array_function def test_delete(self, use_mask): self.create_data(use_mask) t0d = np.delete(self.t0, [2, 3], axis=0) assert_time_all_equal(t0d[:2], self.t0[:2]) assert_time_all_equal(t0d[2:], self.t0[4:]) @pytest.mark.parametrize('use_mask', ('masked', 'not_masked')) class TestArithmetic: """Arithmetic on Time objects, using both doubles.""" kwargs = ({}, {'axis': None}, {'axis': 0}, {'axis': 1}, {'axis': 2}) functions = ('min', 'max', 'sort') def setup_class(cls): mjd = np.arange(50000, 50100, 10).reshape(2, 5, 1) frac = np.array([0.1, 0.1 + 1.e-15, 0.1 - 1.e-15, 0.9 + 2.e-16, 0.9]) frac_masked = np.ma.array(frac) frac_masked[1] = np.ma.masked cls.t0 = { 'not_masked': Time(mjd, frac, format='mjd', scale='utc'), 'masked': Time(mjd, frac_masked, format='mjd', scale='utc') } # Define arrays with same ordinal properties frac = np.array([1, 2, 0, 4, 3]) frac_masked = np.ma.array(frac) frac_masked[1] = np.ma.masked cls.t1 = { 'not_masked': Time(mjd + frac, format='mjd', scale='utc'), 'masked': Time(mjd + frac_masked, format='mjd', scale='utc'), } cls.jd = { 'not_masked': mjd + frac, 'masked': mjd + frac_masked } def create_data(self, use_mask): self.t0 = self.__class__.t0[use_mask] self.t1 = self.__class__.t1[use_mask] self.jd = self.__class__.jd[use_mask] @pytest.mark.parametrize('kw, func', itertools.product(kwargs, functions)) def test_argfuncs(self, kw, func, use_mask): """ Test that ``np.argfunc(jd, **kw)`` is the same as ``t0.argfunc(**kw)`` where ``jd`` is a similarly shaped array with the same ordinal properties but all integer values. Also test the same for t1 which has the same integral values as jd. """ self.create_data(use_mask) t0v = getattr(self.t0, 'arg' + func)(**kw) t1v = getattr(self.t1, 'arg' + func)(**kw) jdv = getattr(np, 'arg' + func)(self.jd, **kw) if self.t0.masked and kw == {'axis': None} and func == 'sort': t0v = np.ma.array(t0v, mask=self.t0.mask.reshape(t0v.shape)[t0v]) t1v = np.ma.array(t1v, mask=self.t1.mask.reshape(t1v.shape)[t1v]) jdv = np.ma.array(jdv, mask=self.jd.mask.reshape(jdv.shape)[jdv]) assert np.all(t0v == jdv) assert np.all(t1v == jdv) assert t0v.shape == jdv.shape assert t1v.shape == jdv.shape @pytest.mark.parametrize('kw, func', itertools.product(kwargs, functions)) def test_funcs(self, kw, func, use_mask): """ Test that ``np.func(jd, **kw)`` is the same as ``t1.func(**kw)`` where ``jd`` is a similarly shaped array and the same integral values. """ self.create_data(use_mask) t1v = getattr(self.t1, func)(**kw) jdv = getattr(np, func)(self.jd, **kw) assert np.all(t1v.value == jdv) assert t1v.shape == jdv.shape def test_argmin(self, use_mask): self.create_data(use_mask) assert self.t0.argmin() == 2 assert np.all(self.t0.argmin(axis=0) == 0) assert np.all(self.t0.argmin(axis=1) == 0) assert np.all(self.t0.argmin(axis=2) == 2) def test_argmax(self, use_mask): self.create_data(use_mask) assert self.t0.argmax() == self.t0.size - 2 if use_mask == 'masked': # The 0 is where all entries are masked in that axis assert np.all(self.t0.argmax(axis=0) == [1, 0, 1, 1, 1]) assert np.all(self.t0.argmax(axis=1) == [4, 0, 4, 4, 4]) else: assert np.all(self.t0.argmax(axis=0) == 1) assert np.all(self.t0.argmax(axis=1) == 4) assert np.all(self.t0.argmax(axis=2) == 3) def test_argsort(self, use_mask): self.create_data(use_mask) order = [2, 0, 4, 3, 1] if use_mask == 'masked' else [2, 0, 1, 4, 3] assert np.all(self.t0.argsort() == np.array(order)) assert np.all(self.t0.argsort(axis=0) == np.arange(2).reshape(2, 1, 1)) assert np.all(self.t0.argsort(axis=1) == np.arange(5).reshape(5, 1)) assert np.all(self.t0.argsort(axis=2) == np.array(order)) ravel = np.arange(50).reshape(-1, 5)[:, order].ravel() if use_mask == 'masked': t0v = self.t0.argsort(axis=None) # Manually remove elements in ravel that correspond to masked # entries in self.t0. This removes the 10 entries that are masked # which show up at the end of the list. mask = self.t0.mask.ravel()[ravel] ravel = ravel[~mask] assert np.all(t0v[:-10] == ravel) else: assert np.all(self.t0.argsort(axis=None) == ravel) @pytest.mark.parametrize('scale', Time.SCALES) def test_argsort_warning(self, use_mask, scale): self.create_data(use_mask) if scale == 'utc': pytest.xfail() with warnings.catch_warnings(record=True) as wlist: Time([1, 2, 3], format='jd', scale=scale).argsort() assert len(wlist) == 0 def test_min(self, use_mask): self.create_data(use_mask) assert self.t0.min() == self.t0[0, 0, 2] assert np.all(self.t0.min(0) == self.t0[0]) assert np.all(self.t0.min(1) == self.t0[:, 0]) assert np.all(self.t0.min(2) == self.t0[:, :, 2]) assert self.t0.min(0).shape == (5, 5) assert self.t0.min(0, keepdims=True).shape == (1, 5, 5) assert self.t0.min(1).shape == (2, 5) assert self.t0.min(1, keepdims=True).shape == (2, 1, 5) assert self.t0.min(2).shape == (2, 5) assert self.t0.min(2, keepdims=True).shape == (2, 5, 1) def test_max(self, use_mask): self.create_data(use_mask) assert self.t0.max() == self.t0[-1, -1, -2] assert np.all(self.t0.max(0) == self.t0[1]) assert np.all(self.t0.max(1) == self.t0[:, 4]) assert np.all(self.t0.max(2) == self.t0[:, :, 3]) assert self.t0.max(0).shape == (5, 5) assert self.t0.max(0, keepdims=True).shape == (1, 5, 5) def test_ptp(self, use_mask): self.create_data(use_mask) assert self.t0.ptp() == self.t0.max() - self.t0.min() assert np.all(self.t0.ptp(0) == self.t0.max(0) - self.t0.min(0)) assert self.t0.ptp(0).shape == (5, 5) assert self.t0.ptp(0, keepdims=True).shape == (1, 5, 5) def test_sort(self, use_mask): self.create_data(use_mask) order = [2, 0, 4, 3, 1] if use_mask == 'masked' else [2, 0, 1, 4, 3] assert np.all(self.t0.sort() == self.t0[:, :, order]) assert np.all(self.t0.sort(0) == self.t0) assert np.all(self.t0.sort(1) == self.t0) assert np.all(self.t0.sort(2) == self.t0[:, :, order]) if use_mask == 'not_masked': assert np.all(self.t0.sort(None) == self.t0[:, :, order].ravel()) # Bit superfluous, but good to check. assert np.all(self.t0.sort(-1)[:, :, 0] == self.t0.min(-1)) assert np.all(self.t0.sort(-1)[:, :, -1] == self.t0.max(-1)) def test_regression(): # For #5225, where a time with a single-element delta_ut1_utc could not # be copied, flattened, or ravelled. (For copy, it is in test_basic.) with iers.conf.set_temp('auto_download', False): t = Time(49580.0, scale='tai', format='mjd') t_ut1 = t.ut1 t_ut1_copy = copy.deepcopy(t_ut1) assert type(t_ut1_copy.delta_ut1_utc) is np.ndarray t_ut1_flatten = t_ut1.flatten() assert type(t_ut1_flatten.delta_ut1_utc) is np.ndarray t_ut1_ravel = t_ut1.ravel() assert type(t_ut1_ravel.delta_ut1_utc) is np.ndarray assert t_ut1_copy.delta_ut1_utc == t_ut1.delta_ut1_utc
9f991075aa8d06f6bef3e4c4a4b96bb273c13c0034d2976922e5421caa311029
# Licensed under a 3-clause BSD style license - see LICENSE.rst from datetime import date from itertools import count import pytest import numpy as np from erfa import DJM0 from astropy.time import Time, TimeFormat from astropy.time.utils import day_frac class SpecificException(ValueError): pass @pytest.fixture def custom_format_name(): for i in count(): if not i: custom = f"custom_format_name" else: custom = f"custom_format_name_{i}" if custom not in Time.FORMATS: break yield custom Time.FORMATS.pop(custom, None) def test_custom_time_format_set_jds_exception(custom_format_name): class Custom(TimeFormat): name = custom_format_name def set_jds(self, val, val2): raise SpecificException try: Time(7.0, format=custom_format_name) except ValueError as e: assert hasattr(e, "__cause__") and isinstance(e.__cause__, SpecificException) def test_custom_time_format_val_type_exception(custom_format_name): class Custom(TimeFormat): name = custom_format_name def _check_val_type(self, val, val2): raise SpecificException try: Time(7.0, format=custom_format_name) except ValueError as e: assert hasattr(e, "__cause__") and isinstance(e.__cause__, SpecificException) def test_custom_time_format_value_exception(custom_format_name): class Custom(TimeFormat): name = custom_format_name def set_jds(self, val, val2): self.jd1, self.jd2 = val, val2 @property def value(self): raise SpecificException t = Time.now() with pytest.raises(SpecificException): getattr(t, custom_format_name) def test_custom_time_format_fine(custom_format_name): class Custom(TimeFormat): name = custom_format_name def set_jds(self, val, val2): self.jd1, self.jd2 = val, val2 @property def value(self): return self.jd1 + self.jd2 t = Time.now() getattr(t, custom_format_name) t2 = Time(7, 9, format=custom_format_name) getattr(t2, custom_format_name) def test_custom_time_format_forgot_property(custom_format_name): with pytest.raises(ValueError): class Custom(TimeFormat): name = custom_format_name def set_jds(self, val, val2): self.jd1, self.jd2 = val, val2 def value(self): return self.jd1, self.jd2 def test_custom_time_format_problematic_name(): assert "sort" not in Time.FORMATS, "problematic name in default FORMATS!" assert hasattr(Time, "sort") try: class Custom(TimeFormat): name = "sort" _dtype = np.dtype([('jd1', 'f8'), ('jd2', 'f8')]) def set_jds(self, val, val2): self.jd1, self.jd2 = val, val2 @property def value(self): result = np.empty(self.jd1.shape, self._dtype) result['jd1'] = self.jd1 result['jd2'] = self.jd2 return result t = Time.now() assert t.sort() == t, "bogus time format clobbers everyone's Time objects" t.format = "sort" assert t.value.dtype == Custom._dtype t2 = Time(7, 9, format="sort") assert t2.value == np.array((7, 9), Custom._dtype) finally: Time.FORMATS.pop("sort", None) def test_mjd_longdouble_preserves_precision(custom_format_name): class CustomMJD(TimeFormat): name = custom_format_name def _check_val_type(self, val, val2): val = np.longdouble(val) if val2 is not None: raise ValueError("Only one value permitted") return val, 0 def set_jds(self, val, val2): mjd1 = np.float64(np.floor(val)) mjd2 = np.float64(val - mjd1) self.jd1, self.jd2 = day_frac(mjd1 + DJM0, mjd2) @property def value(self): mjd1, mjd2 = day_frac(self.jd1 - DJM0, self.jd2) return np.longdouble(mjd1) + np.longdouble(mjd2) m = 58000.0 t = Time(m, format=custom_format_name) # Pick a different long double (ensuring it will give a different jd2 # even when long doubles are more precise than Time, as on arm64). m2 = np.longdouble(m) + max(2. * m * np.finfo(np.longdouble).eps, np.finfo(float).eps) assert m2 != m, 'long double is weird!' t2 = Time(m2, format=custom_format_name) assert t != t2 assert isinstance(getattr(t, custom_format_name), np.longdouble) assert getattr(t, custom_format_name) != getattr(t2, custom_format_name) @pytest.mark.parametrize( "jd1, jd2", [ ("foo", None), (np.arange(3), np.arange(4)), ("foo", "bar"), (1j, 2j), pytest.param( np.longdouble(3), np.longdouble(5), marks=pytest.mark.skipif( np.longdouble().itemsize == np.dtype(float).itemsize, reason="long double == double on this platform")), ({1: 2}, {3: 4}), ({1, 2}, {3, 4}), ([1, 2], [3, 4]), (lambda: 4, lambda: 7), (np.arange(3), np.arange(4)), ], ) def test_custom_format_cannot_make_bogus_jd1(custom_format_name, jd1, jd2): class Custom(TimeFormat): name = custom_format_name def set_jds(self, val, val2): self.jd1, self.jd2 = jd1, jd2 @property def value(self): return self.jd1 + self.jd2 with pytest.raises((ValueError, TypeError)): Time(5, format=custom_format_name) def test_custom_format_scalar_jd1_jd2_okay(custom_format_name): class Custom(TimeFormat): name = custom_format_name def set_jds(self, val, val2): self.jd1, self.jd2 = 7.0, 3.0 @property def value(self): return self.jd1 + self.jd2 getattr(Time(5, format=custom_format_name), custom_format_name) @pytest.mark.parametrize( "thing", [ 1, 1.0, np.longdouble(1), 1.0j, "foo", b"foo", Time(5, format="mjd"), lambda: 7, np.datetime64('2005-02-25'), date(2006, 2, 25), ], ) def test_custom_format_can_return_any_scalar(custom_format_name, thing): class Custom(TimeFormat): name = custom_format_name def set_jds(self, val, val2): self.jd1, self.jd2 = 2., 0. @property def value(self): return np.array(thing) assert type(getattr(Time(5, format=custom_format_name), custom_format_name)) == type(thing) assert np.all(getattr(Time(5, format=custom_format_name), custom_format_name) == thing) @pytest.mark.parametrize( "thing", [ (1, 2), [1, 2], np.array([2, 3]), np.array([2, 3, 5, 7]), {6: 7}, {1, 2}, ], ) def test_custom_format_can_return_any_iterable(custom_format_name, thing): class Custom(TimeFormat): name = custom_format_name def set_jds(self, val, val2): self.jd1, self.jd2 = 2., 0. @property def value(self): return thing assert type(getattr(Time(5, format=custom_format_name), custom_format_name)) == type(thing) assert np.all(getattr(Time(5, format=custom_format_name), custom_format_name) == thing)
0dcc5b39d570a8d9bfaf8d7fb08512827f994789dd1e462852a0977f2d6f2c3f
# Licensed under a 3-clause BSD style license - see LICENSE.rst import functools import numpy as np import pytest from astropy import units as u from astropy.utils import iers from astropy.time import Time from astropy.table import Table from astropy.utils.compat.optional_deps import HAS_H5PY allclose_sec = functools.partial(np.allclose, rtol=2. ** -52, atol=2. ** -52 * 24 * 3600) # 20 ps atol is_masked = np.ma.is_masked def test_simple(): t = Time([1, 2, 3], format='cxcsec') assert t.masked is False assert np.all(t.mask == [False, False, False]) # Before masking, format output is not a masked array (it is an ndarray # like always) assert not isinstance(t.value, np.ma.MaskedArray) assert not isinstance(t.unix, np.ma.MaskedArray) t[2] = np.ma.masked assert t.masked is True assert np.all(t.mask == [False, False, True]) assert allclose_sec(t.value[:2], [1, 2]) assert is_masked(t.value[2]) assert is_masked(t[2].value) # After masking format output is a masked array assert isinstance(t.value, np.ma.MaskedArray) assert isinstance(t.unix, np.ma.MaskedArray) # Todo : test all formats def test_scalar_init(): t = Time('2000:001') assert t.masked is False assert t.mask == np.array(False) def test_mask_not_writeable(): t = Time('2000:001') with pytest.raises(AttributeError) as err: t.mask = True assert "can't set attribute" in str(err.value) t = Time(['2000:001']) with pytest.raises(ValueError) as err: t.mask[0] = True assert "assignment destination is read-only" in str(err.value) def test_str(): t = Time(['2000:001', '2000:002']) t[1] = np.ma.masked assert str(t) == "['2000:001:00:00:00.000' --]" assert repr(t) == "<Time object: scale='utc' format='yday' value=['2000:001:00:00:00.000' --]>" expected = ["masked_array(data=['2000-01-01 00:00:00.000', --],", ' mask=[False, True],', " fill_value='N/A',", " dtype='<U23')"] # Note that we need to take care to allow for big-endian platforms, # for which the dtype will be >U23 instead of <U23, which we do with # the call to replace(). assert repr(t.iso).replace('>U23', '<U23').splitlines() == expected # Assign value to unmask t[1] = '2000:111' assert str(t) == "['2000:001:00:00:00.000' '2000:111:00:00:00.000']" assert t.masked is False def test_transform(): with iers.conf.set_temp('auto_download', False): t = Time(['2000:001', '2000:002']) t[1] = np.ma.masked # Change scale (this tests the ERFA machinery with masking as well) t_ut1 = t.ut1 assert is_masked(t_ut1.value[1]) assert not is_masked(t_ut1.value[0]) assert np.all(t_ut1.mask == [False, True]) # Change format t_unix = t.unix assert is_masked(t_unix[1]) assert not is_masked(t_unix[0]) assert np.all(t_unix.mask == [False, True]) def test_masked_input(): v0 = np.ma.MaskedArray([[1, 2], [3, 4]]) # No masked elements v1 = np.ma.MaskedArray([[1, 2], [3, 4]], mask=[[True, False], [False, False]]) v2 = np.ma.MaskedArray([[10, 20], [30, 40]], mask=[[False, False], [False, True]]) # Init from various combinations of masked arrays t = Time(v0, format='cxcsec') assert np.ma.allclose(t.value, v0) assert np.all(t.mask == [[False, False], [False, False]]) assert t.masked is False t = Time(v1, format='cxcsec') assert np.ma.allclose(t.value, v1) assert np.all(t.mask == v1.mask) assert np.all(t.value.mask == v1.mask) assert t.masked is True t = Time(v1, v2, format='cxcsec') assert np.ma.allclose(t.value, v1 + v2) assert np.all(t.mask == (v1 + v2).mask) assert t.masked is True t = Time(v0, v1, format='cxcsec') assert np.ma.allclose(t.value, v0 + v1) assert np.all(t.mask == (v0 + v1).mask) assert t.masked is True t = Time(0, v2, format='cxcsec') assert np.ma.allclose(t.value, v2) assert np.all(t.mask == v2.mask) assert t.masked is True # Init from a string masked array t_iso = t.iso t2 = Time(t_iso) assert np.all(t2.value == t_iso) assert np.all(t2.mask == v2.mask) assert t2.masked is True def test_all_masked_input(): """Fix for #9612""" # Test with jd=0 and jd=np.nan. Both triggered an exception prior to #9624 # due to astropy.utils.exceptions.ErfaError. for val in (0, np.nan): t = Time(np.ma.masked_array([val], mask=[True]), format='jd') assert str(t.iso) == '[--]' def test_serialize_fits_masked(tmpdir): tm = Time([1, 2, 3], format='cxcsec') tm[1] = np.ma.masked fn = str(tmpdir.join('tempfile.fits')) t = Table([tm]) t.write(fn) t2 = Table.read(fn, astropy_native=True) # Time FITS handling does not current round-trip format in FITS t2['col0'].format = tm.format assert t2['col0'].masked assert np.all(t2['col0'].mask == [False, True, False]) assert np.all(t2['col0'].value == t['col0'].value) @pytest.mark.skipif(not HAS_H5PY, reason='Needs h5py') def test_serialize_hdf5_masked(tmpdir): tm = Time([1, 2, 3], format='cxcsec') tm[1] = np.ma.masked fn = str(tmpdir.join('tempfile.hdf5')) t = Table([tm]) t.write(fn, path='root', serialize_meta=True) t2 = Table.read(fn) assert t2['col0'].masked assert np.all(t2['col0'].mask == [False, True, False]) assert np.all(t2['col0'].value == t['col0'].value) # Ignore warning in MIPS https://github.com/astropy/astropy/issues/9750 @pytest.mark.filterwarnings('ignore:invalid value encountered') @pytest.mark.parametrize('serialize_method', ['jd1_jd2', 'formatted_value']) def test_serialize_ecsv_masked(serialize_method, tmpdir): tm = Time([1, 2, 3], format='cxcsec') tm[1] = np.ma.masked tm.info.serialize_method['ecsv'] = serialize_method fn = str(tmpdir.join('tempfile.ecsv')) t = Table([tm]) t.write(fn) t2 = Table.read(fn) assert t2['col0'].masked assert np.all(t2['col0'].mask == [False, True, False]) # Serializing formatted_value loses some precision. atol = 0.1*u.us if serialize_method == 'formatted_value' else 1*u.ps assert np.all(abs(t2['col0'] - t['col0']) <= atol)
febe90c3b70b6bb1faf89a06a4d8f62106cd2e2d325d382006de59af4fc5317a
# Licensed under a 3-clause BSD style license - see LICENSE.rst import functools import itertools import pytest import numpy as np import erfa from astropy import units as u from astropy.time import Time from astropy.time.core import SIDEREAL_TIME_MODELS from astropy.utils import iers allclose_hours = functools.partial(np.allclose, rtol=1e-15, atol=3e-8) # 0.1 ms atol; IERS-B files change at that level. within_1_second = functools.partial(np.allclose, rtol=1., atol=1. / 3600.) within_2_seconds = functools.partial(np.allclose, rtol=1., atol=2. / 3600.) def test_doc_string_contains_models(): """The doc string is formatted; this ensures this remains working.""" for kind in ('mean', 'apparent'): for model in SIDEREAL_TIME_MODELS[kind]: assert model in Time.sidereal_time.__doc__ class TestERFATestCases: """Test that we reproduce the test cases given in erfa/src/t_erfa_c.c""" def setup_class(cls): # Sidereal time tests use the following JD inputs. cls.time_ut1 = Time(2400000.5, 53736.0, scale='ut1', format='jd') cls.time_tt = Time(2400000.5, 53736.0, scale='tt', format='jd') # but tt!=ut1 at these dates, unlike what is assumed, so we cannot # reproduce this exactly. Now it does not really matter, # but may as well fake this (and avoid IERS table lookup here) cls.time_ut1.delta_ut1_utc = 0. cls.time_ut1.delta_ut1_utc = 24 * 3600 * ( (cls.time_ut1.tt.jd1 - cls.time_tt.jd1) + (cls.time_ut1.tt.jd2 - cls.time_tt.jd2)) def test_setup(self): assert np.allclose((self.time_ut1.tt.jd1 - self.time_tt.jd1) + (self.time_ut1.tt.jd2 - self.time_tt.jd2), 0., atol=1.e-14) @pytest.mark.parametrize('erfa_test_input', ((1.754174972210740592, 1e-12, "eraGmst00"), (1.754174971870091203, 1e-12, "eraGmst06"), (1.754174981860675096, 1e-12, "eraGmst82"), (1.754166138018281369, 1e-12, "eraGst00a"), (1.754166136510680589, 1e-12, "eraGst00b"), (1.754166137675019159, 1e-12, "eraGst06a"), (1.754166136020645203, 1e-12, "eraGst94"))) def test_iau_models(self, erfa_test_input): result, precision, name = erfa_test_input if name[4] == 'm': kind = 'mean' model_name = f"IAU{20 if name[7] == '0' else 19:2d}{name[7:]:s}" else: kind = 'apparent' model_name = f"IAU{20 if name[6] == '0' else 19:2d}{name[6:].upper():s}" assert kind in SIDEREAL_TIME_MODELS.keys() assert model_name in SIDEREAL_TIME_MODELS[kind] gst = self.time_ut1.sidereal_time(kind, 'greenwich', model_name) assert np.allclose(gst.to_value('radian'), result, rtol=1., atol=precision) def test_era(self): # Separate since it does not use the same time. time_ut1 = Time(2400000.5, 54388.0, format='jd', scale='ut1') era = time_ut1.earth_rotation_angle('tio') expected = 0.4022837240028158102 assert np.abs(era.to_value(u.radian) - expected) < 1e-12 class TestST: """Test Greenwich Sidereal Time. Unlike above, this is relative to what was found earlier, so checks changes in implementation, including leap seconds, rather than correctness""" @classmethod def setup_class(cls): cls.orig_auto_download = iers.conf.auto_download iers.conf.auto_download = False cls.t1 = Time(['2012-06-30 12:00:00', '2012-06-30 23:59:59', '2012-06-30 23:59:60', '2012-07-01 00:00:00', '2012-07-01 12:00:00'], scale='utc') cls.t2 = Time(cls.t1, location=('120d', '10d')) @classmethod def teardown_class(cls): iers.conf.auto_download = cls.orig_auto_download def test_gmst(self): """Compare Greenwich Mean Sidereal Time with what was found earlier """ gmst_compare = np.array([6.5968497894730564, 18.629426164144697, 18.629704702452862, 18.629983240761003, 6.6628381828899643]) gmst = self.t1.sidereal_time('mean', 'greenwich') assert allclose_hours(gmst.value, gmst_compare) def test_gst(self): """Compare Greenwich Apparent Sidereal Time with what was found earlier """ gst_compare = np.array([6.5971168570494854, 18.629694220878296, 18.62997275921186, 18.630251297545389, 6.6631074284018244]) gst = self.t1.sidereal_time('apparent', 'greenwich') assert allclose_hours(gst.value, gst_compare) def test_era(self): """Comare ERA relative to erfa.era00 test case.""" t = Time(2400000.5, 54388.0, format='jd', location=(0, 0), scale='ut1') era = t.earth_rotation_angle() expected = 0.4022837240028158102 * u.radian # Without the TIO locator/polar motion, this should be close already. assert np.abs(era - expected) < 1e-10 * u.radian # And with it, one should reach full precision. sp = erfa.sp00(t.tt.jd1, t.tt.jd2) iers_table = iers.earth_orientation_table.get() xp, yp = [c.to_value(u.rad) for c in iers_table.pm_xy(t)] r = erfa.rx(-yp, erfa.ry(-xp, erfa.rz(sp, np.eye(3)))) expected1 = expected + (np.arctan2(r[0, 1], r[0, 0]) << u.radian) assert np.abs(era - expected1) < 1e-12 * u.radian # Now try at a longitude different from 0. t2 = Time(2400000.5, 54388.0, format='jd', location=(45, 0), scale='ut1') era2 = t2.earth_rotation_angle() r2 = erfa.rz(np.deg2rad(45), r) expected2 = expected + (np.arctan2(r2[0, 1], r2[0, 0]) << u.radian) assert np.abs(era2 - expected2) < 1e-12 * u.radian def test_gmst_gst_close(self): """Check that Mean and Apparent are within a few seconds.""" gmst = self.t1.sidereal_time('mean', 'greenwich') gst = self.t1.sidereal_time('apparent', 'greenwich') assert within_2_seconds(gst.value, gmst.value) def test_gmst_era_close(self): """Check that mean sidereal time and earth rotation angle are close.""" gmst = self.t1.sidereal_time('mean', 'greenwich') era = self.t1.earth_rotation_angle('tio') assert within_2_seconds(era.value, gmst.value) def test_gmst_independent_of_self_location(self): """Check that Greenwich time does not depend on self.location""" gmst1 = self.t1.sidereal_time('mean', 'greenwich') gmst2 = self.t2.sidereal_time('mean', 'greenwich') assert allclose_hours(gmst1.value, gmst2.value) def test_gmst_vs_lmst(self): """Check that Greenwich and local sidereal time differ.""" gmst = self.t1.sidereal_time('mean', 'greenwich') lmst = self.t1.sidereal_time('mean', 0) assert allclose_hours(lmst.value, gmst.value) assert np.all(np.abs(lmst-gmst) > 1e-10 * u.hourangle) @pytest.mark.parametrize('kind', ('mean', 'apparent')) def test_lst(self, kind): """Compare Local Sidereal Time with what was found earlier, as well as with what is expected from GMST """ lst_compare = { 'mean': np.array([14.596849789473058, 2.629426164144693, 2.6297047024528588, 2.6299832407610033, 14.662838182889967]), 'apparent': np.array([14.597116857049487, 2.6296942208782959, 2.6299727592118565, 2.6302512975453887, 14.663107428401826])} gmst2 = self.t2.sidereal_time(kind, 'greenwich') lmst2 = self.t2.sidereal_time(kind) assert allclose_hours(lmst2.value, lst_compare[kind]) assert allclose_hours((lmst2 - gmst2).wrap_at('12h').value, self.t2.location.lon.to_value('hourangle')) # check it also works when one gives longitude explicitly lmst1 = self.t1.sidereal_time(kind, self.t2.location.lon) assert allclose_hours(lmst1.value, lst_compare[kind]) def test_lst_string_longitude(self): lmst1 = self.t1.sidereal_time('mean', longitude='120d') lmst2 = self.t2.sidereal_time('mean') assert allclose_hours(lmst1.value, lmst2.value) def test_lst_needs_location(self): with pytest.raises(ValueError): self.t1.sidereal_time('mean') with pytest.raises(ValueError): self.t1.sidereal_time('mean', None) def test_lera(self): lera_compare = np.array([14.586176631122177, 2.618751847545134, 2.6190303858265067, 2.619308924107852, 14.652162695594276]) gera2 = self.t2.earth_rotation_angle('tio') lera2 = self.t2.earth_rotation_angle() assert allclose_hours(lera2.value, lera_compare) assert allclose_hours((lera2 - gera2).wrap_at('12h').value, self.t2.location.lon.to_value('hourangle')) # Check it also works when one gives location explicitly. # This also verifies input of a location generally. lera1 = self.t1.earth_rotation_angle(self.t2.location) assert allclose_hours(lera1.value, lera_compare) class TestModelInterpretation: """Check that models are different, and that wrong models are recognized""" @classmethod def setup_class(cls): cls.orig_auto_download = iers.conf.auto_download iers.conf.auto_download = False cls.t = Time(['2012-06-30 12:00:00'], scale='utc', location=('120d', '10d')) @classmethod def teardown_class(cls): iers.conf.auto_download = cls.orig_auto_download @pytest.mark.parametrize('kind', ('mean', 'apparent')) def test_model_uniqueness(self, kind): """Check models give different answers, yet are close.""" for model1, model2 in itertools.combinations( SIDEREAL_TIME_MODELS[kind].keys(), 2): gst1 = self.t.sidereal_time(kind, 'greenwich', model1) gst2 = self.t.sidereal_time(kind, 'greenwich', model2) assert np.all(gst1.value != gst2.value) assert within_1_second(gst1.value, gst2.value) lst1 = self.t.sidereal_time(kind, None, model1) lst2 = self.t.sidereal_time(kind, None, model2) assert np.all(lst1.value != lst2.value) assert within_1_second(lst1.value, lst2.value) @pytest.mark.parametrize(('kind', 'other'), (('mean', 'apparent'), ('apparent', 'mean'))) def test_wrong_models_raise_exceptions(self, kind, other): with pytest.raises(ValueError): self.t.sidereal_time(kind, 'greenwich', 'nonsense') for model in (set(SIDEREAL_TIME_MODELS[other].keys()) - set(SIDEREAL_TIME_MODELS[kind].keys())): with pytest.raises(ValueError): self.t.sidereal_time(kind, 'greenwich', model) with pytest.raises(ValueError): self.t.sidereal_time(kind, None, model)
98e4a35973be6d404ff47b9b749ced825ad977ad8aba08dde487d61a496c82fd
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICNSE.rst # This module includes files automatically generated from ply (these end in # _lextab.py and _parsetab.py). To generate these files, remove them from this # folder, then build astropy and run the tests in-place: # # python setup.py build_ext --inplace # pytest astropy/units # # You can then commit the changes to the re-generated _lextab.py and # _parsetab.py files. """ Handles the CDS string format for units """ import operator import os import re from .base import Base from . import core, utils from astropy.units.utils import is_effectively_unity from astropy.utils import classproperty, parsing from astropy.utils.misc import did_you_mean # TODO: Support logarithmic units using bracketed syntax class CDS(Base): """ Support the `Centre de Données astronomiques de Strasbourg <http://cds.u-strasbg.fr/>`_ `Standards for Astronomical Catalogues 2.0 <http://vizier.u-strasbg.fr/vizier/doc/catstd-3.2.htx>`_ format, and the `complete set of supported units <https://vizier.u-strasbg.fr/viz-bin/Unit>`_. This format is used by VOTable up to version 1.2. """ _tokens = ( 'PRODUCT', 'DIVISION', 'OPEN_PAREN', 'CLOSE_PAREN', 'OPEN_BRACKET', 'CLOSE_BRACKET', 'X', 'SIGN', 'UINT', 'UFLOAT', 'UNIT', 'DIMENSIONLESS' ) @classproperty(lazy=True) def _units(cls): return cls._generate_unit_names() @classproperty(lazy=True) def _parser(cls): return cls._make_parser() @classproperty(lazy=True) def _lexer(cls): return cls._make_lexer() @staticmethod def _generate_unit_names(): from astropy.units import cds from astropy import units as u names = {} for key, val in cds.__dict__.items(): if isinstance(val, u.UnitBase): names[key] = val return names @classmethod def _make_lexer(cls): tokens = cls._tokens t_PRODUCT = r'\.' t_DIVISION = r'/' t_OPEN_PAREN = r'\(' t_CLOSE_PAREN = r'\)' t_OPEN_BRACKET = r'\[' t_CLOSE_BRACKET = r'\]' # NOTE THE ORDERING OF THESE RULES IS IMPORTANT!! # Regular expression rules for simple tokens def t_UFLOAT(t): r'((\d+\.?\d+)|(\.\d+))([eE][+-]?\d+)?' if not re.search(r'[eE\.]', t.value): t.type = 'UINT' t.value = int(t.value) else: t.value = float(t.value) return t def t_UINT(t): r'\d+' t.value = int(t.value) return t def t_SIGN(t): r'[+-](?=\d)' t.value = float(t.value + '1') return t def t_X(t): # multiplication for factor in front of unit r'[x×]' return t def t_UNIT(t): r'\%|°|\\h|((?!\d)\w)+' t.value = cls._get_unit(t) return t def t_DIMENSIONLESS(t): r'---|-' # These are separate from t_UNIT since they cannot have a prefactor. t.value = cls._get_unit(t) return t t_ignore = '' # Error handling rule def t_error(t): raise ValueError( f"Invalid character at col {t.lexpos}") return parsing.lex(lextab='cds_lextab', package='astropy/units', reflags=int(re.UNICODE)) @classmethod def _make_parser(cls): """ The grammar here is based on the description in the `Standards for Astronomical Catalogues 2.0 <http://vizier.u-strasbg.fr/vizier/doc/catstd-3.2.htx>`_, which is not terribly precise. The exact grammar is here is based on the YACC grammar in the `unity library <https://bitbucket.org/nxg/unity/>`_. """ tokens = cls._tokens def p_main(p): ''' main : factor combined_units | combined_units | DIMENSIONLESS | OPEN_BRACKET combined_units CLOSE_BRACKET | OPEN_BRACKET DIMENSIONLESS CLOSE_BRACKET | factor ''' from astropy.units.core import Unit from astropy.units import dex if len(p) == 3: p[0] = Unit(p[1] * p[2]) elif len(p) == 4: p[0] = dex(p[2]) else: p[0] = Unit(p[1]) def p_combined_units(p): ''' combined_units : product_of_units | division_of_units ''' p[0] = p[1] def p_product_of_units(p): ''' product_of_units : unit_expression PRODUCT combined_units | unit_expression ''' if len(p) == 4: p[0] = p[1] * p[3] else: p[0] = p[1] def p_division_of_units(p): ''' division_of_units : DIVISION unit_expression | unit_expression DIVISION combined_units ''' if len(p) == 3: p[0] = p[2] ** -1 else: p[0] = p[1] / p[3] def p_unit_expression(p): ''' unit_expression : unit_with_power | OPEN_PAREN combined_units CLOSE_PAREN ''' if len(p) == 2: p[0] = p[1] else: p[0] = p[2] def p_factor(p): ''' factor : signed_float X UINT signed_int | UINT X UINT signed_int | UINT signed_int | UINT | signed_float ''' if len(p) == 5: if p[3] != 10: raise ValueError( "Only base ten exponents are allowed in CDS") p[0] = p[1] * 10.0 ** p[4] elif len(p) == 3: if p[1] != 10: raise ValueError( "Only base ten exponents are allowed in CDS") p[0] = 10.0 ** p[2] elif len(p) == 2: p[0] = p[1] def p_unit_with_power(p): ''' unit_with_power : UNIT numeric_power | UNIT ''' if len(p) == 2: p[0] = p[1] else: p[0] = p[1] ** p[2] def p_numeric_power(p): ''' numeric_power : sign UINT ''' p[0] = p[1] * p[2] def p_sign(p): ''' sign : SIGN | ''' if len(p) == 2: p[0] = p[1] else: p[0] = 1.0 def p_signed_int(p): ''' signed_int : SIGN UINT ''' p[0] = p[1] * p[2] def p_signed_float(p): ''' signed_float : sign UINT | sign UFLOAT ''' p[0] = p[1] * p[2] def p_error(p): raise ValueError() return parsing.yacc(tabmodule='cds_parsetab', package='astropy/units') @classmethod def _get_unit(cls, t): try: return cls._parse_unit(t.value) except ValueError as e: registry = core.get_current_unit_registry() if t.value in registry.aliases: return registry.aliases[t.value] raise ValueError( f"At col {t.lexpos}, {str(e)}") @classmethod def _parse_unit(cls, unit, detailed_exception=True): if unit not in cls._units: if detailed_exception: raise ValueError( "Unit '{}' not supported by the CDS SAC " "standard. {}".format( unit, did_you_mean( unit, cls._units))) else: raise ValueError() return cls._units[unit] @classmethod def parse(cls, s, debug=False): if ' ' in s: raise ValueError('CDS unit must not contain whitespace') if not isinstance(s, str): s = s.decode('ascii') # This is a short circuit for the case where the string # is just a single unit name try: return cls._parse_unit(s, detailed_exception=False) except ValueError: try: return cls._parser.parse(s, lexer=cls._lexer, debug=debug) except ValueError as e: if str(e): raise ValueError(str(e)) else: raise ValueError("Syntax error") @staticmethod def _get_unit_name(unit): return unit.get_format_name('cds') @classmethod def _format_unit_list(cls, units): out = [] for base, power in units: if power == 1: out.append(cls._get_unit_name(base)) else: out.append(f'{cls._get_unit_name(base)}{int(power)}') return '.'.join(out) @classmethod def to_string(cls, unit): # Remove units that aren't known to the format unit = utils.decompose_to_known_units(unit, cls._get_unit_name) if isinstance(unit, core.CompositeUnit): if unit == core.dimensionless_unscaled: return '---' elif is_effectively_unity(unit.scale*100.): return '%' if unit.scale == 1: s = '' else: m, e = utils.split_mantissa_exponent(unit.scale) parts = [] if m not in ('', '1'): parts.append(m) if e: if not e.startswith('-'): e = "+" + e parts.append(f'10{e}') s = 'x'.join(parts) pairs = list(zip(unit.bases, unit.powers)) if len(pairs) > 0: pairs.sort(key=operator.itemgetter(1), reverse=True) s += cls._format_unit_list(pairs) elif isinstance(unit, core.NamedUnit): s = cls._get_unit_name(unit) return s
336bfb6b3eafd8e3b57edfab33289f8062bb6d32e4285170134ef778a0d4e310
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst # This file was automatically generated from ply. To re-generate this file, # remove it from this folder, then build astropy and run the tests in-place: # # python setup.py build_ext --inplace # pytest astropy/units # # You can then commit the changes to this file. # ogip_lextab.py. This file automatically created by PLY (version 3.11). Don't edit! _tabversion = '3.10' _lextokens = set(('CLOSE_PAREN', 'DIVISION', 'LIT10', 'OPEN_PAREN', 'SIGN', 'STAR', 'STARSTAR', 'UFLOAT', 'UINT', 'UNIT', 'UNKNOWN', 'WHITESPACE')) _lexreflags = 64 _lexliterals = '' _lexstateinfo = {'INITIAL': 'inclusive'} _lexstatere = {'INITIAL': [('(?P<t_UFLOAT>(((\\d+\\.?\\d*)|(\\.\\d+))([eE][+-]?\\d+))|(((\\d+\\.\\d*)|(\\.\\d+))([eE][+-]?\\d+)?))|(?P<t_UINT>\\d+)|(?P<t_SIGN>[+-](?=\\d))|(?P<t_X>[x×])|(?P<t_LIT10>10)|(?P<t_UNKNOWN>[Uu][Nn][Kk][Nn][Oo][Ww][Nn])|(?P<t_UNIT>[a-zA-Z][a-zA-Z_]*)|(?P<t_WHITESPACE>[ \t]+)|(?P<t_STARSTAR>\\*\\*)|(?P<t_OPEN_PAREN>\\()|(?P<t_CLOSE_PAREN>\\))|(?P<t_STAR>\\*)|(?P<t_DIVISION>/)', [None, ('t_UFLOAT', 'UFLOAT'), None, None, None, None, None, None, None, None, None, None, ('t_UINT', 'UINT'), ('t_SIGN', 'SIGN'), ('t_X', 'X'), ('t_LIT10', 'LIT10'), ('t_UNKNOWN', 'UNKNOWN'), ('t_UNIT', 'UNIT'), (None, 'WHITESPACE'), (None, 'STARSTAR'), (None, 'OPEN_PAREN'), (None, 'CLOSE_PAREN'), (None, 'STAR'), (None, 'DIVISION')])]} _lexstateignore = {'INITIAL': ''} _lexstateerrorf = {'INITIAL': 't_error'} _lexstateeoff = {}
da98f90351a20f4f67830fcb8e0b6b8d7cc6c7f88192f16cceaea3faf37d8967
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Handles the "Console" unit format. """ from . import base, core, utils class Console(base.Base): """ Output-only format for to display pretty formatting at the console. For example:: >>> import astropy.units as u >>> print(u.Ry.decompose().to_string('console')) # doctest: +FLOAT_CMP m^2 kg 2.1798721*10^-18 ------ s^2 """ _times = "*" _line = "-" @classmethod def _get_unit_name(cls, unit): return unit.get_format_name('console') @classmethod def _format_superscript(cls, number): return f'^{number}' @classmethod def _format_unit_list(cls, units): out = [] for base, power in units: if power == 1: out.append(cls._get_unit_name(base)) else: out.append('{}{}'.format( cls._get_unit_name(base), cls._format_superscript( utils.format_power(power)))) return ' '.join(out) @classmethod def format_exponential_notation(cls, val): m, ex = utils.split_mantissa_exponent(val) parts = [] if m: parts.append(m) if ex: parts.append(f"10{cls._format_superscript(ex)}") return cls._times.join(parts) @classmethod def to_string(cls, unit): if isinstance(unit, core.CompositeUnit): if unit.scale == 1: s = '' else: s = cls.format_exponential_notation(unit.scale) if len(unit.bases): positives, negatives = utils.get_grouped_by_powers( unit.bases, unit.powers) if len(negatives): if len(positives): positives = cls._format_unit_list(positives) else: positives = '1' negatives = cls._format_unit_list(negatives) l = len(s) r = max(len(positives), len(negatives)) f = f"{{0:^{l}s}} {{1:^{r}s}}" lines = [ f.format('', positives), f.format(s, cls._line * r), f.format('', negatives) ] s = '\n'.join(lines) else: positives = cls._format_unit_list(positives) s += positives elif isinstance(unit, core.NamedUnit): s = cls._get_unit_name(unit) return s
0e3f1bd7a4c1884f5cff665dac5a2f4ce070ab21785467e717215807320813e7
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst # This file was automatically generated from ply. To re-generate this file, # remove it from this folder, then build astropy and run the tests in-place: # # python setup.py build_ext --inplace # pytest astropy/units # # You can then commit the changes to this file. # generic_parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'CARET CLOSE_PAREN COMMA DOUBLE_STAR FUNCNAME OPEN_PAREN PERIOD SIGN SOLIDUS STAR UFLOAT UINT UNIT\n main : unit\n | structured_unit\n | structured_subunit\n \n structured_subunit : OPEN_PAREN structured_unit CLOSE_PAREN\n \n structured_unit : subunit COMMA\n | subunit COMMA subunit\n \n subunit : unit\n | structured_unit\n | structured_subunit\n \n unit : product_of_units\n | factor product_of_units\n | factor product product_of_units\n | division_product_of_units\n | factor division_product_of_units\n | factor product division_product_of_units\n | inverse_unit\n | factor inverse_unit\n | factor product inverse_unit\n | factor\n \n division_product_of_units : division_product_of_units division product_of_units\n | product_of_units\n \n inverse_unit : division unit_expression\n \n factor : factor_fits\n | factor_float\n | factor_int\n \n factor_float : signed_float\n | signed_float UINT signed_int\n | signed_float UINT power numeric_power\n \n factor_int : UINT\n | UINT signed_int\n | UINT power numeric_power\n | UINT UINT signed_int\n | UINT UINT power numeric_power\n \n factor_fits : UINT power OPEN_PAREN signed_int CLOSE_PAREN\n | UINT power OPEN_PAREN UINT CLOSE_PAREN\n | UINT power signed_int\n | UINT power UINT\n | UINT SIGN UINT\n | UINT OPEN_PAREN signed_int CLOSE_PAREN\n \n product_of_units : unit_expression product product_of_units\n | unit_expression product_of_units\n | unit_expression\n \n unit_expression : function\n | unit_with_power\n | OPEN_PAREN product_of_units CLOSE_PAREN\n \n unit_with_power : UNIT power numeric_power\n | UNIT numeric_power\n | UNIT\n \n numeric_power : sign UINT\n | OPEN_PAREN paren_expr CLOSE_PAREN\n \n paren_expr : sign UINT\n | signed_float\n | frac\n \n frac : sign UINT division sign UINT\n \n sign : SIGN\n |\n \n product : STAR\n | PERIOD\n \n division : SOLIDUS\n \n power : DOUBLE_STAR\n | CARET\n \n signed_int : SIGN UINT\n \n signed_float : sign UINT\n | sign UFLOAT\n \n function_name : FUNCNAME\n \n function : function_name OPEN_PAREN main CLOSE_PAREN\n ' _lr_action_items = {'OPEN_PAREN':([0,6,10,11,12,13,14,15,16,17,18,20,21,22,23,25,27,30,31,32,33,34,35,40,44,46,48,49,51,52,53,56,57,66,68,69,71,73,74,77,78,79,81,82,87,88,91,92,93,94,96,97,],[10,32,35,32,-23,-24,-25,32,-43,-44,45,-26,-59,51,55,-65,32,-57,-58,32,32,10,35,32,72,-30,-60,-61,10,55,-47,-63,-64,-45,-32,55,-37,-36,-31,-38,-27,55,-46,-49,-33,-62,-39,-28,-66,-50,-35,-34,]),'UINT':([0,10,18,19,20,21,23,24,34,35,44,47,48,49,51,52,54,55,56,57,69,70,72,75,79,84,98,99,],[18,18,43,-55,50,-59,-56,56,18,18,71,77,-60,-61,18,-56,82,-56,-63,-64,-56,88,89,88,-56,95,-56,100,]),'SOLIDUS':([0,5,6,7,10,11,12,13,14,16,17,18,20,23,26,27,28,30,31,34,35,37,41,46,51,53,56,57,58,59,62,66,67,68,71,73,74,77,78,81,82,87,88,91,92,93,94,95,96,97,],[21,-21,21,21,21,-42,-23,-24,-25,-43,-44,-29,-26,-48,-21,21,21,-57,-58,21,21,-21,-41,-30,21,-47,-63,-64,-21,21,-20,-45,-40,-32,-37,-36,-31,-38,-27,-46,-49,-33,-62,-39,-28,-66,-50,21,-35,-34,]),'UNIT':([0,6,10,11,12,13,14,15,16,17,18,20,21,23,27,30,31,32,33,34,35,40,46,51,53,56,57,66,68,71,73,74,77,78,81,82,87,88,91,92,93,94,96,97,],[23,23,23,23,-23,-24,-25,23,-43,-44,-29,-26,-59,-48,23,-57,-58,23,23,23,23,23,-30,23,-47,-63,-64,-45,-32,-37,-36,-31,-38,-27,-46,-49,-33,-62,-39,-28,-66,-50,-35,-34,]),'FUNCNAME':([0,6,10,11,12,13,14,15,16,17,18,20,21,23,27,30,31,32,33,34,35,40,46,51,53,56,57,66,68,71,73,74,77,78,81,82,87,88,91,92,93,94,96,97,],[25,25,25,25,-23,-24,-25,25,-43,-44,-29,-26,-59,-48,25,-57,-58,25,25,25,25,25,-30,25,-47,-63,-64,-45,-32,-37,-36,-31,-38,-27,-46,-49,-33,-62,-39,-28,-66,-50,-35,-34,]),'SIGN':([0,10,18,21,23,34,35,43,44,45,48,49,50,51,52,55,69,72,79,98,],[19,19,47,-59,19,19,19,70,75,70,-60,-61,70,19,19,19,19,75,19,19,]),'UFLOAT':([0,10,19,24,34,35,51,55,72,75,84,],[-56,-56,-55,57,-56,-56,-56,-56,-56,-55,57,]),'$end':([1,2,3,4,5,6,7,8,11,12,13,14,16,17,18,20,23,26,28,29,34,38,39,41,42,46,53,56,57,58,59,60,62,63,64,65,66,67,68,71,73,74,77,78,81,82,87,88,91,92,93,94,96,97,],[0,-1,-2,-3,-10,-19,-13,-16,-42,-23,-24,-25,-43,-44,-29,-26,-48,-11,-14,-17,-5,-7,-9,-41,-22,-30,-47,-63,-64,-12,-15,-18,-20,-6,-8,-4,-45,-40,-32,-37,-36,-31,-38,-27,-46,-49,-33,-62,-39,-28,-66,-50,-35,-34,]),'CLOSE_PAREN':([2,3,4,5,6,7,8,11,12,13,14,16,17,18,20,23,26,28,29,34,36,37,38,39,41,42,46,53,56,57,58,59,60,61,62,63,64,65,66,67,68,71,73,74,76,77,78,80,81,82,83,85,86,87,88,89,90,91,92,93,94,95,96,97,100,],[-1,-2,-3,-10,-19,-13,-16,-42,-23,-24,-25,-43,-44,-29,-26,-48,-11,-14,-17,-5,65,66,-7,-9,-41,-22,-30,-47,-63,-64,-12,-15,-18,66,-20,-6,-8,-4,-45,-40,-32,-37,-36,-31,91,-38,-27,93,-46,-49,94,-52,-53,-33,-62,96,97,-39,-28,-66,-50,-51,-35,-34,-54,]),'COMMA':([2,3,4,5,6,7,8,9,11,12,13,14,16,17,18,20,23,26,28,29,34,36,37,38,39,41,42,46,53,56,57,58,59,60,62,63,64,65,66,67,68,71,73,74,77,78,81,82,87,88,91,92,93,94,96,97,],[-7,-8,-9,-10,-19,-13,-16,34,-42,-23,-24,-25,-43,-44,-29,-26,-48,-11,-14,-17,-5,-8,-10,-7,-9,-41,-22,-30,-47,-63,-64,-12,-15,-18,-20,34,-8,-4,-45,-40,-32,-37,-36,-31,-38,-27,-46,-49,-33,-62,-39,-28,-66,-50,-35,-34,]),'STAR':([6,11,12,13,14,16,17,18,20,23,46,53,56,57,66,68,71,73,74,77,78,81,82,87,88,91,92,93,94,96,97,],[30,30,-23,-24,-25,-43,-44,-29,-26,-48,-30,-47,-63,-64,-45,-32,-37,-36,-31,-38,-27,-46,-49,-33,-62,-39,-28,-66,-50,-35,-34,]),'PERIOD':([6,11,12,13,14,16,17,18,20,23,46,53,56,57,66,68,71,73,74,77,78,81,82,87,88,91,92,93,94,96,97,],[31,31,-23,-24,-25,-43,-44,-29,-26,-48,-30,-47,-63,-64,-45,-32,-37,-36,-31,-38,-27,-46,-49,-33,-62,-39,-28,-66,-50,-35,-34,]),'DOUBLE_STAR':([18,23,43,50,],[48,48,48,48,]),'CARET':([18,23,43,50,],[49,49,49,49,]),} _lr_action = {} for _k, _v in _lr_action_items.items(): for _x,_y in zip(_v[0],_v[1]): if not _x in _lr_action: _lr_action[_x] = {} _lr_action[_x][_k] = _y del _lr_action_items _lr_goto_items = {'main':([0,51,],[1,80,]),'unit':([0,10,34,35,51,],[2,38,38,38,2,]),'structured_unit':([0,10,34,35,51,],[3,36,64,36,3,]),'structured_subunit':([0,10,34,35,51,],[4,39,39,39,4,]),'product_of_units':([0,6,10,11,27,32,33,34,35,40,51,],[5,26,37,41,58,61,62,5,37,67,5,]),'factor':([0,10,34,35,51,],[6,6,6,6,6,]),'division_product_of_units':([0,6,10,27,34,35,51,],[7,28,7,59,7,7,7,]),'inverse_unit':([0,6,10,27,34,35,51,],[8,29,8,60,8,8,8,]),'subunit':([0,10,34,35,51,],[9,9,63,9,9,]),'unit_expression':([0,6,10,11,15,27,32,33,34,35,40,51,],[11,11,11,11,42,11,11,11,11,11,11,11,]),'factor_fits':([0,10,34,35,51,],[12,12,12,12,12,]),'factor_float':([0,10,34,35,51,],[13,13,13,13,13,]),'factor_int':([0,10,34,35,51,],[14,14,14,14,14,]),'division':([0,6,7,10,27,28,34,35,51,59,95,],[15,15,33,15,15,33,15,15,15,33,98,]),'function':([0,6,10,11,15,27,32,33,34,35,40,51,],[16,16,16,16,16,16,16,16,16,16,16,16,]),'unit_with_power':([0,6,10,11,15,27,32,33,34,35,40,51,],[17,17,17,17,17,17,17,17,17,17,17,17,]),'signed_float':([0,10,34,35,51,55,72,],[20,20,20,20,20,85,85,]),'function_name':([0,6,10,11,15,27,32,33,34,35,40,51,],[22,22,22,22,22,22,22,22,22,22,22,22,]),'sign':([0,10,23,34,35,44,51,52,55,69,72,79,98,],[24,24,54,24,24,54,24,54,84,54,84,54,99,]),'product':([6,11,],[27,40,]),'power':([18,23,43,50,],[44,52,69,79,]),'signed_int':([18,43,44,45,50,72,],[46,68,73,76,78,90,]),'numeric_power':([23,44,52,69,79,],[53,74,81,87,92,]),'paren_expr':([55,72,],[83,83,]),'frac':([55,72,],[86,86,]),} _lr_goto = {} for _k, _v in _lr_goto_items.items(): for _x, _y in zip(_v[0], _v[1]): if not _x in _lr_goto: _lr_goto[_x] = {} _lr_goto[_x][_k] = _y del _lr_goto_items _lr_productions = [ ("S' -> main","S'",1,None,None,None), ('main -> unit','main',1,'p_main','generic.py',196), ('main -> structured_unit','main',1,'p_main','generic.py',197), ('main -> structured_subunit','main',1,'p_main','generic.py',198), ('structured_subunit -> OPEN_PAREN structured_unit CLOSE_PAREN','structured_subunit',3,'p_structured_subunit','generic.py',209), ('structured_unit -> subunit COMMA','structured_unit',2,'p_structured_unit','generic.py',218), ('structured_unit -> subunit COMMA subunit','structured_unit',3,'p_structured_unit','generic.py',219), ('subunit -> unit','subunit',1,'p_subunit','generic.py',241), ('subunit -> structured_unit','subunit',1,'p_subunit','generic.py',242), ('subunit -> structured_subunit','subunit',1,'p_subunit','generic.py',243), ('unit -> product_of_units','unit',1,'p_unit','generic.py',249), ('unit -> factor product_of_units','unit',2,'p_unit','generic.py',250), ('unit -> factor product product_of_units','unit',3,'p_unit','generic.py',251), ('unit -> division_product_of_units','unit',1,'p_unit','generic.py',252), ('unit -> factor division_product_of_units','unit',2,'p_unit','generic.py',253), ('unit -> factor product division_product_of_units','unit',3,'p_unit','generic.py',254), ('unit -> inverse_unit','unit',1,'p_unit','generic.py',255), ('unit -> factor inverse_unit','unit',2,'p_unit','generic.py',256), ('unit -> factor product inverse_unit','unit',3,'p_unit','generic.py',257), ('unit -> factor','unit',1,'p_unit','generic.py',258), ('division_product_of_units -> division_product_of_units division product_of_units','division_product_of_units',3,'p_division_product_of_units','generic.py',270), ('division_product_of_units -> product_of_units','division_product_of_units',1,'p_division_product_of_units','generic.py',271), ('inverse_unit -> division unit_expression','inverse_unit',2,'p_inverse_unit','generic.py',281), ('factor -> factor_fits','factor',1,'p_factor','generic.py',287), ('factor -> factor_float','factor',1,'p_factor','generic.py',288), ('factor -> factor_int','factor',1,'p_factor','generic.py',289), ('factor_float -> signed_float','factor_float',1,'p_factor_float','generic.py',295), ('factor_float -> signed_float UINT signed_int','factor_float',3,'p_factor_float','generic.py',296), ('factor_float -> signed_float UINT power numeric_power','factor_float',4,'p_factor_float','generic.py',297), ('factor_int -> UINT','factor_int',1,'p_factor_int','generic.py',310), ('factor_int -> UINT signed_int','factor_int',2,'p_factor_int','generic.py',311), ('factor_int -> UINT power numeric_power','factor_int',3,'p_factor_int','generic.py',312), ('factor_int -> UINT UINT signed_int','factor_int',3,'p_factor_int','generic.py',313), ('factor_int -> UINT UINT power numeric_power','factor_int',4,'p_factor_int','generic.py',314), ('factor_fits -> UINT power OPEN_PAREN signed_int CLOSE_PAREN','factor_fits',5,'p_factor_fits','generic.py',332), ('factor_fits -> UINT power OPEN_PAREN UINT CLOSE_PAREN','factor_fits',5,'p_factor_fits','generic.py',333), ('factor_fits -> UINT power signed_int','factor_fits',3,'p_factor_fits','generic.py',334), ('factor_fits -> UINT power UINT','factor_fits',3,'p_factor_fits','generic.py',335), ('factor_fits -> UINT SIGN UINT','factor_fits',3,'p_factor_fits','generic.py',336), ('factor_fits -> UINT OPEN_PAREN signed_int CLOSE_PAREN','factor_fits',4,'p_factor_fits','generic.py',337), ('product_of_units -> unit_expression product product_of_units','product_of_units',3,'p_product_of_units','generic.py',356), ('product_of_units -> unit_expression product_of_units','product_of_units',2,'p_product_of_units','generic.py',357), ('product_of_units -> unit_expression','product_of_units',1,'p_product_of_units','generic.py',358), ('unit_expression -> function','unit_expression',1,'p_unit_expression','generic.py',369), ('unit_expression -> unit_with_power','unit_expression',1,'p_unit_expression','generic.py',370), ('unit_expression -> OPEN_PAREN product_of_units CLOSE_PAREN','unit_expression',3,'p_unit_expression','generic.py',371), ('unit_with_power -> UNIT power numeric_power','unit_with_power',3,'p_unit_with_power','generic.py',380), ('unit_with_power -> UNIT numeric_power','unit_with_power',2,'p_unit_with_power','generic.py',381), ('unit_with_power -> UNIT','unit_with_power',1,'p_unit_with_power','generic.py',382), ('numeric_power -> sign UINT','numeric_power',2,'p_numeric_power','generic.py',393), ('numeric_power -> OPEN_PAREN paren_expr CLOSE_PAREN','numeric_power',3,'p_numeric_power','generic.py',394), ('paren_expr -> sign UINT','paren_expr',2,'p_paren_expr','generic.py',403), ('paren_expr -> signed_float','paren_expr',1,'p_paren_expr','generic.py',404), ('paren_expr -> frac','paren_expr',1,'p_paren_expr','generic.py',405), ('frac -> sign UINT division sign UINT','frac',5,'p_frac','generic.py',414), ('sign -> SIGN','sign',1,'p_sign','generic.py',420), ('sign -> <empty>','sign',0,'p_sign','generic.py',421), ('product -> STAR','product',1,'p_product','generic.py',430), ('product -> PERIOD','product',1,'p_product','generic.py',431), ('division -> SOLIDUS','division',1,'p_division','generic.py',437), ('power -> DOUBLE_STAR','power',1,'p_power','generic.py',443), ('power -> CARET','power',1,'p_power','generic.py',444), ('signed_int -> SIGN UINT','signed_int',2,'p_signed_int','generic.py',450), ('signed_float -> sign UINT','signed_float',2,'p_signed_float','generic.py',456), ('signed_float -> sign UFLOAT','signed_float',2,'p_signed_float','generic.py',457), ('function_name -> FUNCNAME','function_name',1,'p_function_name','generic.py',463), ('function -> function_name OPEN_PAREN main CLOSE_PAREN','function',4,'p_function','generic.py',469), ]
e0694cebcb2b0b729ec82647c089626d2d8d6d21bab6476d319e3d07933334c8
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst # This file was automatically generated from ply. To re-generate this file, # remove it from this folder, then build astropy and run the tests in-place: # # python setup.py build_ext --inplace # pytest astropy/units # # You can then commit the changes to this file. # cds_lextab.py. This file automatically created by PLY (version 3.11). Don't edit! _tabversion = '3.10' _lextokens = set(('CLOSE_BRACKET', 'CLOSE_PAREN', 'DIMENSIONLESS', 'DIVISION', 'OPEN_BRACKET', 'OPEN_PAREN', 'PRODUCT', 'SIGN', 'UFLOAT', 'UINT', 'UNIT', 'X')) _lexreflags = 32 _lexliterals = '' _lexstateinfo = {'INITIAL': 'inclusive'} _lexstatere = {'INITIAL': [('(?P<t_UFLOAT>((\\d+\\.?\\d+)|(\\.\\d+))([eE][+-]?\\d+)?)|(?P<t_UINT>\\d+)|(?P<t_SIGN>[+-](?=\\d))|(?P<t_X>[x×])|(?P<t_UNIT>\\%|°|\\\\h|((?!\\d)\\w)+)|(?P<t_DIMENSIONLESS>---|-)|(?P<t_PRODUCT>\\.)|(?P<t_OPEN_PAREN>\\()|(?P<t_CLOSE_PAREN>\\))|(?P<t_OPEN_BRACKET>\\[)|(?P<t_CLOSE_BRACKET>\\])|(?P<t_DIVISION>/)', [None, ('t_UFLOAT', 'UFLOAT'), None, None, None, None, ('t_UINT', 'UINT'), ('t_SIGN', 'SIGN'), ('t_X', 'X'), ('t_UNIT', 'UNIT'), None, ('t_DIMENSIONLESS', 'DIMENSIONLESS'), (None, 'PRODUCT'), (None, 'OPEN_PAREN'), (None, 'CLOSE_PAREN'), (None, 'OPEN_BRACKET'), (None, 'CLOSE_BRACKET'), (None, 'DIVISION')])]} _lexstateignore = {'INITIAL': ''} _lexstateerrorf = {'INITIAL': 't_error'} _lexstateeoff = {}
eef4256d0e8913a748defff955b75d8d6cf888aec0b5d126672d1505c99c8cc8
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst # This file was automatically generated from ply. To re-generate this file, # remove it from this folder, then build astropy and run the tests in-place: # # python setup.py build_ext --inplace # pytest astropy/units # # You can then commit the changes to this file. # ogip_parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'CLOSE_PAREN DIVISION LIT10 OPEN_PAREN SIGN STAR STARSTAR UFLOAT UINT UNIT UNKNOWN WHITESPACE\n main : UNKNOWN\n | complete_expression\n | scale_factor complete_expression\n | scale_factor WHITESPACE complete_expression\n \n complete_expression : product_of_units\n \n product_of_units : unit_expression\n | division unit_expression\n | product_of_units product unit_expression\n | product_of_units division unit_expression\n \n unit_expression : unit\n | UNIT OPEN_PAREN complete_expression CLOSE_PAREN\n | OPEN_PAREN complete_expression CLOSE_PAREN\n | UNIT OPEN_PAREN complete_expression CLOSE_PAREN power numeric_power\n | OPEN_PAREN complete_expression CLOSE_PAREN power numeric_power\n \n scale_factor : LIT10 power numeric_power\n | LIT10\n | signed_float\n | signed_float power numeric_power\n | signed_int power numeric_power\n \n division : DIVISION\n | WHITESPACE DIVISION\n | WHITESPACE DIVISION WHITESPACE\n | DIVISION WHITESPACE\n \n product : WHITESPACE\n | STAR\n | WHITESPACE STAR\n | WHITESPACE STAR WHITESPACE\n | STAR WHITESPACE\n \n power : STARSTAR\n \n unit : UNIT\n | UNIT power numeric_power\n \n numeric_power : UINT\n | signed_float\n | OPEN_PAREN signed_int CLOSE_PAREN\n | OPEN_PAREN signed_float CLOSE_PAREN\n | OPEN_PAREN signed_float division UINT CLOSE_PAREN\n \n sign : SIGN\n |\n \n signed_int : SIGN UINT\n \n signed_float : sign UINT\n | sign UFLOAT\n ' _lr_action_items = {'UNKNOWN':([0,],[2,]),'LIT10':([0,],[7,]),'SIGN':([0,25,26,27,28,34,47,59,63,],[13,48,-29,48,48,48,13,48,48,]),'UNIT':([0,4,7,8,11,16,17,19,20,21,22,23,24,30,31,33,36,38,39,42,43,44,45,46,49,50,54,55,60,61,67,],[15,15,-16,-17,15,15,-20,15,-21,15,15,-24,-25,-40,-41,15,-23,-20,-22,-26,-28,-15,-32,-33,-18,-19,-22,-27,-34,-35,-36,]),'OPEN_PAREN':([0,4,7,8,11,15,16,17,19,20,21,22,23,24,25,26,27,28,30,31,33,34,36,38,39,42,43,44,45,46,49,50,54,55,59,60,61,63,67,],[16,16,-16,-17,16,33,16,-20,16,-21,16,16,-24,-25,47,-29,47,47,-40,-41,16,47,-23,-20,-22,-26,-28,-15,-32,-33,-18,-19,-22,-27,47,-34,-35,47,-36,]),'DIVISION':([0,4,5,6,7,8,10,14,15,16,19,23,29,30,31,33,40,41,44,45,46,49,50,52,53,57,58,60,61,64,66,67,],[17,17,20,17,-16,-17,-6,-10,-30,17,38,20,-7,-40,-41,17,-8,-9,-15,-32,-33,-18,-19,-31,-12,17,-11,-34,-35,-14,-13,-36,]),'WHITESPACE':([0,4,6,7,8,10,14,15,16,17,19,20,24,29,30,31,33,38,40,41,42,44,45,46,49,50,52,53,57,58,60,61,64,66,67,],[5,19,23,-16,-17,-6,-10,-30,5,36,5,39,43,-7,-40,-41,5,54,-8,-9,55,-15,-32,-33,-18,-19,-31,-12,5,-11,-34,-35,-14,-13,-36,]),'UINT':([0,12,13,17,20,25,26,27,28,34,36,39,47,48,59,62,63,],[-38,30,32,-20,-21,45,-29,45,45,45,-23,-22,-38,-37,45,65,45,]),'UFLOAT':([0,12,13,25,26,27,28,34,47,48,59,63,],[-38,31,-37,-38,-29,-38,-38,-38,-38,-37,-38,-38,]),'$end':([1,2,3,6,10,14,15,18,29,30,31,37,40,41,45,46,52,53,58,60,61,64,66,67,],[0,-1,-2,-5,-6,-10,-30,-3,-7,-40,-41,-4,-8,-9,-32,-33,-31,-12,-11,-34,-35,-14,-13,-36,]),'CLOSE_PAREN':([6,10,14,15,29,30,31,32,35,40,41,45,46,51,52,53,56,57,58,60,61,64,65,66,67,],[-5,-6,-10,-30,-7,-40,-41,-39,53,-8,-9,-32,-33,58,-31,-12,60,61,-11,-34,-35,-14,67,-13,-36,]),'STAR':([6,10,14,15,23,29,30,31,40,41,45,46,52,53,58,60,61,64,66,67,],[24,-6,-10,-30,42,-7,-40,-41,-8,-9,-32,-33,-31,-12,-11,-34,-35,-14,-13,-36,]),'STARSTAR':([7,8,9,15,30,31,32,53,58,],[26,26,26,26,-40,-41,-39,26,26,]),} _lr_action = {} for _k, _v in _lr_action_items.items(): for _x,_y in zip(_v[0],_v[1]): if not _x in _lr_action: _lr_action[_x] = {} _lr_action[_x][_k] = _y del _lr_action_items _lr_goto_items = {'main':([0,],[1,]),'complete_expression':([0,4,16,19,33,],[3,18,35,37,51,]),'scale_factor':([0,],[4,]),'product_of_units':([0,4,16,19,33,],[6,6,6,6,6,]),'signed_float':([0,25,27,28,34,47,59,63,],[8,46,46,46,46,57,46,46,]),'signed_int':([0,47,],[9,56,]),'unit_expression':([0,4,11,16,19,21,22,33,],[10,10,29,10,10,40,41,10,]),'division':([0,4,6,16,19,33,57,],[11,11,22,11,11,11,62,]),'sign':([0,25,27,28,34,47,59,63,],[12,12,12,12,12,12,12,12,]),'unit':([0,4,11,16,19,21,22,33,],[14,14,14,14,14,14,14,14,]),'product':([6,],[21,]),'power':([7,8,9,15,53,58,],[25,27,28,34,59,63,]),'numeric_power':([25,27,28,34,59,63,],[44,49,50,52,64,66,]),} _lr_goto = {} for _k, _v in _lr_goto_items.items(): for _x, _y in zip(_v[0], _v[1]): if not _x in _lr_goto: _lr_goto[_x] = {} _lr_goto[_x][_k] = _y del _lr_goto_items _lr_productions = [ ("S' -> main","S'",1,None,None,None), ('main -> UNKNOWN','main',1,'p_main','ogip.py',184), ('main -> complete_expression','main',1,'p_main','ogip.py',185), ('main -> scale_factor complete_expression','main',2,'p_main','ogip.py',186), ('main -> scale_factor WHITESPACE complete_expression','main',3,'p_main','ogip.py',187), ('complete_expression -> product_of_units','complete_expression',1,'p_complete_expression','ogip.py',198), ('product_of_units -> unit_expression','product_of_units',1,'p_product_of_units','ogip.py',204), ('product_of_units -> division unit_expression','product_of_units',2,'p_product_of_units','ogip.py',205), ('product_of_units -> product_of_units product unit_expression','product_of_units',3,'p_product_of_units','ogip.py',206), ('product_of_units -> product_of_units division unit_expression','product_of_units',3,'p_product_of_units','ogip.py',207), ('unit_expression -> unit','unit_expression',1,'p_unit_expression','ogip.py',221), ('unit_expression -> UNIT OPEN_PAREN complete_expression CLOSE_PAREN','unit_expression',4,'p_unit_expression','ogip.py',222), ('unit_expression -> OPEN_PAREN complete_expression CLOSE_PAREN','unit_expression',3,'p_unit_expression','ogip.py',223), ('unit_expression -> UNIT OPEN_PAREN complete_expression CLOSE_PAREN power numeric_power','unit_expression',6,'p_unit_expression','ogip.py',224), ('unit_expression -> OPEN_PAREN complete_expression CLOSE_PAREN power numeric_power','unit_expression',5,'p_unit_expression','ogip.py',225), ('scale_factor -> LIT10 power numeric_power','scale_factor',3,'p_scale_factor','ogip.py',259), ('scale_factor -> LIT10','scale_factor',1,'p_scale_factor','ogip.py',260), ('scale_factor -> signed_float','scale_factor',1,'p_scale_factor','ogip.py',261), ('scale_factor -> signed_float power numeric_power','scale_factor',3,'p_scale_factor','ogip.py',262), ('scale_factor -> signed_int power numeric_power','scale_factor',3,'p_scale_factor','ogip.py',263), ('division -> DIVISION','division',1,'p_division','ogip.py',278), ('division -> WHITESPACE DIVISION','division',2,'p_division','ogip.py',279), ('division -> WHITESPACE DIVISION WHITESPACE','division',3,'p_division','ogip.py',280), ('division -> DIVISION WHITESPACE','division',2,'p_division','ogip.py',281), ('product -> WHITESPACE','product',1,'p_product','ogip.py',287), ('product -> STAR','product',1,'p_product','ogip.py',288), ('product -> WHITESPACE STAR','product',2,'p_product','ogip.py',289), ('product -> WHITESPACE STAR WHITESPACE','product',3,'p_product','ogip.py',290), ('product -> STAR WHITESPACE','product',2,'p_product','ogip.py',291), ('power -> STARSTAR','power',1,'p_power','ogip.py',297), ('unit -> UNIT','unit',1,'p_unit','ogip.py',303), ('unit -> UNIT power numeric_power','unit',3,'p_unit','ogip.py',304), ('numeric_power -> UINT','numeric_power',1,'p_numeric_power','ogip.py',313), ('numeric_power -> signed_float','numeric_power',1,'p_numeric_power','ogip.py',314), ('numeric_power -> OPEN_PAREN signed_int CLOSE_PAREN','numeric_power',3,'p_numeric_power','ogip.py',315), ('numeric_power -> OPEN_PAREN signed_float CLOSE_PAREN','numeric_power',3,'p_numeric_power','ogip.py',316), ('numeric_power -> OPEN_PAREN signed_float division UINT CLOSE_PAREN','numeric_power',5,'p_numeric_power','ogip.py',317), ('sign -> SIGN','sign',1,'p_sign','ogip.py',328), ('sign -> <empty>','sign',0,'p_sign','ogip.py',329), ('signed_int -> SIGN UINT','signed_int',2,'p_signed_int','ogip.py',338), ('signed_float -> sign UINT','signed_float',2,'p_signed_float','ogip.py',344), ('signed_float -> sign UFLOAT','signed_float',2,'p_signed_float','ogip.py',345), ]
4c8bb5d046c6c671fca145e6af3942b7e9dae4b204283a79b336638ee32af0e9
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ A collection of different unit formats. """ # This is pretty atrocious, but it will prevent a circular import for those # formatters that need access to the units.core module An entry for it should # exist in sys.modules since astropy.units.core imports this module import sys core = sys.modules['astropy.units.core'] from .base import Base # noqa from .generic import Generic, Unscaled # noqa from .cds import CDS # noqa from .console import Console # noqa from .fits import Fits # noqa from .latex import Latex, LatexInline # noqa from .ogip import OGIP # noqa from .unicode_format import Unicode # noqa from .vounit import VOUnit # noqa __all__ = [ 'Base', 'Generic', 'CDS', 'Console', 'Fits', 'Latex', 'LatexInline', 'OGIP', 'Unicode', 'Unscaled', 'VOUnit', 'get_format'] def _known_formats(): inout = [name for name, cls in Base.registry.items() if cls.parse.__func__ is not Base.parse.__func__] out_only = [name for name, cls in Base.registry.items() if cls.parse.__func__ is Base.parse.__func__] return (f"Valid formatter names are: {inout} for input and output, " f"and {out_only} for output only.") def get_format(format=None): """ Get a formatter by name. Parameters ---------- format : str or `astropy.units.format.Base` instance or subclass The name of the format, or the format instance or subclass itself. Returns ------- format : `astropy.units.format.Base` instance The requested formatter. """ if format is None: return Generic if isinstance(format, type) and issubclass(format, Base): return format elif not (isinstance(format, str) or format is None): raise TypeError( f"Formatter must a subclass or instance of a subclass of {Base!r} " f"or a string giving the name of the formatter. {_known_formats()}.") format_lower = format.lower() if format_lower in Base.registry: return Base.registry[format_lower] raise ValueError(f"Unknown format {format!r}. {_known_formats()}")
384e7586b394b7d9330ba6863319431211a4acdc6c0203cd65b3c9bf43c48d25
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Handles the "VOUnit" unit format. """ import copy import keyword import operator import re import warnings from . import core, generic, utils class VOUnit(generic.Generic): """ The IVOA standard for units used by the VO. This is an implementation of `Units in the VO 1.0 <http://www.ivoa.net/documents/VOUnits/>`_. """ _explicit_custom_unit_regex = re.compile( r"^[YZEPTGMkhdcmunpfazy]?'((?!\d)\w)+'$") _custom_unit_regex = re.compile(r"^((?!\d)\w)+$") _custom_units = {} @staticmethod def _generate_unit_names(): from astropy import units as u from astropy.units import required_by_vounit as uvo names = {} deprecated_names = set() bases = [ 'A', 'C', 'D', 'F', 'G', 'H', 'Hz', 'J', 'Jy', 'K', 'N', 'Ohm', 'Pa', 'R', 'Ry', 'S', 'T', 'V', 'W', 'Wb', 'a', 'adu', 'arcmin', 'arcsec', 'barn', 'beam', 'bin', 'cd', 'chan', 'count', 'ct', 'd', 'deg', 'eV', 'erg', 'g', 'h', 'lm', 'lx', 'lyr', 'm', 'mag', 'min', 'mol', 'pc', 'ph', 'photon', 'pix', 'pixel', 'rad', 'rad', 's', 'solLum', 'solMass', 'solRad', 'sr', 'u', 'voxel', 'yr' ] binary_bases = [ 'bit', 'byte', 'B' ] simple_units = [ 'Angstrom', 'angstrom', 'AU', 'au', 'Ba', 'dB', 'mas' ] si_prefixes = [ 'y', 'z', 'a', 'f', 'p', 'n', 'u', 'm', 'c', 'd', '', 'da', 'h', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' ] binary_prefixes = [ 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei' ] deprecated_units = set([ 'a', 'angstrom', 'Angstrom', 'au', 'Ba', 'barn', 'ct', 'erg', 'G', 'ph', 'pix' ]) def do_defines(bases, prefixes, skips=[]): for base in bases: for prefix in prefixes: key = prefix + base if key in skips: continue if keyword.iskeyword(key): continue names[key] = getattr(u if hasattr(u, key) else uvo, key) if base in deprecated_units: deprecated_names.add(key) do_defines(bases, si_prefixes, ['pct', 'pcount', 'yd']) do_defines(binary_bases, si_prefixes + binary_prefixes, ['dB', 'dbyte']) do_defines(simple_units, ['']) return names, deprecated_names, [] @classmethod def parse(cls, s, debug=False): if s in ('unknown', 'UNKNOWN'): return None if s == '': return core.dimensionless_unscaled # Check for excess solidi, but exclude fractional exponents (allowed) if (s.count('/') > 1 and s.count('/') - len(re.findall(r'\(\d+/\d+\)', s)) > 1): raise core.UnitsError( "'{}' contains multiple slashes, which is " "disallowed by the VOUnit standard".format(s)) result = cls._do_parse(s, debug=debug) if hasattr(result, 'function_unit'): raise ValueError("Function units are not yet supported in " "VOUnit.") return result @classmethod def _get_unit(cls, t): try: return super()._get_unit(t) except ValueError: if cls._explicit_custom_unit_regex.match(t.value): return cls._def_custom_unit(t.value) if cls._custom_unit_regex.match(t.value): warnings.warn( "Unit {!r} not supported by the VOUnit " "standard. {}".format( t.value, utils.did_you_mean_units( t.value, cls._units, cls._deprecated_units, cls._to_decomposed_alternative)), core.UnitsWarning) return cls._def_custom_unit(t.value) raise @classmethod def _parse_unit(cls, unit, detailed_exception=True): if unit not in cls._units: raise ValueError() if unit in cls._deprecated_units: utils.unit_deprecation_warning( unit, cls._units[unit], 'VOUnit', cls._to_decomposed_alternative) return cls._units[unit] @classmethod def _get_unit_name(cls, unit): # The da- and d- prefixes are discouraged. This has the # effect of adding a scale to value in the result. if isinstance(unit, core.PrefixUnit): if unit._represents.scale == 10.0: raise ValueError( "In '{}': VOUnit can not represent units with the 'da' " "(deka) prefix".format(unit)) elif unit._represents.scale == 0.1: raise ValueError( "In '{}': VOUnit can not represent units with the 'd' " "(deci) prefix".format(unit)) name = unit.get_format_name('vounit') if unit in cls._custom_units.values(): return name if name not in cls._units: raise ValueError( f"Unit {name!r} is not part of the VOUnit standard") if name in cls._deprecated_units: utils.unit_deprecation_warning( name, unit, 'VOUnit', cls._to_decomposed_alternative) return name @classmethod def _def_custom_unit(cls, unit): def def_base(name): if name in cls._custom_units: return cls._custom_units[name] if name.startswith("'"): return core.def_unit( [name[1:-1], name], format={'vounit': name}, namespace=cls._custom_units) else: return core.def_unit( name, namespace=cls._custom_units) if unit in cls._custom_units: return cls._custom_units[unit] for short, full, factor in core.si_prefixes: for prefix in short: if unit.startswith(prefix): base_name = unit[len(prefix):] base_unit = def_base(base_name) return core.PrefixUnit( [prefix + x for x in base_unit.names], core.CompositeUnit(factor, [base_unit], [1], _error_check=False), format={'vounit': prefix + base_unit.names[-1]}, namespace=cls._custom_units) return def_base(unit) @classmethod def _format_unit_list(cls, units): out = [] units.sort(key=lambda x: cls._get_unit_name(x[0]).lower()) for base, power in units: if power == 1: out.append(cls._get_unit_name(base)) else: power = utils.format_power(power) if '/' in power or '.' in power: out.append(f'{cls._get_unit_name(base)}({power})') else: out.append(f'{cls._get_unit_name(base)}**{power}') return '.'.join(out) @classmethod def to_string(cls, unit): from astropy.units import core # Remove units that aren't known to the format unit = utils.decompose_to_known_units(unit, cls._get_unit_name) if isinstance(unit, core.CompositeUnit): if unit.physical_type == 'dimensionless' and unit.scale != 1: raise core.UnitScaleError( "The VOUnit format is not able to " "represent scale for dimensionless units. " "Multiply your data by {:e}." .format(unit.scale)) s = '' if unit.scale != 1: s += f'{unit.scale:.8g}' pairs = list(zip(unit.bases, unit.powers)) pairs.sort(key=operator.itemgetter(1), reverse=True) s += cls._format_unit_list(pairs) elif isinstance(unit, core.NamedUnit): s = cls._get_unit_name(unit) return s @classmethod def _to_decomposed_alternative(cls, unit): from astropy.units import core try: s = cls.to_string(unit) except core.UnitScaleError: scale = unit.scale unit = copy.copy(unit) unit._scale = 1.0 return f'{cls.to_string(unit)} (with data multiplied by {scale})' return s
73914533ad702179ad37143d23196b09ebab8623282b3308d37a74298c6a8f98
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Handles the "LaTeX" unit format. """ import re import numpy as np from . import base, core, utils class Latex(base.Base): """ Output LaTeX to display the unit based on IAU style guidelines. Attempts to follow the `IAU Style Manual <https://www.iau.org/static/publications/stylemanual1989.pdf>`_. """ @classmethod def _latex_escape(cls, name): # This doesn't escape arbitrary LaTeX strings, but it should # be good enough for unit names which are required to be alpha # + "_" anyway. return name.replace('_', r'\_') @classmethod def _get_unit_name(cls, unit): name = unit.get_format_name('latex') if name == unit.name: return cls._latex_escape(name) return name @classmethod def _format_unit_list(cls, units): out = [] for base, power in units: base_latex = cls._get_unit_name(base) if power == 1: out.append(base_latex) else: # If the LaTeX representation of the base unit already ends with # a superscript, we need to spell out the unit to avoid double # superscripts. For example, the logic below ensures that # `u.deg**2` returns `deg^{2}` instead of `{}^{\circ}^{2}`. if re.match(r".*\^{[^}]*}$", base_latex): # ends w/ superscript? base_latex = base.short_names[0] out.append(f'{base_latex}^{{{utils.format_power(power)}}}') return r'\,'.join(out) @classmethod def _format_bases(cls, unit): positives, negatives = utils.get_grouped_by_powers( unit.bases, unit.powers) if len(negatives): if len(positives): positives = cls._format_unit_list(positives) else: positives = '1' negatives = cls._format_unit_list(negatives) s = fr'\frac{{{positives}}}{{{negatives}}}' else: positives = cls._format_unit_list(positives) s = positives return s @classmethod def to_string(cls, unit): latex_name = None if hasattr(unit, '_format'): latex_name = unit._format.get('latex') if latex_name is not None: s = latex_name elif isinstance(unit, core.CompositeUnit): if unit.scale == 1: s = '' else: s = cls.format_exponential_notation(unit.scale) + r'\,' if len(unit.bases): s += cls._format_bases(unit) elif isinstance(unit, core.NamedUnit): s = cls._latex_escape(unit.name) return fr'$\mathrm{{{s}}}$' @classmethod def format_exponential_notation(cls, val, format_spec=".8g"): """ Formats a value in exponential notation for LaTeX. Parameters ---------- val : number The value to be formatted format_spec : str, optional Format used to split up mantissa and exponent Returns ------- latex_string : str The value in exponential notation in a format suitable for LaTeX. """ if np.isfinite(val): m, ex = utils.split_mantissa_exponent(val, format_spec) parts = [] if m: parts.append(m) if ex: parts.append(f"10^{{{ex}}}") return r" \times ".join(parts) else: if np.isnan(val): return r'{\rm NaN}' elif val > 0: # positive infinity return r'\infty' else: # negative infinity return r'-\infty' class LatexInline(Latex): """ Output LaTeX to display the unit based on IAU style guidelines with negative powers. Attempts to follow the `IAU Style Manual <https://www.iau.org/static/publications/stylemanual1989.pdf>`_ and the `ApJ and AJ style guide <https://journals.aas.org/manuscript-preparation/>`_. """ name = 'latex_inline' @classmethod def _format_bases(cls, unit): return cls._format_unit_list(zip(unit.bases, unit.powers))
22647b3ae1f4ca84626542dc13e9788d57459c873b3ceae3a3f5190bf892e0e3
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Handles the "Unicode" unit format. """ from . import console, utils class Unicode(console.Console): """ Output-only format to display pretty formatting at the console using Unicode characters. For example:: >>> import astropy.units as u >>> print(u.bar.decompose().to_string('unicode')) kg 100000 ──── m s² """ _times = "×" _line = "─" @classmethod def _get_unit_name(cls, unit): return unit.get_format_name('unicode') @classmethod def format_exponential_notation(cls, val): m, ex = utils.split_mantissa_exponent(val) parts = [] if m: parts.append(m.replace('-', '−')) if ex: parts.append(f"10{cls._format_superscript(ex)}") return cls._times.join(parts) @classmethod def _format_superscript(cls, number): mapping = { '0': '⁰', '1': '¹', '2': '²', '3': '³', '4': '⁴', '5': '⁵', '6': '⁶', '7': '⁷', '8': '⁸', '9': '⁹', '-': '⁻', '−': '⁻', # This is actually a "raised omission bracket", but it's # the closest thing I could find to a superscript solidus. '/': '⸍', } output = [] for c in number: output.append(mapping[c]) return ''.join(output)
940608021a361ad77e4dfcc391a4b233e64e1ac6e5e6e0da0f2837fe6dd17e45
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst # This file was automatically generated from ply. To re-generate this file, # remove it from this folder, then build astropy and run the tests in-place: # # python setup.py build_ext --inplace # pytest astropy/units # # You can then commit the changes to this file. # generic_lextab.py. This file automatically created by PLY (version 3.11). Don't edit! _tabversion = '3.10' _lextokens = set(('CARET', 'CLOSE_PAREN', 'COMMA', 'DOUBLE_STAR', 'FUNCNAME', 'OPEN_PAREN', 'PERIOD', 'SIGN', 'SOLIDUS', 'STAR', 'UFLOAT', 'UINT', 'UNIT')) _lexreflags = 32 _lexliterals = '' _lexstateinfo = {'INITIAL': 'inclusive'} _lexstatere = {'INITIAL': [("(?P<t_UFLOAT>((\\d+\\.?\\d*)|(\\.\\d+))([eE][+-]?\\d+)?)|(?P<t_UINT>\\d+)|(?P<t_SIGN>[+-](?=\\d))|(?P<t_FUNCNAME>((sqrt)|(ln)|(exp)|(log)|(mag)|(dB)|(dex))(?=\\ *\\())|(?P<t_UNIT>%|([YZEPTGMkhdcmuµnpfazy]?'((?!\\d)\\w)+')|((?!\\d)\\w)+)|(?P<t_DOUBLE_STAR>\\*\\*)|(?P<t_COMMA>\\,)|(?P<t_STAR>\\*)|(?P<t_PERIOD>\\.)|(?P<t_CARET>\\^)|(?P<t_OPEN_PAREN>\\()|(?P<t_CLOSE_PAREN>\\))|(?P<t_SOLIDUS>/)", [None, ('t_UFLOAT', 'UFLOAT'), None, None, None, None, ('t_UINT', 'UINT'), ('t_SIGN', 'SIGN'), ('t_FUNCNAME', 'FUNCNAME'), None, None, None, None, None, None, None, None, ('t_UNIT', 'UNIT'), None, None, None, (None, 'DOUBLE_STAR'), (None, 'COMMA'), (None, 'STAR'), (None, 'PERIOD'), (None, 'CARET'), (None, 'OPEN_PAREN'), (None, 'CLOSE_PAREN'), (None, 'SOLIDUS')])]} _lexstateignore = {'INITIAL': ' '} _lexstateerrorf = {'INITIAL': 't_error'} _lexstateeoff = {}
fca8b7912322bb82f5204235be4bacc218ffa711bae1bdfa41d9a3ad37d9b88e
# Licensed under a 3-clause BSD style license - see LICENSE.rst class Base: """ The abstract base class of all unit formats. """ registry = {} def __new__(cls, *args, **kwargs): # This __new__ is to make it clear that there is no reason to # instantiate a Formatter--if you try to you'll just get back the # class return cls def __init_subclass__(cls, **kwargs): # Keep a registry of all formats. Key by the class name unless a name # is explicitly set (i.e., one *not* inherited from a superclass). if 'name' not in cls.__dict__: cls.name = cls.__name__.lower() Base.registry[cls.name] = cls super().__init_subclass__(**kwargs) @classmethod def parse(cls, s): """ Convert a string to a unit object. """ raise NotImplementedError( f"Can not parse with {cls.__name__} format") @classmethod def to_string(cls, u): """ Convert a unit object to a string. """ raise NotImplementedError( f"Can not output in {cls.__name__} format")
7a4c92e69716a87c54e51c8138192d155bd6767a92a27f74c79a3edac3bb7b01
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICNSE.rst # This module includes files automatically generated from ply (these end in # _lextab.py and _parsetab.py). To generate these files, remove them from this # folder, then build astropy and run the tests in-place: # # python setup.py build_ext --inplace # pytest astropy/units # # You can then commit the changes to the re-generated _lextab.py and # _parsetab.py files. """ Handles units in `Office of Guest Investigator Programs (OGIP) FITS files <https://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/general/ogip_93_001/>`__. """ import keyword import math import os import copy import warnings from fractions import Fraction from . import core, generic, utils from astropy.utils import parsing class OGIP(generic.Generic): """ Support the units in `Office of Guest Investigator Programs (OGIP) FITS files <https://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/general/ogip_93_001/>`__. """ _tokens = ( 'DIVISION', 'OPEN_PAREN', 'CLOSE_PAREN', 'WHITESPACE', 'STARSTAR', 'STAR', 'SIGN', 'UFLOAT', 'LIT10', 'UINT', 'UNKNOWN', 'UNIT' ) @staticmethod def _generate_unit_names(): from astropy import units as u names = {} deprecated_names = set() bases = [ 'A', 'C', 'cd', 'eV', 'F', 'g', 'H', 'Hz', 'J', 'Jy', 'K', 'lm', 'lx', 'm', 'mol', 'N', 'ohm', 'Pa', 'pc', 'rad', 's', 'S', 'sr', 'T', 'V', 'W', 'Wb' ] deprecated_bases = [] prefixes = [ 'y', 'z', 'a', 'f', 'p', 'n', 'u', 'm', 'c', 'd', '', 'da', 'h', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' ] for base in bases + deprecated_bases: for prefix in prefixes: key = prefix + base if keyword.iskeyword(key): continue names[key] = getattr(u, key) for base in deprecated_bases: for prefix in prefixes: deprecated_names.add(prefix + base) simple_units = [ 'angstrom', 'arcmin', 'arcsec', 'AU', 'barn', 'bin', 'byte', 'chan', 'count', 'day', 'deg', 'erg', 'G', 'h', 'lyr', 'mag', 'min', 'photon', 'pixel', 'voxel', 'yr' ] for unit in simple_units: names[unit] = getattr(u, unit) # Create a separate, disconnected unit for the special case of # Crab and mCrab, since OGIP doesn't define their quantities. Crab = u.def_unit(['Crab'], prefixes=False, doc='Crab (X-ray flux)') mCrab = u.Unit(10 ** -3 * Crab) names['Crab'] = Crab names['mCrab'] = mCrab deprecated_units = ['Crab', 'mCrab'] for unit in deprecated_units: deprecated_names.add(unit) # Define the function names, so we can parse them, even though # we can't use any of them (other than sqrt) meaningfully for # now. functions = [ 'log', 'ln', 'exp', 'sqrt', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'sinh', 'cosh', 'tanh' ] for name in functions: names[name] = name return names, deprecated_names, functions @classmethod def _make_lexer(cls): tokens = cls._tokens t_DIVISION = r'/' t_OPEN_PAREN = r'\(' t_CLOSE_PAREN = r'\)' t_WHITESPACE = '[ \t]+' t_STARSTAR = r'\*\*' t_STAR = r'\*' # NOTE THE ORDERING OF THESE RULES IS IMPORTANT!! # Regular expression rules for simple tokens def t_UFLOAT(t): r'(((\d+\.?\d*)|(\.\d+))([eE][+-]?\d+))|(((\d+\.\d*)|(\.\d+))([eE][+-]?\d+)?)' t.value = float(t.value) return t def t_UINT(t): r'\d+' t.value = int(t.value) return t def t_SIGN(t): r'[+-](?=\d)' t.value = float(t.value + '1') return t def t_X(t): # multiplication for factor in front of unit r'[x×]' return t def t_LIT10(t): r'10' return 10 def t_UNKNOWN(t): r'[Uu][Nn][Kk][Nn][Oo][Ww][Nn]' return None def t_UNIT(t): r'[a-zA-Z][a-zA-Z_]*' t.value = cls._get_unit(t) return t # Don't ignore whitespace t_ignore = '' # Error handling rule def t_error(t): raise ValueError( f"Invalid character at col {t.lexpos}") return parsing.lex(lextab='ogip_lextab', package='astropy/units') @classmethod def _make_parser(cls): """ The grammar here is based on the description in the `Specification of Physical Units within OGIP FITS files <https://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/general/ogip_93_001/>`__, which is not terribly precise. The exact grammar is here is based on the YACC grammar in the `unity library <https://bitbucket.org/nxg/unity/>`_. """ tokens = cls._tokens def p_main(p): ''' main : UNKNOWN | complete_expression | scale_factor complete_expression | scale_factor WHITESPACE complete_expression ''' if len(p) == 4: p[0] = p[1] * p[3] elif len(p) == 3: p[0] = p[1] * p[2] else: p[0] = p[1] def p_complete_expression(p): ''' complete_expression : product_of_units ''' p[0] = p[1] def p_product_of_units(p): ''' product_of_units : unit_expression | division unit_expression | product_of_units product unit_expression | product_of_units division unit_expression ''' if len(p) == 4: if p[2] == 'DIVISION': p[0] = p[1] / p[3] else: p[0] = p[1] * p[3] elif len(p) == 3: p[0] = p[2] ** -1 else: p[0] = p[1] def p_unit_expression(p): ''' unit_expression : unit | UNIT OPEN_PAREN complete_expression CLOSE_PAREN | OPEN_PAREN complete_expression CLOSE_PAREN | UNIT OPEN_PAREN complete_expression CLOSE_PAREN power numeric_power | OPEN_PAREN complete_expression CLOSE_PAREN power numeric_power ''' # If we run p[1] in cls._functions, it will try and parse each # item in the list into a unit, which is slow. Since we know that # all the items in the list are strings, we can simply convert # p[1] to a string instead. p1_str = str(p[1]) if p1_str in cls._functions and p1_str != 'sqrt': raise ValueError( "The function '{}' is valid in OGIP, but not understood " "by astropy.units.".format( p[1])) if len(p) == 7: if p1_str == 'sqrt': p[0] = p[1] * p[3] ** (0.5 * p[6]) else: p[0] = p[1] * p[3] ** p[6] elif len(p) == 6: p[0] = p[2] ** p[5] elif len(p) == 5: if p1_str == 'sqrt': p[0] = p[3] ** 0.5 else: p[0] = p[1] * p[3] elif len(p) == 4: p[0] = p[2] else: p[0] = p[1] def p_scale_factor(p): ''' scale_factor : LIT10 power numeric_power | LIT10 | signed_float | signed_float power numeric_power | signed_int power numeric_power ''' if len(p) == 4: p[0] = 10 ** p[3] else: p[0] = p[1] # Can't use np.log10 here, because p[0] may be a Python long. if math.log10(p[0]) % 1.0 != 0.0: from astropy.units.core import UnitsWarning warnings.warn( "'{}' scale should be a power of 10 in " "OGIP format".format(p[0]), UnitsWarning) def p_division(p): ''' division : DIVISION | WHITESPACE DIVISION | WHITESPACE DIVISION WHITESPACE | DIVISION WHITESPACE ''' p[0] = 'DIVISION' def p_product(p): ''' product : WHITESPACE | STAR | WHITESPACE STAR | WHITESPACE STAR WHITESPACE | STAR WHITESPACE ''' p[0] = 'PRODUCT' def p_power(p): ''' power : STARSTAR ''' p[0] = 'POWER' def p_unit(p): ''' unit : UNIT | UNIT power numeric_power ''' if len(p) == 4: p[0] = p[1] ** p[3] else: p[0] = p[1] def p_numeric_power(p): ''' numeric_power : UINT | signed_float | OPEN_PAREN signed_int CLOSE_PAREN | OPEN_PAREN signed_float CLOSE_PAREN | OPEN_PAREN signed_float division UINT CLOSE_PAREN ''' if len(p) == 6: p[0] = Fraction(int(p[2]), int(p[4])) elif len(p) == 4: p[0] = p[2] else: p[0] = p[1] def p_sign(p): ''' sign : SIGN | ''' if len(p) == 2: p[0] = p[1] else: p[0] = 1.0 def p_signed_int(p): ''' signed_int : SIGN UINT ''' p[0] = p[1] * p[2] def p_signed_float(p): ''' signed_float : sign UINT | sign UFLOAT ''' p[0] = p[1] * p[2] def p_error(p): raise ValueError() return parsing.yacc(tabmodule='ogip_parsetab', package='astropy/units') @classmethod def _validate_unit(cls, unit, detailed_exception=True): if unit not in cls._units: if detailed_exception: raise ValueError( "Unit '{}' not supported by the OGIP " "standard. {}".format( unit, utils.did_you_mean_units( unit, cls._units, cls._deprecated_units, cls._to_decomposed_alternative))) else: raise ValueError() if unit in cls._deprecated_units: utils.unit_deprecation_warning( unit, cls._units[unit], 'OGIP', cls._to_decomposed_alternative) @classmethod def _parse_unit(cls, unit, detailed_exception=True): cls._validate_unit(unit, detailed_exception=detailed_exception) return cls._units[unit] @classmethod def parse(cls, s, debug=False): s = s.strip() try: # This is a short circuit for the case where the string is # just a single unit name return cls._parse_unit(s, detailed_exception=False) except ValueError: try: return core.Unit( cls._parser.parse(s, lexer=cls._lexer, debug=debug)) except ValueError as e: if str(e): raise else: raise ValueError( f"Syntax error parsing unit '{s}'") @classmethod def _get_unit_name(cls, unit): name = unit.get_format_name('ogip') cls._validate_unit(name) return name @classmethod def _format_unit_list(cls, units): out = [] units.sort(key=lambda x: cls._get_unit_name(x[0]).lower()) for base, power in units: if power == 1: out.append(cls._get_unit_name(base)) else: power = utils.format_power(power) if '/' in power: out.append(f'{cls._get_unit_name(base)}**({power})') else: out.append(f'{cls._get_unit_name(base)}**{power}') return ' '.join(out) @classmethod def to_string(cls, unit): # Remove units that aren't known to the format unit = utils.decompose_to_known_units(unit, cls._get_unit_name) if isinstance(unit, core.CompositeUnit): # Can't use np.log10 here, because p[0] may be a Python long. if math.log10(unit.scale) % 1.0 != 0.0: warnings.warn( f"'{unit.scale}' scale should be a power of 10 in OGIP format", core.UnitsWarning) return generic._to_string(cls, unit) @classmethod def _to_decomposed_alternative(cls, unit): # Remove units that aren't known to the format unit = utils.decompose_to_known_units(unit, cls._get_unit_name) if isinstance(unit, core.CompositeUnit): # Can't use np.log10 here, because p[0] may be a Python long. if math.log10(unit.scale) % 1.0 != 0.0: scale = unit.scale unit = copy.copy(unit) unit._scale = 1.0 return '{} (with data multiplied by {})'.format( generic._to_string(cls, unit), scale) return generic._to_string(unit)
621bc9736ae1f6cf20037bf5872b2c3e625b934f040e6a84b5d2ce008eb425cf
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Utilities shared by the different formats. """ import warnings from fractions import Fraction from astropy.utils.misc import did_you_mean from ..utils import maybe_simple_fraction def get_grouped_by_powers(bases, powers): """ Groups the powers and bases in the given `~astropy.units.CompositeUnit` into positive powers and negative powers for easy display on either side of a solidus. Parameters ---------- bases : list of `astropy.units.UnitBase` instances powers : list of int Returns ------- positives, negatives : tuple of lists Each element in each list is tuple of the form (*base*, *power*). The negatives have the sign of their power reversed (i.e. the powers are all positive). """ positive = [] negative = [] for base, power in zip(bases, powers): if power < 0: negative.append((base, -power)) elif power > 0: positive.append((base, power)) else: raise ValueError("Unit with 0 power") return positive, negative def split_mantissa_exponent(v, format_spec=".8g"): """ Given a number, split it into its mantissa and base 10 exponent parts, each as strings. If the exponent is too small, it may be returned as the empty string. Parameters ---------- v : float format_spec : str, optional Number representation formatting string Returns ------- mantissa, exponent : tuple of strings """ x = format(v, format_spec).split('e') if x[0] != '1.' + '0' * (len(x[0]) - 2): m = x[0] else: m = '' if len(x) == 2: ex = x[1].lstrip("0+") if len(ex) > 0 and ex[0] == '-': ex = '-' + ex[1:].lstrip('0') else: ex = '' return m, ex def decompose_to_known_units(unit, func): """ Partially decomposes a unit so it is only composed of units that are "known" to a given format. Parameters ---------- unit : `~astropy.units.UnitBase` instance func : callable This function will be called to determine if a given unit is "known". If the unit is not known, this function should raise a `ValueError`. Returns ------- unit : `~astropy.units.UnitBase` instance A flattened unit. """ from astropy.units import core if isinstance(unit, core.CompositeUnit): new_unit = core.Unit(unit.scale) for base, power in zip(unit.bases, unit.powers): new_unit = new_unit * decompose_to_known_units(base, func) ** power return new_unit elif isinstance(unit, core.NamedUnit): try: func(unit) except ValueError: if isinstance(unit, core.Unit): return decompose_to_known_units(unit._represents, func) raise return unit else: raise TypeError("unit argument must be a 'NamedUnit' or 'CompositeUnit', " f"not {type(unit)}") def format_power(power): """ Converts a value for a power (which may be floating point or a `fractions.Fraction` object), into a string looking like either an integer or a fraction, if the power is close to that. """ if not hasattr(power, 'denominator'): power = maybe_simple_fraction(power) if getattr(power, 'denonimator', None) == 1: power = power.nominator return str(power) def _try_decomposed(unit, format_decomposed): represents = getattr(unit, '_represents', None) if represents is not None: try: represents_string = format_decomposed(represents) except ValueError: pass else: return represents_string decomposed = unit.decompose() if decomposed is not unit: try: decompose_string = format_decomposed(decomposed) except ValueError: pass else: return decompose_string return None def did_you_mean_units(s, all_units, deprecated_units, format_decomposed): """ A wrapper around `astropy.utils.misc.did_you_mean` that deals with the display of deprecated units. Parameters ---------- s : str The invalid unit string all_units : dict A mapping from valid unit names to unit objects. deprecated_units : sequence The deprecated unit names format_decomposed : callable A function to turn a decomposed version of the unit into a string. Should return `None` if not possible Returns ------- msg : str A string message with a list of alternatives, or the empty string. """ def fix_deprecated(x): if x in deprecated_units: results = [x + ' (deprecated)'] decomposed = _try_decomposed( all_units[x], format_decomposed) if decomposed is not None: results.append(decomposed) return results return (x,) return did_you_mean(s, all_units, fix=fix_deprecated) def unit_deprecation_warning(s, unit, standard_name, format_decomposed): """ Raises a UnitsWarning about a deprecated unit in a given format. Suggests a decomposed alternative if one is available. Parameters ---------- s : str The deprecated unit name. unit : astropy.units.core.UnitBase The unit object. standard_name : str The name of the format for which the unit is deprecated. format_decomposed : callable A function to turn a decomposed version of the unit into a string. Should return `None` if not possible """ from astropy.units.core import UnitsWarning message = f"The unit '{s}' has been deprecated in the {standard_name} standard." decomposed = _try_decomposed(unit, format_decomposed) if decomposed is not None: message += f" Suggested: {decomposed}." warnings.warn(message, UnitsWarning)
80176c99196c647054dfc444bbbd62a7b70d29b5847ee634eb51ec0feb87d8db
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst # This file was automatically generated from ply. To re-generate this file, # remove it from this folder, then build astropy and run the tests in-place: # # python setup.py build_ext --inplace # pytest astropy/units # # You can then commit the changes to this file. # cds_parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'CLOSE_BRACKET CLOSE_PAREN DIMENSIONLESS DIVISION OPEN_BRACKET OPEN_PAREN PRODUCT SIGN UFLOAT UINT UNIT X\n main : factor combined_units\n | combined_units\n | DIMENSIONLESS\n | OPEN_BRACKET combined_units CLOSE_BRACKET\n | OPEN_BRACKET DIMENSIONLESS CLOSE_BRACKET\n | factor\n \n combined_units : product_of_units\n | division_of_units\n \n product_of_units : unit_expression PRODUCT combined_units\n | unit_expression\n \n division_of_units : DIVISION unit_expression\n | unit_expression DIVISION combined_units\n \n unit_expression : unit_with_power\n | OPEN_PAREN combined_units CLOSE_PAREN\n \n factor : signed_float X UINT signed_int\n | UINT X UINT signed_int\n | UINT signed_int\n | UINT\n | signed_float\n \n unit_with_power : UNIT numeric_power\n | UNIT\n \n numeric_power : sign UINT\n \n sign : SIGN\n |\n \n signed_int : SIGN UINT\n \n signed_float : sign UINT\n | sign UFLOAT\n ' _lr_action_items = {'DIMENSIONLESS':([0,5,],[4,19,]),'OPEN_BRACKET':([0,],[5,]),'UINT':([0,10,13,16,20,21,23,31,],[7,24,-23,-24,34,35,36,40,]),'DIVISION':([0,2,5,6,7,11,14,15,16,22,24,25,26,27,30,36,39,40,41,42,],[12,12,12,-19,-18,27,-13,12,-21,-17,-26,-27,12,12,-20,-25,-14,-22,-15,-16,]),'SIGN':([0,7,16,34,35,],[13,23,13,23,23,]),'UFLOAT':([0,10,13,],[-24,25,-23,]),'OPEN_PAREN':([0,2,5,6,7,12,15,22,24,25,26,27,36,41,42,],[15,15,15,-19,-18,15,15,-17,-26,-27,15,15,-25,-15,-16,]),'UNIT':([0,2,5,6,7,12,15,22,24,25,26,27,36,41,42,],[16,16,16,-19,-18,16,16,-17,-26,-27,16,16,-25,-15,-16,]),'$end':([1,2,3,4,6,7,8,9,11,14,16,17,22,24,25,28,30,32,33,36,37,38,39,40,41,42,],[0,-6,-2,-3,-19,-18,-7,-8,-10,-13,-21,-1,-17,-26,-27,-11,-20,-4,-5,-25,-9,-12,-14,-22,-15,-16,]),'X':([6,7,24,25,],[20,21,-26,-27,]),'CLOSE_BRACKET':([8,9,11,14,16,18,19,28,30,37,38,39,40,],[-7,-8,-10,-13,-21,32,33,-11,-20,-9,-12,-14,-22,]),'CLOSE_PAREN':([8,9,11,14,16,28,29,30,37,38,39,40,],[-7,-8,-10,-13,-21,-11,39,-20,-9,-12,-14,-22,]),'PRODUCT':([11,14,16,30,39,40,],[26,-13,-21,-20,-14,-22,]),} _lr_action = {} for _k, _v in _lr_action_items.items(): for _x,_y in zip(_v[0],_v[1]): if not _x in _lr_action: _lr_action[_x] = {} _lr_action[_x][_k] = _y del _lr_action_items _lr_goto_items = {'main':([0,],[1,]),'factor':([0,],[2,]),'combined_units':([0,2,5,15,26,27,],[3,17,18,29,37,38,]),'signed_float':([0,],[6,]),'product_of_units':([0,2,5,15,26,27,],[8,8,8,8,8,8,]),'division_of_units':([0,2,5,15,26,27,],[9,9,9,9,9,9,]),'sign':([0,16,],[10,31,]),'unit_expression':([0,2,5,12,15,26,27,],[11,11,11,28,11,11,11,]),'unit_with_power':([0,2,5,12,15,26,27,],[14,14,14,14,14,14,14,]),'signed_int':([7,34,35,],[22,41,42,]),'numeric_power':([16,],[30,]),} _lr_goto = {} for _k, _v in _lr_goto_items.items(): for _x, _y in zip(_v[0], _v[1]): if not _x in _lr_goto: _lr_goto[_x] = {} _lr_goto[_x][_k] = _y del _lr_goto_items _lr_productions = [ ("S' -> main","S'",1,None,None,None), ('main -> factor combined_units','main',2,'p_main','cds.py',156), ('main -> combined_units','main',1,'p_main','cds.py',157), ('main -> DIMENSIONLESS','main',1,'p_main','cds.py',158), ('main -> OPEN_BRACKET combined_units CLOSE_BRACKET','main',3,'p_main','cds.py',159), ('main -> OPEN_BRACKET DIMENSIONLESS CLOSE_BRACKET','main',3,'p_main','cds.py',160), ('main -> factor','main',1,'p_main','cds.py',161), ('combined_units -> product_of_units','combined_units',1,'p_combined_units','cds.py',174), ('combined_units -> division_of_units','combined_units',1,'p_combined_units','cds.py',175), ('product_of_units -> unit_expression PRODUCT combined_units','product_of_units',3,'p_product_of_units','cds.py',181), ('product_of_units -> unit_expression','product_of_units',1,'p_product_of_units','cds.py',182), ('division_of_units -> DIVISION unit_expression','division_of_units',2,'p_division_of_units','cds.py',191), ('division_of_units -> unit_expression DIVISION combined_units','division_of_units',3,'p_division_of_units','cds.py',192), ('unit_expression -> unit_with_power','unit_expression',1,'p_unit_expression','cds.py',201), ('unit_expression -> OPEN_PAREN combined_units CLOSE_PAREN','unit_expression',3,'p_unit_expression','cds.py',202), ('factor -> signed_float X UINT signed_int','factor',4,'p_factor','cds.py',211), ('factor -> UINT X UINT signed_int','factor',4,'p_factor','cds.py',212), ('factor -> UINT signed_int','factor',2,'p_factor','cds.py',213), ('factor -> UINT','factor',1,'p_factor','cds.py',214), ('factor -> signed_float','factor',1,'p_factor','cds.py',215), ('unit_with_power -> UNIT numeric_power','unit_with_power',2,'p_unit_with_power','cds.py',232), ('unit_with_power -> UNIT','unit_with_power',1,'p_unit_with_power','cds.py',233), ('numeric_power -> sign UINT','numeric_power',2,'p_numeric_power','cds.py',242), ('sign -> SIGN','sign',1,'p_sign','cds.py',248), ('sign -> <empty>','sign',0,'p_sign','cds.py',249), ('signed_int -> SIGN UINT','signed_int',2,'p_signed_int','cds.py',258), ('signed_float -> sign UINT','signed_float',2,'p_signed_float','cds.py',264), ('signed_float -> sign UFLOAT','signed_float',2,'p_signed_float','cds.py',265), ]
c7f52c75d80f96f5d12610fe6c488bee80479162951d247c2133b0925eb447f0
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Handles the "FITS" unit format. """ import numpy as np import copy import keyword import operator from . import core, generic, utils class Fits(generic.Generic): """ The FITS standard unit format. This supports the format defined in the Units section of the `FITS Standard <https://fits.gsfc.nasa.gov/fits_standard.html>`_. """ name = 'fits' @staticmethod def _generate_unit_names(): from astropy import units as u names = {} deprecated_names = set() # Note about deprecated units: before v2.0, several units were treated # as deprecated (G, barn, erg, Angstrom, angstrom). However, in the # FITS 3.0 standard, these units are explicitly listed in the allowed # units, but deprecated in the IAU Style Manual (McNally 1988). So # after discussion (https://github.com/astropy/astropy/issues/2933), # these units have been removed from the lists of deprecated units and # bases. bases = [ 'm', 'g', 's', 'rad', 'sr', 'K', 'A', 'mol', 'cd', 'Hz', 'J', 'W', 'V', 'N', 'Pa', 'C', 'Ohm', 'S', 'F', 'Wb', 'T', 'H', 'lm', 'lx', 'a', 'yr', 'eV', 'pc', 'Jy', 'mag', 'R', 'bit', 'byte', 'G', 'barn' ] deprecated_bases = [] prefixes = [ 'y', 'z', 'a', 'f', 'p', 'n', 'u', 'm', 'c', 'd', '', 'da', 'h', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] special_cases = {'dbyte': u.Unit('dbyte', 0.1*u.byte)} for base in bases + deprecated_bases: for prefix in prefixes: key = prefix + base if keyword.iskeyword(key): continue elif key in special_cases: names[key] = special_cases[key] else: names[key] = getattr(u, key) for base in deprecated_bases: for prefix in prefixes: deprecated_names.add(prefix + base) simple_units = [ 'deg', 'arcmin', 'arcsec', 'mas', 'min', 'h', 'd', 'Ry', 'solMass', 'u', 'solLum', 'solRad', 'AU', 'lyr', 'count', 'ct', 'photon', 'ph', 'pixel', 'pix', 'D', 'Sun', 'chan', 'bin', 'voxel', 'adu', 'beam', 'erg', 'Angstrom', 'angstrom' ] deprecated_units = [] for unit in simple_units + deprecated_units: names[unit] = getattr(u, unit) for unit in deprecated_units: deprecated_names.add(unit) return names, deprecated_names, [] @classmethod def _validate_unit(cls, unit, detailed_exception=True): if unit not in cls._units: if detailed_exception: raise ValueError( "Unit '{}' not supported by the FITS standard. {}".format( unit, utils.did_you_mean_units( unit, cls._units, cls._deprecated_units, cls._to_decomposed_alternative))) else: raise ValueError() if unit in cls._deprecated_units: utils.unit_deprecation_warning( unit, cls._units[unit], 'FITS', cls._to_decomposed_alternative) @classmethod def _parse_unit(cls, unit, detailed_exception=True): cls._validate_unit(unit) return cls._units[unit] @classmethod def _get_unit_name(cls, unit): name = unit.get_format_name('fits') cls._validate_unit(name) return name @classmethod def to_string(cls, unit): # Remove units that aren't known to the format unit = utils.decompose_to_known_units(unit, cls._get_unit_name) parts = [] if isinstance(unit, core.CompositeUnit): base = np.log10(unit.scale) if base % 1.0 != 0.0: raise core.UnitScaleError( "The FITS unit format is not able to represent scales " "that are not powers of 10. Multiply your data by " "{:e}.".format(unit.scale)) elif unit.scale != 1.0: parts.append(f'10**{int(base)}') pairs = list(zip(unit.bases, unit.powers)) if len(pairs): pairs.sort(key=operator.itemgetter(1), reverse=True) parts.append(cls._format_unit_list(pairs)) s = ' '.join(parts) elif isinstance(unit, core.NamedUnit): s = cls._get_unit_name(unit) return s @classmethod def _to_decomposed_alternative(cls, unit): try: s = cls.to_string(unit) except core.UnitScaleError: scale = unit.scale unit = copy.copy(unit) unit._scale = 1.0 return f'{cls.to_string(unit)} (with data multiplied by {scale})' return s @classmethod def parse(cls, s, debug=False): result = super().parse(s, debug) if hasattr(result, 'function_unit'): raise ValueError("Function units are not yet supported for " "FITS units.") return result
6cded613b1b0b388c3fbdaa62ed94ac95768357c15e1b94e2304fe499a2dc80d
# Licensed under a 3-clause BSD style license - see LICENSE.rst # This module includes files automatically generated from ply (these end in # _lextab.py and _parsetab.py). To generate these files, remove them from this # folder, then build astropy and run the tests in-place: # # python setup.py build_ext --inplace # pytest astropy/units # # You can then commit the changes to the re-generated _lextab.py and # _parsetab.py files. """ Handles a "generic" string format for units """ import re import warnings from fractions import Fraction import unicodedata from . import core, utils from .base import Base from astropy.utils import classproperty, parsing from astropy.utils.misc import did_you_mean def _to_string(cls, unit): if isinstance(unit, core.CompositeUnit): parts = [] if cls._show_scale and unit.scale != 1: parts.append(f'{unit.scale:g}') if len(unit.bases): positives, negatives = utils.get_grouped_by_powers( unit.bases, unit.powers) if len(positives): parts.append(cls._format_unit_list(positives)) elif len(parts) == 0: parts.append('1') if len(negatives): parts.append('/') unit_list = cls._format_unit_list(negatives) if len(negatives) == 1: parts.append(f'{unit_list}') else: parts.append(f'({unit_list})') return ' '.join(parts) elif isinstance(unit, core.NamedUnit): return cls._get_unit_name(unit) class Generic(Base): """ A "generic" format. The syntax of the format is based directly on the FITS standard, but instead of only supporting the units that FITS knows about, it supports any unit available in the `astropy.units` namespace. """ _show_scale = True _tokens = ( 'COMMA', 'DOUBLE_STAR', 'STAR', 'PERIOD', 'SOLIDUS', 'CARET', 'OPEN_PAREN', 'CLOSE_PAREN', 'FUNCNAME', 'UNIT', 'SIGN', 'UINT', 'UFLOAT' ) @classproperty(lazy=True) def _all_units(cls): return cls._generate_unit_names() @classproperty(lazy=True) def _units(cls): return cls._all_units[0] @classproperty(lazy=True) def _deprecated_units(cls): return cls._all_units[1] @classproperty(lazy=True) def _functions(cls): return cls._all_units[2] @classproperty(lazy=True) def _parser(cls): return cls._make_parser() @classproperty(lazy=True) def _lexer(cls): return cls._make_lexer() @classmethod def _make_lexer(cls): tokens = cls._tokens t_COMMA = r'\,' t_STAR = r'\*' t_PERIOD = r'\.' t_SOLIDUS = r'/' t_DOUBLE_STAR = r'\*\*' t_CARET = r'\^' t_OPEN_PAREN = r'\(' t_CLOSE_PAREN = r'\)' # NOTE THE ORDERING OF THESE RULES IS IMPORTANT!! # Regular expression rules for simple tokens def t_UFLOAT(t): r'((\d+\.?\d*)|(\.\d+))([eE][+-]?\d+)?' if not re.search(r'[eE\.]', t.value): t.type = 'UINT' t.value = int(t.value) elif t.value.endswith('.'): t.type = 'UINT' t.value = int(t.value[:-1]) else: t.value = float(t.value) return t def t_UINT(t): r'\d+' t.value = int(t.value) return t def t_SIGN(t): r'[+-](?=\d)' t.value = int(t.value + '1') return t # This needs to be a function so we can force it to happen # before t_UNIT def t_FUNCNAME(t): r'((sqrt)|(ln)|(exp)|(log)|(mag)|(dB)|(dex))(?=\ *\()' return t def t_UNIT(t): "%|([YZEPTGMkhdcmu\N{MICRO SIGN}npfazy]?'((?!\\d)\\w)+')|((?!\\d)\\w)+" t.value = cls._get_unit(t) return t t_ignore = ' ' # Error handling rule def t_error(t): raise ValueError( f"Invalid character at col {t.lexpos}") return parsing.lex(lextab='generic_lextab', package='astropy/units', reflags=int(re.UNICODE)) @classmethod def _make_parser(cls): """ The grammar here is based on the description in the `FITS standard <http://fits.gsfc.nasa.gov/standard30/fits_standard30aa.pdf>`_, Section 4.3, which is not terribly precise. The exact grammar is here is based on the YACC grammar in the `unity library <https://bitbucket.org/nxg/unity/>`_. This same grammar is used by the `"fits"` and `"vounit"` formats, the only difference being the set of available unit strings. """ tokens = cls._tokens def p_main(p): ''' main : unit | structured_unit | structured_subunit ''' if isinstance(p[1], tuple): # Unpack possible StructuredUnit inside a tuple, ie., # ignore any set of very outer parentheses. p[0] = p[1][0] else: p[0] = p[1] def p_structured_subunit(p): ''' structured_subunit : OPEN_PAREN structured_unit CLOSE_PAREN ''' # We hide a structured unit enclosed by parentheses inside # a tuple, so that we can easily distinguish units like # "(au, au/day), yr" from "au, au/day, yr". p[0] = (p[2],) def p_structured_unit(p): ''' structured_unit : subunit COMMA | subunit COMMA subunit ''' from ..structured import StructuredUnit inputs = (p[1],) if len(p) == 3 else (p[1], p[3]) units = () for subunit in inputs: if isinstance(subunit, tuple): # Structured unit that should be its own entry in the # new StructuredUnit (was enclosed in parentheses). units += subunit elif isinstance(subunit, StructuredUnit): # Structured unit whose entries should be # individiually added to the new StructuredUnit. units += subunit.values() else: # Regular unit to be added to the StructuredUnit. units += (subunit,) p[0] = StructuredUnit(units) def p_subunit(p): ''' subunit : unit | structured_unit | structured_subunit ''' p[0] = p[1] def p_unit(p): ''' unit : product_of_units | factor product_of_units | factor product product_of_units | division_product_of_units | factor division_product_of_units | factor product division_product_of_units | inverse_unit | factor inverse_unit | factor product inverse_unit | factor ''' from astropy.units.core import Unit if len(p) == 2: p[0] = Unit(p[1]) elif len(p) == 3: p[0] = Unit(p[1] * p[2]) elif len(p) == 4: p[0] = Unit(p[1] * p[3]) def p_division_product_of_units(p): ''' division_product_of_units : division_product_of_units division product_of_units | product_of_units ''' from astropy.units.core import Unit if len(p) == 4: p[0] = Unit(p[1] / p[3]) else: p[0] = p[1] def p_inverse_unit(p): ''' inverse_unit : division unit_expression ''' p[0] = p[2] ** -1 def p_factor(p): ''' factor : factor_fits | factor_float | factor_int ''' p[0] = p[1] def p_factor_float(p): ''' factor_float : signed_float | signed_float UINT signed_int | signed_float UINT power numeric_power ''' if cls.name == 'fits': raise ValueError("Numeric factor not supported by FITS") if len(p) == 4: p[0] = p[1] * p[2] ** float(p[3]) elif len(p) == 5: p[0] = p[1] * p[2] ** float(p[4]) elif len(p) == 2: p[0] = p[1] def p_factor_int(p): ''' factor_int : UINT | UINT signed_int | UINT power numeric_power | UINT UINT signed_int | UINT UINT power numeric_power ''' if cls.name == 'fits': raise ValueError("Numeric factor not supported by FITS") if len(p) == 2: p[0] = p[1] elif len(p) == 3: p[0] = p[1] ** float(p[2]) elif len(p) == 4: if isinstance(p[2], int): p[0] = p[1] * p[2] ** float(p[3]) else: p[0] = p[1] ** float(p[3]) elif len(p) == 5: p[0] = p[1] * p[2] ** p[4] def p_factor_fits(p): ''' factor_fits : UINT power OPEN_PAREN signed_int CLOSE_PAREN | UINT power OPEN_PAREN UINT CLOSE_PAREN | UINT power signed_int | UINT power UINT | UINT SIGN UINT | UINT OPEN_PAREN signed_int CLOSE_PAREN ''' if p[1] != 10: if cls.name == 'fits': raise ValueError("Base must be 10") else: return if len(p) == 4: if p[2] in ('**', '^'): p[0] = 10 ** p[3] else: p[0] = 10 ** (p[2] * p[3]) elif len(p) == 5: p[0] = 10 ** p[3] elif len(p) == 6: p[0] = 10 ** p[4] def p_product_of_units(p): ''' product_of_units : unit_expression product product_of_units | unit_expression product_of_units | unit_expression ''' if len(p) == 2: p[0] = p[1] elif len(p) == 3: p[0] = p[1] * p[2] else: p[0] = p[1] * p[3] def p_unit_expression(p): ''' unit_expression : function | unit_with_power | OPEN_PAREN product_of_units CLOSE_PAREN ''' if len(p) == 2: p[0] = p[1] else: p[0] = p[2] def p_unit_with_power(p): ''' unit_with_power : UNIT power numeric_power | UNIT numeric_power | UNIT ''' if len(p) == 2: p[0] = p[1] elif len(p) == 3: p[0] = p[1] ** p[2] else: p[0] = p[1] ** p[3] def p_numeric_power(p): ''' numeric_power : sign UINT | OPEN_PAREN paren_expr CLOSE_PAREN ''' if len(p) == 3: p[0] = p[1] * p[2] elif len(p) == 4: p[0] = p[2] def p_paren_expr(p): ''' paren_expr : sign UINT | signed_float | frac ''' if len(p) == 3: p[0] = p[1] * p[2] else: p[0] = p[1] def p_frac(p): ''' frac : sign UINT division sign UINT ''' p[0] = Fraction(p[1] * p[2], p[4] * p[5]) def p_sign(p): ''' sign : SIGN | ''' if len(p) == 2: p[0] = p[1] else: p[0] = 1 def p_product(p): ''' product : STAR | PERIOD ''' pass def p_division(p): ''' division : SOLIDUS ''' pass def p_power(p): ''' power : DOUBLE_STAR | CARET ''' p[0] = p[1] def p_signed_int(p): ''' signed_int : SIGN UINT ''' p[0] = p[1] * p[2] def p_signed_float(p): ''' signed_float : sign UINT | sign UFLOAT ''' p[0] = p[1] * p[2] def p_function_name(p): ''' function_name : FUNCNAME ''' p[0] = p[1] def p_function(p): ''' function : function_name OPEN_PAREN main CLOSE_PAREN ''' if p[1] == 'sqrt': p[0] = p[3] ** 0.5 return elif p[1] in ('mag', 'dB', 'dex'): function_unit = cls._parse_unit(p[1]) # In Generic, this is callable, but that does not have to # be the case in subclasses (e.g., in VOUnit it is not). if callable(function_unit): p[0] = function_unit(p[3]) return raise ValueError(f"'{p[1]}' is not a recognized function") def p_error(p): raise ValueError() return parsing.yacc(tabmodule='generic_parsetab', package='astropy/units') @classmethod def _get_unit(cls, t): try: return cls._parse_unit(t.value) except ValueError as e: registry = core.get_current_unit_registry() if t.value in registry.aliases: return registry.aliases[t.value] raise ValueError( f"At col {t.lexpos}, {str(e)}") @classmethod def _parse_unit(cls, s, detailed_exception=True): registry = core.get_current_unit_registry().registry if s in cls._unit_symbols: s = cls._unit_symbols[s] elif not s.isascii(): if s[0] == '\N{MICRO SIGN}': s = 'u' + s[1:] if s[-1] in cls._prefixable_unit_symbols: s = s[:-1] + cls._prefixable_unit_symbols[s[-1]] elif len(s) > 1 and s[-1] in cls._unit_suffix_symbols: s = s[:-1] + cls._unit_suffix_symbols[s[-1]] elif s.endswith('R\N{INFINITY}'): s = s[:-2] + 'Ry' if s in registry: return registry[s] if detailed_exception: raise ValueError( f'{s} is not a valid unit. {did_you_mean(s, registry)}') else: raise ValueError() _unit_symbols = { '%': 'percent', '\N{PRIME}': 'arcmin', '\N{DOUBLE PRIME}': 'arcsec', '\N{MODIFIER LETTER SMALL H}': 'hourangle', 'e\N{SUPERSCRIPT MINUS}': 'electron', } _prefixable_unit_symbols = { '\N{GREEK CAPITAL LETTER OMEGA}': 'Ohm', '\N{LATIN CAPITAL LETTER A WITH RING ABOVE}': 'Angstrom', '\N{SCRIPT SMALL L}': 'l', } _unit_suffix_symbols = { '\N{CIRCLED DOT OPERATOR}': 'sun', '\N{SUN}': 'sun', '\N{CIRCLED PLUS}': 'earth', '\N{EARTH}': 'earth', '\N{JUPITER}': 'jupiter', '\N{LATIN SUBSCRIPT SMALL LETTER E}': '_e', '\N{LATIN SUBSCRIPT SMALL LETTER P}': '_p', } _translations = str.maketrans({ '\N{GREEK SMALL LETTER MU}': '\N{MICRO SIGN}', '\N{MINUS SIGN}': '-', }) """Character translations that should be applied before parsing a string. Note that this does explicitly *not* generally translate MICRO SIGN to u, since then a string like 'µ' would be interpreted as unit mass. """ _superscripts = ( '\N{SUPERSCRIPT MINUS}' '\N{SUPERSCRIPT PLUS SIGN}' '\N{SUPERSCRIPT ZERO}' '\N{SUPERSCRIPT ONE}' '\N{SUPERSCRIPT TWO}' '\N{SUPERSCRIPT THREE}' '\N{SUPERSCRIPT FOUR}' '\N{SUPERSCRIPT FIVE}' '\N{SUPERSCRIPT SIX}' '\N{SUPERSCRIPT SEVEN}' '\N{SUPERSCRIPT EIGHT}' '\N{SUPERSCRIPT NINE}' ) _superscript_translations = str.maketrans(_superscripts, '-+0123456789') _regex_superscript = re.compile(f'[{_superscripts}]?[{_superscripts[2:]}]+') _regex_deg = re.compile('°([CF])?') @classmethod def _convert_superscript(cls, m): return f'({m.group().translate(cls._superscript_translations)})' @classmethod def _convert_deg(cls, m): if len(m.string) == 1: return 'deg' return m.string.replace('°', 'deg_') @classmethod def parse(cls, s, debug=False): if not isinstance(s, str): s = s.decode('ascii') elif not s.isascii(): # common normalization of unicode strings to avoid # having to deal with multiple representations of # the same character. This normalizes to "composed" form # and will e.g. convert OHM SIGN to GREEK CAPITAL LETTER OMEGA s = unicodedata.normalize('NFC', s) # Translate some basic unicode items that we'd like to support on # input but are not standard. s = s.translate(cls._translations) # TODO: might the below be better done in the parser/lexer? # Translate superscripts to parenthesized numbers; this ensures # that mixes of superscripts and regular numbers fail. s = cls._regex_superscript.sub(cls._convert_superscript, s) # Translate possible degrees. s = cls._regex_deg.sub(cls._convert_deg, s) result = cls._do_parse(s, debug=debug) # Check for excess solidi, but exclude fractional exponents (accepted) n_slashes = s.count('/') if n_slashes > 1 and (n_slashes - len(re.findall(r'\(\d+/\d+\)', s))) > 1: warnings.warn( "'{}' contains multiple slashes, which is " "discouraged by the FITS standard".format(s), core.UnitsWarning) return result @classmethod def _do_parse(cls, s, debug=False): try: # This is a short circuit for the case where the string # is just a single unit name return cls._parse_unit(s, detailed_exception=False) except ValueError as e: try: return cls._parser.parse(s, lexer=cls._lexer, debug=debug) except ValueError as e: if str(e): raise else: raise ValueError(f"Syntax error parsing unit '{s}'") @classmethod def _get_unit_name(cls, unit): return unit.get_format_name('generic') @classmethod def _format_unit_list(cls, units): out = [] units.sort(key=lambda x: cls._get_unit_name(x[0]).lower()) for base, power in units: if power == 1: out.append(cls._get_unit_name(base)) else: power = utils.format_power(power) if '/' in power or '.' in power: out.append(f'{cls._get_unit_name(base)}({power})') else: out.append(f'{cls._get_unit_name(base)}{power}') return ' '.join(out) @classmethod def to_string(cls, unit): return _to_string(cls, unit) class Unscaled(Generic): """ A format that doesn't display the scale part of the unit, other than that, it is identical to the `Generic` format. This is used in some error messages where the scale is irrelevant. """ _show_scale = False
05b30f9e7e1071078ec18a4ce3fcf596156a5944a52a190c9937229f1472ff7e
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst # The idea for this module (but no code) was borrowed from the # quantities (http://pythonhosted.org/quantities/) package. """Helper functions for Quantity. In particular, this implements the logic that determines scaling and result units for a given ufunc, given input units. """ from fractions import Fraction import numpy as np from . import UFUNC_HELPERS, UNSUPPORTED_UFUNCS from astropy.units.core import ( UnitsError, UnitConversionError, UnitTypeError, dimensionless_unscaled, get_current_unit_registry, unit_scale_converter) def _d(unit): if unit is None: return dimensionless_unscaled else: return unit def get_converter(from_unit, to_unit): """Like Unit._get_converter, except returns None if no scaling is needed, i.e., if the inferred scale is unity.""" converter = from_unit._get_converter(to_unit) return None if converter is unit_scale_converter else converter def get_converters_and_unit(f, unit1, unit2): converters = [None, None] # By default, we try adjusting unit2 to unit1, so that the result will # be unit1 as well. But if there is no second unit, we have to try # adjusting unit1 (to dimensionless, see below). if unit2 is None: if unit1 is None: # No units for any input -- e.g., np.add(a1, a2, out=q) return converters, dimensionless_unscaled changeable = 0 # swap units. unit2 = unit1 unit1 = None elif unit2 is unit1: # ensure identical units is fast ("==" is slow, so avoid that). return converters, unit1 else: changeable = 1 # Try to get a converter from unit2 to unit1. if unit1 is None: try: converters[changeable] = get_converter(unit2, dimensionless_unscaled) except UnitsError: # special case: would be OK if unitless number is zero, inf, nan converters[1-changeable] = False return converters, unit2 else: return converters, dimensionless_unscaled else: try: converters[changeable] = get_converter(unit2, unit1) except UnitsError: raise UnitConversionError( "Can only apply '{}' function to quantities " "with compatible dimensions" .format(f.__name__)) return converters, unit1 # SINGLE ARGUMENT UFUNC HELPERS # # The functions below take a single argument, which is the quantity upon which # the ufunc is being used. The output of the helper function should be two # values: a list with a single converter to be used to scale the input before # it is being passed to the ufunc (or None if no conversion is needed), and # the unit the output will be in. def helper_onearg_test(f, unit): return ([None], None) def helper_invariant(f, unit): return ([None], _d(unit)) def helper_square(f, unit): return ([None], unit ** 2 if unit is not None else dimensionless_unscaled) def helper_reciprocal(f, unit): return ([None], unit ** -1 if unit is not None else dimensionless_unscaled) one_half = 0.5 # faster than Fraction(1, 2) one_third = Fraction(1, 3) def helper_sqrt(f, unit): return ([None], unit ** one_half if unit is not None else dimensionless_unscaled) def helper_cbrt(f, unit): return ([None], (unit ** one_third if unit is not None else dimensionless_unscaled)) def helper_modf(f, unit): if unit is None: return [None], (dimensionless_unscaled, dimensionless_unscaled) try: return ([get_converter(unit, dimensionless_unscaled)], (dimensionless_unscaled, dimensionless_unscaled)) except UnitsError: raise UnitTypeError("Can only apply '{}' function to " "dimensionless quantities" .format(f.__name__)) def helper__ones_like(f, unit): return [None], dimensionless_unscaled def helper_dimensionless_to_dimensionless(f, unit): if unit is None: return [None], dimensionless_unscaled try: return ([get_converter(unit, dimensionless_unscaled)], dimensionless_unscaled) except UnitsError: raise UnitTypeError("Can only apply '{}' function to " "dimensionless quantities" .format(f.__name__)) def helper_dimensionless_to_radian(f, unit): from astropy.units.si import radian if unit is None: return [None], radian try: return [get_converter(unit, dimensionless_unscaled)], radian except UnitsError: raise UnitTypeError("Can only apply '{}' function to " "dimensionless quantities" .format(f.__name__)) def helper_degree_to_radian(f, unit): from astropy.units.si import degree, radian try: return [get_converter(unit, degree)], radian except UnitsError: raise UnitTypeError("Can only apply '{}' function to " "quantities with angle units" .format(f.__name__)) def helper_radian_to_degree(f, unit): from astropy.units.si import degree, radian try: return [get_converter(unit, radian)], degree except UnitsError: raise UnitTypeError("Can only apply '{}' function to " "quantities with angle units" .format(f.__name__)) def helper_radian_to_dimensionless(f, unit): from astropy.units.si import radian try: return [get_converter(unit, radian)], dimensionless_unscaled except UnitsError: raise UnitTypeError("Can only apply '{}' function to " "quantities with angle units" .format(f.__name__)) def helper_frexp(f, unit): if not unit.is_unity(): raise UnitTypeError("Can only apply '{}' function to " "unscaled dimensionless quantities" .format(f.__name__)) return [None], (None, None) # TWO ARGUMENT UFUNC HELPERS # # The functions below take a two arguments. The output of the helper function # should be two values: a tuple of two converters to be used to scale the # inputs before being passed to the ufunc (None if no conversion is needed), # and the unit the output will be in. def helper_multiplication(f, unit1, unit2): return [None, None], _d(unit1) * _d(unit2) def helper_division(f, unit1, unit2): return [None, None], _d(unit1) / _d(unit2) def helper_power(f, unit1, unit2): # TODO: find a better way to do this, currently need to signal that one # still needs to raise power of unit1 in main code if unit2 is None: return [None, None], False try: return [None, get_converter(unit2, dimensionless_unscaled)], False except UnitsError: raise UnitTypeError("Can only raise something to a " "dimensionless quantity") def helper_ldexp(f, unit1, unit2): if unit2 is not None: raise TypeError("Cannot use ldexp with a quantity " "as second argument.") else: return [None, None], _d(unit1) def helper_copysign(f, unit1, unit2): # if first arg is not a quantity, just return plain array if unit1 is None: return [None, None], None else: return [None, None], unit1 def helper_heaviside(f, unit1, unit2): try: converter2 = (get_converter(unit2, dimensionless_unscaled) if unit2 is not None else None) except UnitsError: raise UnitTypeError("Can only apply 'heaviside' function with a " "dimensionless second argument.") return ([None, converter2], dimensionless_unscaled) def helper_two_arg_dimensionless(f, unit1, unit2): try: converter1 = (get_converter(unit1, dimensionless_unscaled) if unit1 is not None else None) converter2 = (get_converter(unit2, dimensionless_unscaled) if unit2 is not None else None) except UnitsError: raise UnitTypeError("Can only apply '{}' function to " "dimensionless quantities" .format(f.__name__)) return ([converter1, converter2], dimensionless_unscaled) # This used to be a separate function that just called get_converters_and_unit. # Using it directly saves a few us; keeping the clearer name. helper_twoarg_invariant = get_converters_and_unit def helper_twoarg_comparison(f, unit1, unit2): converters, _ = get_converters_and_unit(f, unit1, unit2) return converters, None def helper_twoarg_invtrig(f, unit1, unit2): from astropy.units.si import radian converters, _ = get_converters_and_unit(f, unit1, unit2) return converters, radian def helper_twoarg_floor_divide(f, unit1, unit2): converters, _ = get_converters_and_unit(f, unit1, unit2) return converters, dimensionless_unscaled def helper_divmod(f, unit1, unit2): converters, result_unit = get_converters_and_unit(f, unit1, unit2) return converters, (dimensionless_unscaled, result_unit) def helper_clip(f, unit1, unit2, unit3): # Treat the array being clipped as primary. converters = [None] if unit1 is None: result_unit = dimensionless_unscaled try: converters += [(None if unit is None else get_converter(unit, dimensionless_unscaled)) for unit in (unit2, unit3)] except UnitsError: raise UnitConversionError( "Can only apply '{}' function to quantities with " "compatible dimensions".format(f.__name__)) else: result_unit = unit1 for unit in unit2, unit3: try: converter = get_converter(_d(unit), result_unit) except UnitsError: if unit is None: # special case: OK if unitless number is zero, inf, nan converters.append(False) else: raise UnitConversionError( "Can only apply '{}' function to quantities with " "compatible dimensions".format(f.__name__)) else: converters.append(converter) return converters, result_unit # list of ufuncs: # https://numpy.org/doc/stable/reference/ufuncs.html#available-ufuncs UNSUPPORTED_UFUNCS |= { np.bitwise_and, np.bitwise_or, np.bitwise_xor, np.invert, np.left_shift, np.right_shift, np.logical_and, np.logical_or, np.logical_xor, np.logical_not, np.isnat, np.gcd, np.lcm} # SINGLE ARGUMENT UFUNCS # ufuncs that do not care about the unit and do not return a Quantity # (but rather a boolean, or -1, 0, or +1 for np.sign). onearg_test_ufuncs = (np.isfinite, np.isinf, np.isnan, np.sign, np.signbit) for ufunc in onearg_test_ufuncs: UFUNC_HELPERS[ufunc] = helper_onearg_test # ufuncs that return a value with the same unit as the input invariant_ufuncs = (np.absolute, np.fabs, np.conj, np.conjugate, np.negative, np.spacing, np.rint, np.floor, np.ceil, np.trunc, np.positive) for ufunc in invariant_ufuncs: UFUNC_HELPERS[ufunc] = helper_invariant # ufuncs that require dimensionless input and and give dimensionless output dimensionless_to_dimensionless_ufuncs = (np.exp, np.expm1, np.exp2, np.log, np.log10, np.log2, np.log1p) # Default numpy does not ship an "erf" ufunc, but some versions hacked by # intel do. This is bad, since it means code written for that numpy will # not run on non-hacked numpy. But still, we might as well support it. if isinstance(getattr(np.core.umath, 'erf', None), np.ufunc): dimensionless_to_dimensionless_ufuncs += (np.core.umath.erf,) for ufunc in dimensionless_to_dimensionless_ufuncs: UFUNC_HELPERS[ufunc] = helper_dimensionless_to_dimensionless # ufuncs that require dimensionless input and give output in radians dimensionless_to_radian_ufuncs = (np.arccos, np.arcsin, np.arctan, np.arccosh, np.arcsinh, np.arctanh) for ufunc in dimensionless_to_radian_ufuncs: UFUNC_HELPERS[ufunc] = helper_dimensionless_to_radian # ufuncs that require input in degrees and give output in radians degree_to_radian_ufuncs = (np.radians, np.deg2rad) for ufunc in degree_to_radian_ufuncs: UFUNC_HELPERS[ufunc] = helper_degree_to_radian # ufuncs that require input in radians and give output in degrees radian_to_degree_ufuncs = (np.degrees, np.rad2deg) for ufunc in radian_to_degree_ufuncs: UFUNC_HELPERS[ufunc] = helper_radian_to_degree # ufuncs that require input in radians and give dimensionless output radian_to_dimensionless_ufuncs = (np.cos, np.sin, np.tan, np.cosh, np.sinh, np.tanh) for ufunc in radian_to_dimensionless_ufuncs: UFUNC_HELPERS[ufunc] = helper_radian_to_dimensionless # ufuncs handled as special cases UFUNC_HELPERS[np.sqrt] = helper_sqrt UFUNC_HELPERS[np.square] = helper_square UFUNC_HELPERS[np.reciprocal] = helper_reciprocal UFUNC_HELPERS[np.cbrt] = helper_cbrt UFUNC_HELPERS[np.core.umath._ones_like] = helper__ones_like UFUNC_HELPERS[np.modf] = helper_modf UFUNC_HELPERS[np.frexp] = helper_frexp # TWO ARGUMENT UFUNCS # two argument ufuncs that require dimensionless input and and give # dimensionless output two_arg_dimensionless_ufuncs = (np.logaddexp, np.logaddexp2) for ufunc in two_arg_dimensionless_ufuncs: UFUNC_HELPERS[ufunc] = helper_two_arg_dimensionless # two argument ufuncs that return a value with the same unit as the input twoarg_invariant_ufuncs = (np.add, np.subtract, np.hypot, np.maximum, np.minimum, np.fmin, np.fmax, np.nextafter, np.remainder, np.mod, np.fmod) for ufunc in twoarg_invariant_ufuncs: UFUNC_HELPERS[ufunc] = helper_twoarg_invariant # two argument ufuncs that need compatible inputs and return a boolean twoarg_comparison_ufuncs = (np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal, np.equal) for ufunc in twoarg_comparison_ufuncs: UFUNC_HELPERS[ufunc] = helper_twoarg_comparison # two argument ufuncs that do inverse trigonometry twoarg_invtrig_ufuncs = (np.arctan2,) # another private function in numpy; use getattr in case it disappears if isinstance(getattr(np.core.umath, '_arg', None), np.ufunc): twoarg_invtrig_ufuncs += (np.core.umath._arg,) for ufunc in twoarg_invtrig_ufuncs: UFUNC_HELPERS[ufunc] = helper_twoarg_invtrig # ufuncs handled as special cases UFUNC_HELPERS[np.multiply] = helper_multiplication if isinstance(getattr(np, 'matmul', None), np.ufunc): UFUNC_HELPERS[np.matmul] = helper_multiplication UFUNC_HELPERS[np.divide] = helper_division UFUNC_HELPERS[np.true_divide] = helper_division UFUNC_HELPERS[np.power] = helper_power UFUNC_HELPERS[np.ldexp] = helper_ldexp UFUNC_HELPERS[np.copysign] = helper_copysign UFUNC_HELPERS[np.floor_divide] = helper_twoarg_floor_divide UFUNC_HELPERS[np.heaviside] = helper_heaviside UFUNC_HELPERS[np.float_power] = helper_power UFUNC_HELPERS[np.divmod] = helper_divmod # Check for clip ufunc; note that np.clip is a wrapper function, not the ufunc. if isinstance(getattr(np.core.umath, 'clip', None), np.ufunc): UFUNC_HELPERS[np.core.umath.clip] = helper_clip del ufunc
56df8ce8ed3a64490a8720efb4ea8c59676759b7f9968aa7921a036a10165112
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """Converters for Quantity.""" import threading import numpy as np from astropy.units.core import (UnitsError, UnitConversionError, UnitTypeError, dimensionless_unscaled) __all__ = ['can_have_arbitrary_unit', 'converters_and_unit', 'check_output', 'UFUNC_HELPERS', 'UNSUPPORTED_UFUNCS'] class UfuncHelpers(dict): """Registry of unit conversion functions to help ufunc evaluation. Based on dict for quick access, but with a missing method to load helpers for additional modules such as scipy.special and erfa. Such modules should be registered using ``register_module``. """ def __init__(self, *args, **kwargs): self.modules = {} self.UNSUPPORTED = set() # Upper-case for backwards compatibility self._lock = threading.RLock() super().__init__(*args, **kwargs) def register_module(self, module, names, importer): """Register (but do not import) a set of ufunc helpers. Parameters ---------- module : str Name of the module with the ufuncs (e.g., 'scipy.special'). names : iterable of str Names of the module ufuncs for which helpers are available. importer : callable Function that imports the ufuncs and returns a dict of helpers keyed by those ufuncs. If the value is `None`, the ufunc is explicitly *not* supported. """ with self._lock: self.modules[module] = {'names': names, 'importer': importer} def import_module(self, module): """Import the helpers from the given module using its helper function. Parameters ---------- module : str Name of the module. Has to have been registered beforehand. """ with self._lock: module_info = self.modules.pop(module) self.update(module_info['importer']()) def __missing__(self, ufunc): """Called if a ufunc is not found. Check if the ufunc is in any of the available modules, and, if so, import the helpers for that module. """ with self._lock: # Check if it was loaded while we waited for the lock if ufunc in self: return self[ufunc] if ufunc in self.UNSUPPORTED: raise TypeError(f"Cannot use ufunc '{ufunc.__name__}' with quantities") for module, module_info in list(self.modules.items()): if ufunc.__name__ in module_info['names']: # A ufunc with the same name is supported by this module. # Of course, this doesn't necessarily mean it is the # right module. So, we try let the importer do its work. # If it fails (e.g., for `scipy.special`), then that's # fine, just raise the TypeError. If it succeeds, but # the ufunc is not found, that is also fine: we will # enter __missing__ again and either find another # module or get the TypeError there. try: self.import_module(module) except ImportError: # pragma: no cover pass else: return self[ufunc] raise TypeError("unknown ufunc {}. If you believe this ufunc " "should be supported, please raise an issue on " "https://github.com/astropy/astropy" .format(ufunc.__name__)) def __setitem__(self, key, value): # Implementation note: in principle, we could just let `None` # mean that something is not implemented, but this means an # extra if clause for the output, slowing down the common # path where a ufunc is supported. with self._lock: if value is None: self.UNSUPPORTED |= {key} self.pop(key, None) else: super().__setitem__(key, value) self.UNSUPPORTED -= {key} UFUNC_HELPERS = UfuncHelpers() UNSUPPORTED_UFUNCS = UFUNC_HELPERS.UNSUPPORTED def can_have_arbitrary_unit(value): """Test whether the items in value can have arbitrary units Numbers whose value does not change upon a unit change, i.e., zero, infinity, or not-a-number Parameters ---------- value : number or array Returns ------- bool `True` if each member is either zero or not finite, `False` otherwise """ return np.all(np.logical_or(np.equal(value, 0.), ~np.isfinite(value))) def converters_and_unit(function, method, *args): """Determine the required converters and the unit of the ufunc result. Converters are functions required to convert to a ufunc's expected unit, e.g., radian for np.sin; or to ensure units of two inputs are consistent, e.g., for np.add. In these examples, the unit of the result would be dimensionless_unscaled for np.sin, and the same consistent unit for np.add. Parameters ---------- function : `~numpy.ufunc` Numpy universal function method : str Method with which the function is evaluated, e.g., '__call__', 'reduce', etc. *args : `~astropy.units.Quantity` or ndarray subclass Input arguments to the function Raises ------ TypeError : when the specified function cannot be used with Quantities (e.g., np.logical_or), or when the routine does not know how to handle the specified function (in which case an issue should be raised on https://github.com/astropy/astropy). UnitTypeError : when the conversion to the required (or consistent) units is not possible. """ # Check whether we support this ufunc, by getting the helper function # (defined in helpers) which returns a list of function(s) that convert the # input(s) to the unit required for the ufunc, as well as the unit the # result will have (a tuple of units if there are multiple outputs). ufunc_helper = UFUNC_HELPERS[function] if method == '__call__' or (method == 'outer' and function.nin == 2): # Find out the units of the arguments passed to the ufunc; usually, # at least one is a quantity, but for two-argument ufuncs, the second # could also be a Numpy array, etc. These are given unit=None. units = [getattr(arg, 'unit', None) for arg in args] # Determine possible conversion functions, and the result unit. converters, result_unit = ufunc_helper(function, *units) if any(converter is False for converter in converters): # for multi-argument ufuncs with a quantity and a non-quantity, # the quantity normally needs to be dimensionless, *except* # if the non-quantity can have arbitrary unit, i.e., when it # is all zero, infinity or NaN. In that case, the non-quantity # can just have the unit of the quantity # (this allows, e.g., `q > 0.` independent of unit) try: # Don't fold this loop in the test above: this rare case # should not make the common case slower. for i, converter in enumerate(converters): if converter is not False: continue if can_have_arbitrary_unit(args[i]): converters[i] = None else: raise UnitConversionError( "Can only apply '{}' function to " "dimensionless quantities when other " "argument is not a quantity (unless the " "latter is all zero/infinity/nan)" .format(function.__name__)) except TypeError: # _can_have_arbitrary_unit failed: arg could not be compared # with zero or checked to be finite. Then, ufunc will fail too. raise TypeError("Unsupported operand type(s) for ufunc {}: " "'{}'".format(function.__name__, ','.join([arg.__class__.__name__ for arg in args]))) # In the case of np.power and np.float_power, the unit itself needs to # be modified by an amount that depends on one of the input values, # so we need to treat this as a special case. # TODO: find a better way to deal with this. if result_unit is False: if units[0] is None or units[0] == dimensionless_unscaled: result_unit = dimensionless_unscaled else: if units[1] is None: p = args[1] else: p = args[1].to(dimensionless_unscaled).value try: result_unit = units[0] ** p except ValueError as exc: # Changing the unit does not work for, e.g., array-shaped # power, but this is OK if we're (scaled) dimensionless. try: converters[0] = units[0]._get_converter( dimensionless_unscaled) except UnitConversionError: raise exc else: result_unit = dimensionless_unscaled else: # methods for which the unit should stay the same nin = function.nin unit = getattr(args[0], 'unit', None) if method == 'at' and nin <= 2: if nin == 1: units = [unit] else: units = [unit, getattr(args[2], 'unit', None)] converters, result_unit = ufunc_helper(function, *units) # ensure there is no 'converter' for indices (2nd argument) converters.insert(1, None) elif method in {'reduce', 'accumulate', 'reduceat'} and nin == 2: converters, result_unit = ufunc_helper(function, unit, unit) converters = converters[:1] if method == 'reduceat': # add 'scale' for indices (2nd argument) converters += [None] else: if method in {'reduce', 'accumulate', 'reduceat', 'outer'} and nin != 2: raise ValueError(f"{method} only supported for binary functions") raise TypeError("Unexpected ufunc method {}. If this should " "work, please raise an issue on" "https://github.com/astropy/astropy" .format(method)) # for all but __call__ method, scaling is not allowed if unit is not None and result_unit is None: raise TypeError("Cannot use '{1}' method on ufunc {0} with a " "Quantity instance as the result is not a " "Quantity.".format(function.__name__, method)) if (converters[0] is not None or (unit is not None and unit is not result_unit and (not result_unit.is_equivalent(unit) or result_unit.to(unit) != 1.))): # NOTE: this cannot be the more logical UnitTypeError, since # then things like np.cumprod will not longer fail (they check # for TypeError). raise UnitsError("Cannot use '{1}' method on ufunc {0} with a " "Quantity instance as it would change the unit." .format(function.__name__, method)) return converters, result_unit def check_output(output, unit, inputs, function=None): """Check that function output can be stored in the output array given. Parameters ---------- output : array or `~astropy.units.Quantity` or tuple Array that should hold the function output (or tuple of such arrays). unit : `~astropy.units.Unit` or None, or tuple Unit that the output will have, or `None` for pure numbers (should be tuple of same if output is a tuple of outputs). inputs : tuple Any input arguments. These should be castable to the output. function : callable The function that will be producing the output. If given, used to give a more informative error message. Returns ------- arrays : ndarray view or tuple thereof The view(s) is of ``output``. Raises ------ UnitTypeError : If ``unit`` is inconsistent with the class of ``output`` TypeError : If the ``inputs`` cannot be cast safely to ``output``. """ if isinstance(output, tuple): return tuple(check_output(output_, unit_, inputs, function) for output_, unit_ in zip(output, unit)) # ``None`` indicates no actual array is needed. This can happen, e.g., # with np.modf(a, out=(None, b)). if output is None: return None if hasattr(output, '__quantity_subclass__'): # Check that we're not trying to store a plain Numpy array or a # Quantity with an inconsistent unit (e.g., not angular for Angle). if unit is None: raise TypeError("Cannot store non-quantity output{} in {} " "instance".format( (f" from {function.__name__} function" if function is not None else ""), type(output))) q_cls, subok = output.__quantity_subclass__(unit) if not (subok or q_cls is type(output)): raise UnitTypeError( "Cannot store output with unit '{}'{} " "in {} instance. Use {} instance instead." .format(unit, (f" from {function.__name__} function" if function is not None else ""), type(output), q_cls)) # check we can handle the dtype (e.g., that we are not int # when float is required). Note that we only do this for Quantity # output; for array output, we defer to numpy's default handling. # Also, any structured dtype are ignored (likely erfa ufuncs). # TODO: make more logical; is this necessary at all? if inputs and not output.dtype.names: result_type = np.result_type(*inputs) if not (result_type.names or np.can_cast(result_type, output.dtype, casting='same_kind')): raise TypeError("Arguments cannot be cast safely to inplace " "output with dtype={}".format(output.dtype)) # Turn into ndarray, so we do not loop into array_wrap/array_ufunc # if the output is used to store results of a function. return output.view(np.ndarray) else: # output is not a Quantity, so cannot obtain a unit. if not (unit is None or unit is dimensionless_unscaled): raise UnitTypeError("Cannot store quantity with dimension " "{}in a non-Quantity instance." .format("" if function is None else "resulting from {} function " .format(function.__name__))) return output
9c274e60c287a02a015c54b612399a7bb1266c73883730e76dcf7442a82f9797
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Helper functions for Quantity. In particular, this implements the logic that determines scaling and result units for a given ufunc, given input units. """ from .converters import * # By importing helpers, all the unit conversion functions needed for # numpy ufuncs and functions are defined. from . import helpers, function_helpers # For scipy.special and erfa, importing the helper modules ensures # the definitions are added as modules to UFUNC_HELPERS, to be loaded # on demand. from . import scipy_special, erfa
3c8e8aeb4482bab1e04e6e7d3b2470ca4dcf3d4c81d9168ea508ae0707113ea8
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """Quantity helpers for the ERFA ufuncs.""" # Tests for these are in coordinates, not in units. from erfa import ufunc as erfa_ufunc, dt_pv, dt_eraLDBODY, dt_eraASTROM from astropy.units.core import UnitsError, UnitTypeError, dimensionless_unscaled from astropy.units.structured import StructuredUnit from . import UFUNC_HELPERS from .helpers import (get_converter, helper_invariant, helper_multiplication, helper_twoarg_invariant, _d) erfa_ufuncs = ('s2c', 's2p', 'c2s', 'p2s', 'pm', 'pdp', 'pxp', 'rxp', 'cpv', 'p2pv', 'pv2p', 'pv2s', 'pvdpv', 'pvm', 'pvmpv', 'pvppv', 'pvstar', 'pvtob', 'pvu', 'pvup', 'pvxpv', 'rxpv', 's2pv', 's2xpv', 'starpv', 'sxpv', 'trxpv', 'gd2gc', 'gc2gd', 'ldn', 'aper', 'apio', 'atciq', 'atciqn', 'atciqz', 'aticq', 'atioq', 'atoiq') def has_matching_structure(unit, dtype): dtype_fields = dtype.fields if dtype_fields: return (isinstance(unit, StructuredUnit) and len(unit) == len(dtype_fields) and all(has_matching_structure(u, df_v[0]) for (u, df_v) in zip(unit.values(), dtype_fields.values()))) else: return not isinstance(unit, StructuredUnit) def check_structured_unit(unit, dtype): if not has_matching_structure(unit, dtype): msg = {dt_pv: 'pv', dt_eraLDBODY: 'ldbody', dt_eraASTROM: 'astrom'}.get(dtype, 'function') raise UnitTypeError(f'{msg} input needs unit matching dtype={dtype}.') def helper_s2c(f, unit1, unit2): from astropy.units.si import radian try: return [get_converter(unit1, radian), get_converter(unit2, radian)], dimensionless_unscaled except UnitsError: raise UnitTypeError("Can only apply '{}' function to " "quantities with angle units" .format(f.__name__)) def helper_s2p(f, unit1, unit2, unit3): from astropy.units.si import radian try: return [get_converter(unit1, radian), get_converter(unit2, radian), None], unit3 except UnitsError: raise UnitTypeError("Can only apply '{}' function to " "quantities with angle units" .format(f.__name__)) def helper_c2s(f, unit1): from astropy.units.si import radian return [None], (radian, radian) def helper_p2s(f, unit1): from astropy.units.si import radian return [None], (radian, radian, unit1) def helper_gc2gd(f, nounit, unit1): from astropy.units.si import m, radian if nounit is not None: raise UnitTypeError("ellipsoid cannot be a quantity.") try: return [None, get_converter(unit1, m)], (radian, radian, m, None) except UnitsError: raise UnitTypeError("Can only apply '{}' function to " "quantities with length units" .format(f.__name__)) def helper_gd2gc(f, nounit, unit1, unit2, unit3): from astropy.units.si import m, radian if nounit is not None: raise UnitTypeError("ellipsoid cannot be a quantity.") try: return [None, get_converter(unit1, radian), get_converter(unit2, radian), get_converter(unit3, m)], (m, None) except UnitsError: raise UnitTypeError("Can only apply '{}' function to lon, lat " "with angle and height with length units" .format(f.__name__)) def helper_p2pv(f, unit1): from astropy.units.si import s if isinstance(unit1, StructuredUnit): raise UnitTypeError("p vector unit cannot be a structured unit.") return [None], StructuredUnit((unit1, unit1 / s)) def helper_pv2p(f, unit1): check_structured_unit(unit1, dt_pv) return [None], unit1[0] def helper_pv2s(f, unit_pv): from astropy.units.si import radian check_structured_unit(unit_pv, dt_pv) ang_unit = radian * unit_pv[1] / unit_pv[0] return [None], (radian, radian, unit_pv[0], ang_unit, ang_unit, unit_pv[1]) def helper_s2pv(f, unit_theta, unit_phi, unit_r, unit_td, unit_pd, unit_rd): from astropy.units.si import radian time_unit = unit_r / unit_rd return [get_converter(unit_theta, radian), get_converter(unit_phi, radian), None, get_converter(unit_td, radian / time_unit), get_converter(unit_pd, radian / time_unit), None], StructuredUnit((unit_r, unit_rd)) def helper_pv_multiplication(f, unit1, unit2): check_structured_unit(unit1, dt_pv) check_structured_unit(unit2, dt_pv) result_unit = StructuredUnit((unit1[0] * unit2[0], unit1[1] * unit2[0])) converter = get_converter(unit2, StructuredUnit( (unit2[0], unit1[1] * unit2[0] / unit1[0]))) return [None, converter], result_unit def helper_pvm(f, unit1): check_structured_unit(unit1, dt_pv) return [None], (unit1[0], unit1[1]) def helper_pvstar(f, unit1): from astropy.units.astrophys import AU from astropy.units.si import km, s, radian, day, year, arcsec return [get_converter(unit1, StructuredUnit((AU, AU/day)))], ( radian, radian, radian / year, radian / year, arcsec, km / s, None) def helper_starpv(f, unit_ra, unit_dec, unit_pmr, unit_pmd, unit_px, unit_rv): from astropy.units.si import km, s, day, year, radian, arcsec from astropy.units.astrophys import AU return [get_converter(unit_ra, radian), get_converter(unit_dec, radian), get_converter(unit_pmr, radian/year), get_converter(unit_pmd, radian/year), get_converter(unit_px, arcsec), get_converter(unit_rv, km/s)], (StructuredUnit((AU, AU/day)), None) def helper_pvtob(f, unit_elong, unit_phi, unit_hm, unit_xp, unit_yp, unit_sp, unit_theta): from astropy.units.si import m, s, radian return [get_converter(unit_elong, radian), get_converter(unit_phi, radian), get_converter(unit_hm, m), get_converter(unit_xp, radian), get_converter(unit_yp, radian), get_converter(unit_sp, radian), get_converter(unit_theta, radian)], StructuredUnit((m, m/s)) def helper_pvu(f, unit_t, unit_pv): check_structured_unit(unit_pv, dt_pv) return [get_converter(unit_t, unit_pv[0]/unit_pv[1]), None], unit_pv def helper_pvup(f, unit_t, unit_pv): check_structured_unit(unit_pv, dt_pv) return [get_converter(unit_t, unit_pv[0]/unit_pv[1]), None], unit_pv[0] def helper_s2xpv(f, unit1, unit2, unit_pv): check_structured_unit(unit_pv, dt_pv) return [None, None, None], StructuredUnit((_d(unit1) * unit_pv[0], _d(unit2) * unit_pv[1])) def ldbody_unit(): from astropy.units.si import day, radian from astropy.units.astrophys import Msun, AU return StructuredUnit((Msun, radian, (AU, AU/day)), erfa_ufunc.dt_eraLDBODY) def astrom_unit(): from astropy.units.si import rad, year from astropy.units.astrophys import AU one = rel2c = dimensionless_unscaled return StructuredUnit((year, AU, one, AU, rel2c, one, one, rad, rad, rad, rad, one, one, rel2c, rad, rad, rad), erfa_ufunc.dt_eraASTROM) def helper_ldn(f, unit_b, unit_ob, unit_sc): from astropy.units.astrophys import AU return [get_converter(unit_b, ldbody_unit()), get_converter(unit_ob, AU), get_converter(_d(unit_sc), dimensionless_unscaled)], dimensionless_unscaled def helper_aper(f, unit_theta, unit_astrom): check_structured_unit(unit_astrom, dt_eraASTROM) unit_along = unit_astrom[7] # along if unit_astrom[14] is unit_along: # eral result_unit = unit_astrom else: result_units = tuple((unit_along if i == 14 else v) for i, v in enumerate(unit_astrom.values())) result_unit = unit_astrom.__class__(result_units, names=unit_astrom) return [get_converter(unit_theta, unit_along), None], result_unit def helper_apio(f, unit_sp, unit_theta, unit_elong, unit_phi, unit_hm, unit_xp, unit_yp, unit_refa, unit_refb): from astropy.units.si import radian, m return [get_converter(unit_sp, radian), get_converter(unit_theta, radian), get_converter(unit_elong, radian), get_converter(unit_phi, radian), get_converter(unit_hm, m), get_converter(unit_xp, radian), get_converter(unit_xp, radian), get_converter(unit_xp, radian), get_converter(unit_xp, radian)], astrom_unit() def helper_atciq(f, unit_rc, unit_dc, unit_pr, unit_pd, unit_px, unit_rv, unit_astrom): from astropy.units.si import radian, arcsec, year, km, s return [get_converter(unit_rc, radian), get_converter(unit_dc, radian), get_converter(unit_pr, radian / year), get_converter(unit_pd, radian / year), get_converter(unit_px, arcsec), get_converter(unit_rv, km / s), get_converter(unit_astrom, astrom_unit())], (radian, radian) def helper_atciqn(f, unit_rc, unit_dc, unit_pr, unit_pd, unit_px, unit_rv, unit_astrom, unit_b): from astropy.units.si import radian, arcsec, year, km, s return [get_converter(unit_rc, radian), get_converter(unit_dc, radian), get_converter(unit_pr, radian / year), get_converter(unit_pd, radian / year), get_converter(unit_px, arcsec), get_converter(unit_rv, km / s), get_converter(unit_astrom, astrom_unit()), get_converter(unit_b, ldbody_unit())], (radian, radian) def helper_atciqz_aticq(f, unit_rc, unit_dc, unit_astrom): from astropy.units.si import radian return [get_converter(unit_rc, radian), get_converter(unit_dc, radian), get_converter(unit_astrom, astrom_unit())], (radian, radian) def helper_aticqn(f, unit_rc, unit_dc, unit_astrom, unit_b): from astropy.units.si import radian return [get_converter(unit_rc, radian), get_converter(unit_dc, radian), get_converter(unit_astrom, astrom_unit()), get_converter(unit_b, ldbody_unit())], (radian, radian) def helper_atioq(f, unit_rc, unit_dc, unit_astrom): from astropy.units.si import radian return [get_converter(unit_rc, radian), get_converter(unit_dc, radian), get_converter(unit_astrom, astrom_unit())], (radian,)*5 def helper_atoiq(f, unit_type, unit_ri, unit_di, unit_astrom): from astropy.units.si import radian if unit_type is not None: raise UnitTypeError("argument 'type' should not have a unit") return [None, get_converter(unit_ri, radian), get_converter(unit_di, radian), get_converter(unit_astrom, astrom_unit())], (radian, radian) def get_erfa_helpers(): ERFA_HELPERS = {} ERFA_HELPERS[erfa_ufunc.s2c] = helper_s2c ERFA_HELPERS[erfa_ufunc.s2p] = helper_s2p ERFA_HELPERS[erfa_ufunc.c2s] = helper_c2s ERFA_HELPERS[erfa_ufunc.p2s] = helper_p2s ERFA_HELPERS[erfa_ufunc.pm] = helper_invariant ERFA_HELPERS[erfa_ufunc.cpv] = helper_invariant ERFA_HELPERS[erfa_ufunc.p2pv] = helper_p2pv ERFA_HELPERS[erfa_ufunc.pv2p] = helper_pv2p ERFA_HELPERS[erfa_ufunc.pv2s] = helper_pv2s ERFA_HELPERS[erfa_ufunc.pvdpv] = helper_pv_multiplication ERFA_HELPERS[erfa_ufunc.pvxpv] = helper_pv_multiplication ERFA_HELPERS[erfa_ufunc.pvm] = helper_pvm ERFA_HELPERS[erfa_ufunc.pvmpv] = helper_twoarg_invariant ERFA_HELPERS[erfa_ufunc.pvppv] = helper_twoarg_invariant ERFA_HELPERS[erfa_ufunc.pvstar] = helper_pvstar ERFA_HELPERS[erfa_ufunc.pvtob] = helper_pvtob ERFA_HELPERS[erfa_ufunc.pvu] = helper_pvu ERFA_HELPERS[erfa_ufunc.pvup] = helper_pvup ERFA_HELPERS[erfa_ufunc.pdp] = helper_multiplication ERFA_HELPERS[erfa_ufunc.pxp] = helper_multiplication ERFA_HELPERS[erfa_ufunc.rxp] = helper_multiplication ERFA_HELPERS[erfa_ufunc.rxpv] = helper_multiplication ERFA_HELPERS[erfa_ufunc.s2pv] = helper_s2pv ERFA_HELPERS[erfa_ufunc.s2xpv] = helper_s2xpv ERFA_HELPERS[erfa_ufunc.starpv] = helper_starpv ERFA_HELPERS[erfa_ufunc.sxpv] = helper_multiplication ERFA_HELPERS[erfa_ufunc.trxpv] = helper_multiplication ERFA_HELPERS[erfa_ufunc.gc2gd] = helper_gc2gd ERFA_HELPERS[erfa_ufunc.gd2gc] = helper_gd2gc ERFA_HELPERS[erfa_ufunc.ldn] = helper_ldn ERFA_HELPERS[erfa_ufunc.aper] = helper_aper ERFA_HELPERS[erfa_ufunc.apio] = helper_apio ERFA_HELPERS[erfa_ufunc.atciq] = helper_atciq ERFA_HELPERS[erfa_ufunc.atciqn] = helper_atciqn ERFA_HELPERS[erfa_ufunc.atciqz] = helper_atciqz_aticq ERFA_HELPERS[erfa_ufunc.aticq] = helper_atciqz_aticq ERFA_HELPERS[erfa_ufunc.aticqn] = helper_aticqn ERFA_HELPERS[erfa_ufunc.atioq] = helper_atioq ERFA_HELPERS[erfa_ufunc.atoiq] = helper_atoiq return ERFA_HELPERS UFUNC_HELPERS.register_module('erfa.ufunc', erfa_ufuncs, get_erfa_helpers)
5b20e9673a6f23728f091533c138ec761829e2d38e94e5856609858510817ff2
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license. See LICENSE.rst except # for parts explicitly labelled as being (largely) copies of numpy # implementations; for those, see licenses/NUMPY_LICENSE.rst. """Helpers for overriding numpy functions. We override numpy functions in `~astropy.units.Quantity.__array_function__`. In this module, the numpy functions are split in four groups, each of which has an associated `set` or `dict`: 1. SUBCLASS_SAFE_FUNCTIONS (set), if the numpy implementation supports Quantity; we pass on to ndarray.__array_function__. 2. FUNCTION_HELPERS (dict), if the numpy implementation is usable after converting quantities to arrays with suitable units, and possibly setting units on the result. 3. DISPATCHED_FUNCTIONS (dict), if the function makes sense but requires a Quantity-specific implementation 4. UNSUPPORTED_FUNCTIONS (set), if the function does not make sense. For the FUNCTION_HELPERS `dict`, the value is a function that does the unit conversion. It should take the same arguments as the numpy function would (though one can use ``*args`` and ``**kwargs``) and return a tuple of ``args, kwargs, unit, out``, where ``args`` and ``kwargs`` will be will be passed on to the numpy implementation, ``unit`` is a possible unit of the result (`None` if it should not be converted to Quantity), and ``out`` is a possible output Quantity passed in, which will be filled in-place. For the DISPATCHED_FUNCTIONS `dict`, the value is a function that implements the numpy functionality for Quantity input. It should return a tuple of ``result, unit, out``, where ``result`` is generally a plain array with the result, and ``unit`` and ``out`` are as above. If unit is `None`, result gets returned directly, so one can also return a Quantity directly using ``quantity_result, None, None``. """ import functools import operator import numpy as np from numpy.lib import recfunctions as rfn from astropy.units.core import ( UnitsError, UnitTypeError, dimensionless_unscaled) from astropy.utils.compat import NUMPY_LT_1_20, NUMPY_LT_1_23 from astropy.utils import isiterable # In 1.17, overrides are enabled by default, but it is still possible to # turn them off using an environment variable. We use getattr since it # is planned to remove that possibility in later numpy versions. ARRAY_FUNCTION_ENABLED = getattr(np.core.overrides, 'ENABLE_ARRAY_FUNCTION', True) SUBCLASS_SAFE_FUNCTIONS = set() """Functions with implementations supporting subclasses like Quantity.""" FUNCTION_HELPERS = {} """Functions with implementations usable with proper unit conversion.""" DISPATCHED_FUNCTIONS = {} """Functions for which we provide our own implementation.""" UNSUPPORTED_FUNCTIONS = set() """Functions that cannot sensibly be used with quantities.""" SUBCLASS_SAFE_FUNCTIONS |= { np.shape, np.size, np.ndim, np.reshape, np.ravel, np.moveaxis, np.rollaxis, np.swapaxes, np.transpose, np.atleast_1d, np.atleast_2d, np.atleast_3d, np.expand_dims, np.squeeze, np.broadcast_to, np.broadcast_arrays, np.flip, np.fliplr, np.flipud, np.rot90, np.argmin, np.argmax, np.argsort, np.lexsort, np.searchsorted, np.nonzero, np.argwhere, np.flatnonzero, np.diag_indices_from, np.triu_indices_from, np.tril_indices_from, np.real, np.imag, np.diagonal, np.diagflat, np.empty_like, np.compress, np.extract, np.delete, np.trim_zeros, np.roll, np.take, np.put, np.fill_diagonal, np.tile, np.repeat, np.split, np.array_split, np.hsplit, np.vsplit, np.dsplit, np.stack, np.column_stack, np.hstack, np.vstack, np.dstack, np.amax, np.amin, np.ptp, np.sum, np.cumsum, np.prod, np.product, np.cumprod, np.cumproduct, np.round, np.around, np.fix, np.angle, np.i0, np.clip, np.isposinf, np.isneginf, np.isreal, np.iscomplex, np.average, np.mean, np.std, np.var, np.median, np.trace, np.nanmax, np.nanmin, np.nanargmin, np.nanargmax, np.nanmean, np.nanmedian, np.nansum, np.nancumsum, np.nanstd, np.nanvar, np.nanprod, np.nancumprod, np.einsum_path, np.trapz, np.linspace, np.sort, np.msort, np.partition, np.meshgrid, np.common_type, np.result_type, np.can_cast, np.min_scalar_type, np.iscomplexobj, np.isrealobj, np.shares_memory, np.may_share_memory, np.apply_along_axis, np.take_along_axis, np.put_along_axis, np.linalg.cond, np.linalg.multi_dot} # Implemented as methods on Quantity: # np.ediff1d is from setops, but we support it anyway; the others # currently return NotImplementedError. # TODO: move latter to UNSUPPORTED? Would raise TypeError instead. SUBCLASS_SAFE_FUNCTIONS |= {np.ediff1d} # Nonsensical for quantities. UNSUPPORTED_FUNCTIONS |= { np.packbits, np.unpackbits, np.unravel_index, np.ravel_multi_index, np.ix_, np.cov, np.corrcoef, np.busday_count, np.busday_offset, np.datetime_as_string, np.is_busday, np.all, np.any, np.sometrue, np.alltrue} # Could be supported if we had a natural logarithm unit. UNSUPPORTED_FUNCTIONS |= {np.linalg.slogdet} # TODO! support whichever of these functions it makes sense to support TBD_FUNCTIONS = { rfn.drop_fields, rfn.rename_fields, rfn.append_fields, rfn.join_by, rfn.apply_along_fields, rfn.assign_fields_by_name, rfn.merge_arrays, rfn.find_duplicates, rfn.recursive_fill_fields, rfn.require_fields, rfn.repack_fields, rfn.stack_arrays } UNSUPPORTED_FUNCTIONS |= TBD_FUNCTIONS # The following are not just unsupported, but so unlikely to be thought # to be supported that we ignore them in testing. (Kept in a separate # variable so that we can check consistency in the test routine - # test_quantity_non_ufuncs.py) IGNORED_FUNCTIONS = { # I/O - useless for Quantity, since no way to store the unit. np.save, np.savez, np.savetxt, np.savez_compressed, # Polynomials np.poly, np.polyadd, np.polyder, np.polydiv, np.polyfit, np.polyint, np.polymul, np.polysub, np.polyval, np.roots, np.vander, # functions taking record arrays (which are deprecated) rfn.rec_append_fields, rfn.rec_drop_fields, rfn.rec_join, } if NUMPY_LT_1_20: # financial IGNORED_FUNCTIONS |= {np.fv, np.ipmt, np.irr, np.mirr, np.nper, np.npv, np.pmt, np.ppmt, np.pv, np.rate} if NUMPY_LT_1_23: IGNORED_FUNCTIONS |= { # Deprecated, removed in numpy 1.23 np.asscalar, np.alen, } UNSUPPORTED_FUNCTIONS |= IGNORED_FUNCTIONS class FunctionAssigner: def __init__(self, assignments): self.assignments = assignments def __call__(self, f=None, helps=None, module=np): """Add a helper to a numpy function. Normally used as a decorator. If ``helps`` is given, it should be the numpy function helped (or an iterable of numpy functions helped). If ``helps`` is not given, it is assumed the function helped is the numpy function with the same name as the decorated function. """ if f is not None: if helps is None: helps = getattr(module, f.__name__) if not isiterable(helps): helps = (helps,) for h in helps: self.assignments[h] = f return f elif helps is not None or module is not np: return functools.partial(self.__call__, helps=helps, module=module) else: # pragma: no cover raise ValueError("function_helper requires at least one argument.") function_helper = FunctionAssigner(FUNCTION_HELPERS) dispatched_function = FunctionAssigner(DISPATCHED_FUNCTIONS) @function_helper(helps={ np.copy, np.asfarray, np.real_if_close, np.sort_complex, np.resize, np.fft.fft, np.fft.ifft, np.fft.rfft, np.fft.irfft, np.fft.fft2, np.fft.ifft2, np.fft.rfft2, np.fft.irfft2, np.fft.fftn, np.fft.ifftn, np.fft.rfftn, np.fft.irfftn, np.fft.hfft, np.fft.ihfft, np.linalg.eigvals, np.linalg.eigvalsh}) def invariant_a_helper(a, *args, **kwargs): return (a.view(np.ndarray),) + args, kwargs, a.unit, None @function_helper(helps={np.tril, np.triu}) def invariant_m_helper(m, *args, **kwargs): return (m.view(np.ndarray),) + args, kwargs, m.unit, None @function_helper(helps={np.fft.fftshift, np.fft.ifftshift}) def invariant_x_helper(x, *args, **kwargs): return (x.view(np.ndarray),) + args, kwargs, x.unit, None # Note that ones_like does *not* work by default since if one creates an empty # array with a unit, one cannot just fill it with unity. Indeed, in this # respect, it is a bit of an odd function for Quantity. On the other hand, it # matches the idea that a unit is the same as the quantity with that unit and # value of 1. Also, it used to work without __array_function__. # zeros_like does work by default for regular quantities, because numpy first # creates an empty array with the unit and then fills it with 0 (which can have # any unit), but for structured dtype this fails (0 cannot have an arbitrary # structured unit), so we include it here too. @function_helper(helps={np.ones_like, np.zeros_like}) def like_helper(a, *args, **kwargs): subok = args[2] if len(args) > 2 else kwargs.pop('subok', True) unit = a.unit if subok else None return (a.view(np.ndarray),) + args, kwargs, unit, None @function_helper def sinc(x): from astropy.units.si import radian try: x = x.to_value(radian) except UnitsError: raise UnitTypeError("Can only apply 'sinc' function to " "quantities with angle units") return (x,), {}, dimensionless_unscaled, None @dispatched_function def unwrap(p, discont=None, axis=-1): from astropy.units.si import radian if discont is None: discont = np.pi << radian p, discont = _as_quantities(p, discont) result = np.unwrap.__wrapped__(p.to_value(radian), discont.to_value(radian), axis=axis) result = radian.to(p.unit, result) return result, p.unit, None @function_helper def argpartition(a, *args, **kwargs): return (a.view(np.ndarray),) + args, kwargs, None, None @function_helper def full_like(a, fill_value, *args, **kwargs): unit = a.unit if kwargs.get('subok', True) else None return (a.view(np.ndarray), a._to_own_unit(fill_value)) + args, kwargs, unit, None @function_helper def putmask(a, mask, values): from astropy.units import Quantity if isinstance(a, Quantity): return (a.view(np.ndarray), mask, a._to_own_unit(values)), {}, a.unit, None elif isinstance(values, Quantity): return (a, mask, values.to_value(dimensionless_unscaled)), {}, None, None else: raise NotImplementedError @function_helper def place(arr, mask, vals): from astropy.units import Quantity if isinstance(arr, Quantity): return (arr.view(np.ndarray), mask, arr._to_own_unit(vals)), {}, arr.unit, None elif isinstance(vals, Quantity): return (arr, mask, vals.to_value(dimensionless_unscaled)), {}, None, None else: raise NotImplementedError @function_helper def copyto(dst, src, *args, **kwargs): from astropy.units import Quantity if isinstance(dst, Quantity): return ((dst.view(np.ndarray), dst._to_own_unit(src)) + args, kwargs, None, None) elif isinstance(src, Quantity): return ((dst, src.to_value(dimensionless_unscaled)) + args, kwargs, None, None) else: raise NotImplementedError @function_helper def nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None): nan = x._to_own_unit(nan) if posinf is not None: posinf = x._to_own_unit(posinf) if neginf is not None: neginf = x._to_own_unit(neginf) return ((x.view(np.ndarray),), dict(copy=True, nan=nan, posinf=posinf, neginf=neginf), x.unit, None) def _as_quantity(a): """Convert argument to a Quantity (or raise NotImplementedError).""" from astropy.units import Quantity try: return Quantity(a, copy=False, subok=True) except Exception: # If we cannot convert to Quantity, we should just bail. raise NotImplementedError def _as_quantities(*args): """Convert arguments to Quantity (or raise NotImplentedError).""" from astropy.units import Quantity try: return tuple(Quantity(a, copy=False, subok=True) for a in args) except Exception: # If we cannot convert to Quantity, we should just bail. raise NotImplementedError def _quantities2arrays(*args, unit_from_first=False): """Convert to arrays in units of the first argument that has a unit. If unit_from_first, take the unit of the first argument regardless whether it actually defined a unit (e.g., dimensionless for arrays). """ # Turn first argument into a quantity. q = _as_quantity(args[0]) if len(args) == 1: return (q.value,), q.unit # If we care about the unit being explicit, then check whether this # argument actually had a unit, or was likely inferred. if not unit_from_first and (q.unit is q._default_unit and not hasattr(args[0], 'unit')): # Here, the argument could still be things like [10*u.one, 11.*u.one]), # i.e., properly dimensionless. So, we only override with anything # that has a unit not equivalent to dimensionless (fine to ignore other # dimensionless units pass, even if explicitly given). for arg in args[1:]: trial = _as_quantity(arg) if not trial.unit.is_equivalent(q.unit): # Use any explicit unit not equivalent to dimensionless. q = trial break # We use the private _to_own_unit method here instead of just # converting everything to quantity and then do .to_value(qs0.unit) # as we want to allow arbitrary unit for 0, inf, and nan. try: arrays = tuple((q._to_own_unit(arg)) for arg in args) except TypeError: raise NotImplementedError return arrays, q.unit def _iterable_helper(*args, out=None, **kwargs): """Convert arguments to Quantity, and treat possible 'out'.""" from astropy.units import Quantity if out is not None: if isinstance(out, Quantity): kwargs['out'] = out.view(np.ndarray) else: # TODO: for an ndarray output, we could in principle # try converting all Quantity to dimensionless. raise NotImplementedError arrays, unit = _quantities2arrays(*args) return arrays, kwargs, unit, out @function_helper def concatenate(arrays, axis=0, out=None): # TODO: make this smarter by creating an appropriately shaped # empty output array and just filling it. arrays, kwargs, unit, out = _iterable_helper(*arrays, out=out, axis=axis) return (arrays,), kwargs, unit, out @dispatched_function def block(arrays): # We need to override block since the numpy implementation can take two # different paths, one for concatenation, one for creating a large empty # result array in which parts are set. Each assumes array input and # cannot be used directly. Since it would be very costly to inspect all # arrays and then turn them back into a nested list, we just copy here the # second implementation, np.core.shape_base._block_slicing, since it is # shortest and easiest. (arrays, list_ndim, result_ndim, final_size) = np.core.shape_base._block_setup(arrays) shape, slices, arrays = np.core.shape_base._block_info_recursion( arrays, list_ndim, result_ndim) # Here, one line of difference! arrays, unit = _quantities2arrays(*arrays) # Back to _block_slicing dtype = np.result_type(*[arr.dtype for arr in arrays]) F_order = all(arr.flags['F_CONTIGUOUS'] for arr in arrays) C_order = all(arr.flags['C_CONTIGUOUS'] for arr in arrays) order = 'F' if F_order and not C_order else 'C' result = np.empty(shape=shape, dtype=dtype, order=order) for the_slice, arr in zip(slices, arrays): result[(Ellipsis,) + the_slice] = arr return result, unit, None @function_helper def choose(a, choices, out=None, **kwargs): choices, kwargs, unit, out = _iterable_helper(*choices, out=out, **kwargs) return (a, choices,), kwargs, unit, out @function_helper def select(condlist, choicelist, default=0): choicelist, kwargs, unit, out = _iterable_helper(*choicelist) if default != 0: default = (1 * unit)._to_own_unit(default) return (condlist, choicelist, default), kwargs, unit, out @dispatched_function def piecewise(x, condlist, funclist, *args, **kw): from astropy.units import Quantity # Copied implementation from numpy.lib.function_base.piecewise, # taking care of units of function outputs. n2 = len(funclist) # undocumented: single condition is promoted to a list of one condition if np.isscalar(condlist) or ( not isinstance(condlist[0], (list, np.ndarray)) and x.ndim != 0): condlist = [condlist] if any(isinstance(c, Quantity) for c in condlist): raise NotImplementedError condlist = np.array(condlist, dtype=bool) n = len(condlist) if n == n2 - 1: # compute the "otherwise" condition. condelse = ~np.any(condlist, axis=0, keepdims=True) condlist = np.concatenate([condlist, condelse], axis=0) n += 1 elif n != n2: raise ValueError( f"with {n} condition(s), either {n} or {n + 1} functions are expected" ) y = np.zeros(x.shape, x.dtype) where = [] what = [] for k in range(n): item = funclist[k] if not callable(item): where.append(condlist[k]) what.append(item) else: vals = x[condlist[k]] if vals.size > 0: where.append(condlist[k]) what.append(item(vals, *args, **kw)) what, unit = _quantities2arrays(*what) for item, value in zip(where, what): y[item] = value return y, unit, None @function_helper def append(arr, values, *args, **kwargs): arrays, unit = _quantities2arrays(arr, values, unit_from_first=True) return arrays + args, kwargs, unit, None @function_helper def insert(arr, obj, values, *args, **kwargs): from astropy.units import Quantity if isinstance(obj, Quantity): raise NotImplementedError (arr, values), unit = _quantities2arrays(arr, values, unit_from_first=True) return (arr, obj, values) + args, kwargs, unit, None @function_helper def pad(array, pad_width, mode='constant', **kwargs): # pad dispatches only on array, so that must be a Quantity. for key in 'constant_values', 'end_values': value = kwargs.pop(key, None) if value is None: continue if not isinstance(value, tuple): value = (value,) new_value = [] for v in value: new_value.append( tuple(array._to_own_unit(_v) for _v in v) if isinstance(v, tuple) else array._to_own_unit(v)) kwargs[key] = new_value return (array.view(np.ndarray), pad_width, mode), kwargs, array.unit, None @function_helper def where(condition, *args): from astropy.units import Quantity if isinstance(condition, Quantity) or len(args) != 2: raise NotImplementedError args, unit = _quantities2arrays(*args) return (condition,) + args, {}, unit, None @function_helper(helps=({np.quantile, np.nanquantile})) def quantile(a, q, *args, _q_unit=dimensionless_unscaled, **kwargs): if len(args) >= 2: out = args[1] args = args[:1] + args[2:] else: out = kwargs.pop('out', None) from astropy.units import Quantity if isinstance(q, Quantity): q = q.to_value(_q_unit) (a,), kwargs, unit, out = _iterable_helper(a, out=out, **kwargs) return (a, q) + args, kwargs, unit, out @function_helper(helps={np.percentile, np.nanpercentile}) def percentile(a, q, *args, **kwargs): from astropy.units import percent return quantile(a, q, *args, _q_unit=percent, **kwargs) @function_helper def count_nonzero(a, *args, **kwargs): return (a.value,) + args, kwargs, None, None @function_helper(helps={np.isclose, np.allclose}) def close(a, b, rtol=1e-05, atol=1e-08, *args, **kwargs): from astropy.units import Quantity (a, b), unit = _quantities2arrays(a, b, unit_from_first=True) # Allow number without a unit as having the unit. atol = Quantity(atol, unit).value return (a, b, rtol, atol) + args, kwargs, None, None @function_helper def array_equal(a1, a2): args, unit = _quantities2arrays(a1, a2) return args, {}, None, None @function_helper def array_equiv(a1, a2): args, unit = _quantities2arrays(a1, a2) return args, {}, None, None @function_helper(helps={np.dot, np.outer}) def dot_like(a, b, out=None): from astropy.units import Quantity a, b = _as_quantities(a, b) unit = a.unit * b.unit if out is not None: if not isinstance(out, Quantity): raise NotImplementedError return tuple(x.view(np.ndarray) for x in (a, b, out)), {}, unit, out else: return (a.view(np.ndarray), b.view(np.ndarray)), {}, unit, None @function_helper(helps={np.cross, np.inner, np.vdot, np.tensordot, np.kron, np.correlate, np.convolve}) def cross_like(a, b, *args, **kwargs): a, b = _as_quantities(a, b) unit = a.unit * b.unit return (a.view(np.ndarray), b.view(np.ndarray)) + args, kwargs, unit, None @function_helper def einsum(subscripts, *operands, out=None, **kwargs): from astropy.units import Quantity if not isinstance(subscripts, str): raise ValueError('only "subscripts" string mode supported for einsum.') if out is not None: if not isinstance(out, Quantity): raise NotImplementedError else: kwargs['out'] = out.view(np.ndarray) qs = _as_quantities(*operands) unit = functools.reduce(operator.mul, (q.unit for q in qs), dimensionless_unscaled) arrays = tuple(q.view(np.ndarray) for q in qs) return (subscripts,) + arrays, kwargs, unit, out @function_helper def bincount(x, weights=None, minlength=0): from astropy.units import Quantity if isinstance(x, Quantity): raise NotImplementedError return (x, weights.value, minlength), {}, weights.unit, None @function_helper def digitize(x, bins, *args, **kwargs): arrays, unit = _quantities2arrays(x, bins, unit_from_first=True) return arrays + args, kwargs, None, None def _check_bins(bins, unit): from astropy.units import Quantity check = _as_quantity(bins) if check.ndim > 0: return check.to_value(unit) elif isinstance(bins, Quantity): # bins should be an integer (or at least definitely not a Quantity). raise NotImplementedError else: return bins @function_helper def histogram(a, bins=10, range=None, weights=None, density=None): if weights is not None: weights = _as_quantity(weights) unit = weights.unit weights = weights.value else: unit = None a = _as_quantity(a) if not isinstance(bins, str): bins = _check_bins(bins, a.unit) if density: unit = (unit or 1) / a.unit return ((a.value, bins, range), {'weights': weights, 'density': density}, (unit, a.unit), None) @function_helper(helps=np.histogram_bin_edges) def histogram_bin_edges(a, bins=10, range=None, weights=None): # weights is currently unused a = _as_quantity(a) if not isinstance(bins, str): bins = _check_bins(bins, a.unit) return (a.value, bins, range, weights), {}, a.unit, None @function_helper def histogram2d(x, y, bins=10, range=None, weights=None, density=None): from astropy.units import Quantity if weights is not None: weights = _as_quantity(weights) unit = weights.unit weights = weights.value else: unit = None x, y = _as_quantities(x, y) try: n = len(bins) except TypeError: # bins should be an integer (or at least definitely not a Quantity). if isinstance(bins, Quantity): raise NotImplementedError else: if n == 1: raise NotImplementedError elif n == 2 and not isinstance(bins, Quantity): bins = [_check_bins(b, unit) for (b, unit) in zip(bins, (x.unit, y.unit))] else: bins = _check_bins(bins, x.unit) y = y.to(x.unit) if density: unit = (unit or 1) / x.unit / y.unit return ((x.value, y.value, bins, range), {'weights': weights, 'density': density}, (unit, x.unit, y.unit), None) @function_helper def histogramdd(sample, bins=10, range=None, weights=None, density=None): if weights is not None: weights = _as_quantity(weights) unit = weights.unit weights = weights.value else: unit = None try: # Sample is an ND-array. _, D = sample.shape except (AttributeError, ValueError): # Sample is a sequence of 1D arrays. sample = _as_quantities(*sample) sample_units = [s.unit for s in sample] sample = [s.value for s in sample] D = len(sample) else: sample = _as_quantity(sample) sample_units = [sample.unit] * D try: M = len(bins) except TypeError: # bins should be an integer from astropy.units import Quantity if isinstance(bins, Quantity): raise NotImplementedError else: if M != D: raise ValueError( 'The dimension of bins must be equal to the dimension of the ' ' sample x.') bins = [_check_bins(b, unit) for (b, unit) in zip(bins, sample_units)] if density: unit = functools.reduce(operator.truediv, sample_units, (unit or 1)) return ((sample, bins, range), {'weights': weights, 'density': density}, (unit, sample_units), None) @function_helper def diff(a, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue): a = _as_quantity(a) if prepend is not np._NoValue: prepend = _as_quantity(prepend).to_value(a.unit) if append is not np._NoValue: append = _as_quantity(append).to_value(a.unit) return (a.value, n, axis, prepend, append), {}, a.unit, None @function_helper def gradient(f, *varargs, **kwargs): f = _as_quantity(f) axis = kwargs.get('axis', None) if axis is None: n_axis = f.ndim elif isinstance(axis, tuple): n_axis = len(axis) else: n_axis = 1 if varargs: varargs = _as_quantities(*varargs) if len(varargs) == 1 and n_axis > 1: varargs = varargs * n_axis if varargs: units = [f.unit / q.unit for q in varargs] varargs = tuple(q.value for q in varargs) else: units = [f.unit] * n_axis if len(units) == 1: units = units[0] return (f.value,) + varargs, kwargs, units, None @function_helper def logspace(start, stop, *args, **kwargs): from astropy.units import LogQuantity, dex if (not isinstance(start, LogQuantity) or not isinstance(stop, LogQuantity)): raise NotImplementedError # Get unit from end point as for linspace. stop = stop.to(dex(stop.unit.physical_unit)) start = start.to(stop.unit) unit = stop.unit.physical_unit return (start.value, stop.value) + args, kwargs, unit, None @function_helper def geomspace(start, stop, *args, **kwargs): # Get unit from end point as for linspace. (stop, start), unit = _quantities2arrays(stop, start) return (start, stop) + args, kwargs, unit, None @function_helper def interp(x, xp, fp, *args, **kwargs): from astropy.units import Quantity (x, xp), _ = _quantities2arrays(x, xp) if isinstance(fp, Quantity): unit = fp.unit fp = fp.value else: unit = None return (x, xp, fp) + args, kwargs, unit, None @function_helper def unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None): unit = ar.unit n_index = sum(bool(i) for i in (return_index, return_inverse, return_counts)) if n_index: unit = [unit] + n_index * [None] return (ar.value, return_index, return_inverse, return_counts, axis), {}, unit, None @function_helper def intersect1d(ar1, ar2, assume_unique=False, return_indices=False): (ar1, ar2), unit = _quantities2arrays(ar1, ar2) if return_indices: unit = [unit, None, None] return (ar1, ar2, assume_unique, return_indices), {}, unit, None @function_helper(helps=(np.setxor1d, np.union1d, np.setdiff1d)) def twosetop(ar1, ar2, *args, **kwargs): (ar1, ar2), unit = _quantities2arrays(ar1, ar2) return (ar1, ar2) + args, kwargs, unit, None @function_helper(helps=(np.isin, np.in1d)) def setcheckop(ar1, ar2, *args, **kwargs): # This tests whether ar1 is in ar2, so we should change the unit of # a1 to that of a2. (ar2, ar1), unit = _quantities2arrays(ar2, ar1) return (ar1, ar2) + args, kwargs, None, None @dispatched_function def apply_over_axes(func, a, axes): # Copied straight from numpy/lib/shape_base, just to omit its # val = asarray(a); if only it had been asanyarray, or just not there # since a is assumed to an an array in the next line... # Which is what we do here - we can only get here if it is a Quantity. val = a N = a.ndim if np.array(axes).ndim == 0: axes = (axes,) for axis in axes: if axis < 0: axis = N + axis args = (val, axis) res = func(*args) if res.ndim == val.ndim: val = res else: res = np.expand_dims(res, axis) if res.ndim == val.ndim: val = res else: raise ValueError("function is not returning " "an array of the correct shape") # Returning unit is None to signal nothing should happen to # the output. return val, None, None @dispatched_function def array_repr(arr, *args, **kwargs): # TODO: The addition of "unit='...'" doesn't worry about line # length. Could copy & adapt _array_repr_implementation from # numpy.core.arrayprint.py cls_name = arr.__class__.__name__ fake_name = '_' * len(cls_name) fake_cls = type(fake_name, (np.ndarray,), {}) no_unit = np.array_repr(arr.view(fake_cls), *args, **kwargs).replace(fake_name, cls_name) unit_part = f"unit='{arr.unit}'" pre, dtype, post = no_unit.rpartition('dtype') if dtype: return f"{pre}{unit_part}, {dtype}{post}", None, None else: return f"{no_unit[:-1]}, {unit_part})", None, None @dispatched_function def array_str(arr, *args, **kwargs): # TODO: The addition of the unit doesn't worry about line length. # Could copy & adapt _array_repr_implementation from # numpy.core.arrayprint.py no_unit = np.array_str(arr.value, *args, **kwargs) return no_unit + arr._unitstr, None, None @function_helper def array2string(a, *args, **kwargs): # array2string breaks on quantities as it tries to turn individual # items into float, which works only for dimensionless. Since the # defaults would not keep any unit anyway, this is rather pointless - # we're better off just passing on the array view. However, one can # also work around this by passing on a formatter (as is done in Angle). # So, we do nothing if the formatter argument is present and has the # relevant formatter for our dtype. formatter = args[6] if len(args) >= 7 else kwargs.get('formatter', None) if formatter is None: a = a.value else: # See whether it covers our dtype. from numpy.core.arrayprint import _get_format_function with np.printoptions(formatter=formatter) as options: try: ff = _get_format_function(a.value, **options) except Exception: # Shouldn't happen, but possibly we're just not being smart # enough, so let's pass things on as is. pass else: # If the selected format function is that of numpy, we know # things will fail if 'numpy' in ff.__module__: a = a.value return (a,) + args, kwargs, None, None @function_helper def diag(v, *args, **kwargs): # Function works for *getting* the diagonal, but not *setting*. # So, override always. return (v.value,) + args, kwargs, v.unit, None @function_helper(module=np.linalg) def svd(a, full_matrices=True, compute_uv=True, hermitian=False): unit = a.unit if compute_uv: unit = (None, unit, None) return ((a.view(np.ndarray), full_matrices, compute_uv, hermitian), {}, unit, None) def _interpret_tol(tol, unit): from astropy.units import Quantity return Quantity(tol, unit).value @function_helper(module=np.linalg) def matrix_rank(M, tol=None, *args, **kwargs): if tol is not None: tol = _interpret_tol(tol, M.unit) return (M.view(np.ndarray), tol) + args, kwargs, None, None @function_helper(helps={np.linalg.inv, np.linalg.tensorinv}) def inv(a, *args, **kwargs): return (a.view(np.ndarray),)+args, kwargs, 1/a.unit, None @function_helper(module=np.linalg) def pinv(a, rcond=1e-15, *args, **kwargs): rcond = _interpret_tol(rcond, a.unit) return (a.view(np.ndarray), rcond) + args, kwargs, 1/a.unit, None @function_helper(module=np.linalg) def det(a): return (a.view(np.ndarray),), {}, a.unit ** a.shape[-1], None @function_helper(helps={np.linalg.solve, np.linalg.tensorsolve}) def solve(a, b, *args, **kwargs): a, b = _as_quantities(a, b) return ((a.view(np.ndarray), b.view(np.ndarray)) + args, kwargs, b.unit / a.unit, None) @function_helper(module=np.linalg) def lstsq(a, b, rcond="warn"): a, b = _as_quantities(a, b) if rcond not in (None, "warn", -1): rcond = _interpret_tol(rcond, a.unit) return ((a.view(np.ndarray), b.view(np.ndarray), rcond), {}, (b.unit / a.unit, b.unit ** 2, None, a.unit), None) @function_helper(module=np.linalg) def norm(x, ord=None, *args, **kwargs): if ord == 0: from astropy.units import dimensionless_unscaled unit = dimensionless_unscaled else: unit = x.unit return (x.view(np.ndarray), ord)+args, kwargs, unit, None @function_helper(module=np.linalg) def matrix_power(a, n): return (a.value, n), {}, a.unit ** n, None @function_helper(module=np.linalg) def cholesky(a): return (a.value,), {}, a.unit ** 0.5, None @function_helper(module=np.linalg) def qr(a, mode='reduced'): if mode.startswith('e'): units = None elif mode == 'r': units = a.unit else: from astropy.units import dimensionless_unscaled units = (dimensionless_unscaled, a.unit) return (a.value, mode), {}, units, None @function_helper(helps={np.linalg.eig, np.linalg.eigh}) def eig(a, *args, **kwargs): from astropy.units import dimensionless_unscaled return (a.value,)+args, kwargs, (a.unit, dimensionless_unscaled), None @function_helper(module=np.lib.recfunctions) def structured_to_unstructured(arr, *args, **kwargs): """ Convert a structured quantity to an unstructured one. This only works if all the units are compatible. """ from astropy.units import StructuredUnit target_unit = arr.unit.values()[0] def replace_unit(x): if isinstance(x, StructuredUnit): return x._recursively_apply(replace_unit) else: return target_unit to_unit = arr.unit._recursively_apply(replace_unit) return (arr.to_value(to_unit), ) + args, kwargs, target_unit, None def _build_structured_unit(dtype, unit): """Build structured unit from dtype Parameters ---------- dtype : `numpy.dtype` unit : `astropy.units.Unit` Returns ------- `astropy.units.Unit` or tuple """ if dtype.fields is None: return unit return tuple(_build_structured_unit(v[0], unit) for v in dtype.fields.values()) @function_helper(module=np.lib.recfunctions) def unstructured_to_structured(arr, dtype, *args, **kwargs): from astropy.units import StructuredUnit target_unit = StructuredUnit(_build_structured_unit(dtype, arr.unit)) return (arr.to_value(arr.unit), dtype) + args, kwargs, target_unit, None
75c515dd75882ae204821d41e7c0ad640ce69f8f138a1a2a3b0eb788adca9380
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """Quantity helpers for the scipy.special ufuncs. Available ufuncs in this module are at https://docs.scipy.org/doc/scipy/reference/special.html """ import numpy as np from astropy.units.core import UnitsError, UnitTypeError, dimensionless_unscaled from . import UFUNC_HELPERS from .helpers import (get_converter, helper_dimensionless_to_dimensionless, helper_cbrt, helper_two_arg_dimensionless) # ufuncs that require dimensionless input and give dimensionless output. dimensionless_to_dimensionless_sps_ufuncs = ( 'erf', 'erfc', 'erfcx', 'erfi', 'erfinv', 'erfcinv', 'gamma', 'gammaln', 'loggamma', 'gammasgn', 'psi', 'rgamma', 'digamma', 'wofz', 'dawsn', 'entr', 'exprel', 'expm1', 'log1p', 'exp2', 'exp10', 'j0', 'j1', 'y0', 'y1', 'i0', 'i0e', 'i1', 'i1e', 'k0', 'k0e', 'k1', 'k1e', 'itj0y0', 'it2j0y0', 'iti0k0', 'it2i0k0', 'ndtr', 'ndtri') scipy_special_ufuncs = dimensionless_to_dimensionless_sps_ufuncs # ufuncs that require input in degrees and give dimensionless output. degree_to_dimensionless_sps_ufuncs = ('cosdg', 'sindg', 'tandg', 'cotdg') scipy_special_ufuncs += degree_to_dimensionless_sps_ufuncs # ufuncs that require 2 dimensionless inputs and give dimensionless output. # note: 'jv' and 'jn' are aliases in some scipy versions, which will # cause the same key to be written twice, but since both are handled by the # same helper there is no harm done. two_arg_dimensionless_sps_ufuncs = ( 'jv', 'jn', 'jve', 'yn', 'yv', 'yve', 'kn', 'kv', 'kve', 'iv', 'ive', 'hankel1', 'hankel1e', 'hankel2', 'hankel2e') scipy_special_ufuncs += two_arg_dimensionless_sps_ufuncs # ufuncs handled as special cases scipy_special_ufuncs += ('cbrt', 'radian') def helper_degree_to_dimensionless(f, unit): from astropy.units.si import degree try: return [get_converter(unit, degree)], dimensionless_unscaled except UnitsError: raise UnitTypeError("Can only apply '{}' function to " "quantities with angle units" .format(f.__name__)) def helper_degree_minute_second_to_radian(f, unit1, unit2, unit3): from astropy.units.si import degree, arcmin, arcsec, radian try: return [get_converter(unit1, degree), get_converter(unit2, arcmin), get_converter(unit3, arcsec)], radian except UnitsError: raise UnitTypeError("Can only apply '{}' function to " "quantities with angle units" .format(f.__name__)) def get_scipy_special_helpers(): import scipy.special as sps SCIPY_HELPERS = {} for name in dimensionless_to_dimensionless_sps_ufuncs: # In SCIPY_LT_1_5, erfinv and erfcinv are not ufuncs. ufunc = getattr(sps, name, None) if isinstance(ufunc, np.ufunc): SCIPY_HELPERS[ufunc] = helper_dimensionless_to_dimensionless for ufunc in degree_to_dimensionless_sps_ufuncs: SCIPY_HELPERS[getattr(sps, ufunc)] = helper_degree_to_dimensionless for ufunc in two_arg_dimensionless_sps_ufuncs: SCIPY_HELPERS[getattr(sps, ufunc)] = helper_two_arg_dimensionless # ufuncs handled as special cases SCIPY_HELPERS[sps.cbrt] = helper_cbrt SCIPY_HELPERS[sps.radian] = helper_degree_minute_second_to_radian return SCIPY_HELPERS UFUNC_HELPERS.register_module('scipy.special', scipy_special_ufuncs, get_scipy_special_helpers)
ba527ae919c55bde7077185170a67067a2d5d74040843844d45d62df41541a36
# coding: utf-8 # Licensed under a 3-clause BSD style license - see LICENSE.rst """Separate tests specifically for equivalencies.""" # THIRD-PARTY import pytest import numpy as np from numpy.testing import assert_allclose # LOCAL from astropy import units as u from astropy.units.equivalencies import Equivalency from astropy import constants from astropy.tests.helper import assert_quantity_allclose from astropy.utils.exceptions import AstropyDeprecationWarning def test_dimensionless_angles(): # test that the angles_dimensionless option allows one to change # by any order in radian in the unit (#1161) rad1 = u.dimensionless_angles() assert u.radian.to(1, equivalencies=rad1) == 1. assert u.deg.to(1, equivalencies=rad1) == u.deg.to(u.rad) assert u.steradian.to(1, equivalencies=rad1) == 1. assert u.dimensionless_unscaled.to(u.steradian, equivalencies=rad1) == 1. # now quantities assert (1.*u.radian).to_value(1, equivalencies=rad1) == 1. assert (1.*u.deg).to_value(1, equivalencies=rad1) == u.deg.to(u.rad) assert (1.*u.steradian).to_value(1, equivalencies=rad1) == 1. # more complicated example I = 1.e45 * u.g * u.cm**2 # noqa Omega = u.cycle / (1.*u.s) Erot = 0.5 * I * Omega**2 # check that equivalency makes this work Erot_in_erg1 = Erot.to(u.erg, equivalencies=rad1) # and check that value is correct assert_allclose(Erot_in_erg1.value, (Erot/u.radian**2).to_value(u.erg)) # test built-in equivalency in subclass class MyRad1(u.Quantity): _equivalencies = rad1 phase = MyRad1(1., u.cycle) assert phase.to_value(1) == u.cycle.to(u.radian) @pytest.mark.parametrize('log_unit', (u.mag, u.dex, u.dB)) def test_logarithmic(log_unit): # check conversion of mag, dB, and dex to dimensionless and vice versa with pytest.raises(u.UnitsError): log_unit.to(1, 0.) with pytest.raises(u.UnitsError): u.dimensionless_unscaled.to(log_unit) assert log_unit.to(1, 0., equivalencies=u.logarithmic()) == 1. assert u.dimensionless_unscaled.to(log_unit, equivalencies=u.logarithmic()) == 0. # also try with quantities q_dex = np.array([0., -1., 1., 2.]) * u.dex q_expected = 10.**q_dex.value * u.dimensionless_unscaled q_log_unit = q_dex.to(log_unit) assert np.all(q_log_unit.to(1, equivalencies=u.logarithmic()) == q_expected) assert np.all(q_expected.to(log_unit, equivalencies=u.logarithmic()) == q_log_unit) with u.set_enabled_equivalencies(u.logarithmic()): assert np.all(np.abs(q_log_unit - q_expected.to(log_unit)) < 1.e-10*log_unit) doppler_functions = [u.doppler_optical, u.doppler_radio, u.doppler_relativistic] @pytest.mark.parametrize(('function'), doppler_functions) def test_doppler_frequency_0(function): rest = 105.01 * u.GHz velo0 = rest.to(u.km/u.s, equivalencies=function(rest)) assert velo0.value == 0 @pytest.mark.parametrize(('function'), doppler_functions) def test_doppler_wavelength_0(function): rest = 105.01 * u.GHz q1 = 0.00285489437196 * u.m velo0 = q1.to(u.km/u.s, equivalencies=function(rest)) np.testing.assert_almost_equal(velo0.value, 0, decimal=6) @pytest.mark.parametrize(('function'), doppler_functions) def test_doppler_energy_0(function): rest = 105.01 * u.GHz q1 = 0.0004342864648539744 * u.eV velo0 = q1.to(u.km/u.s, equivalencies=function(rest)) np.testing.assert_almost_equal(velo0.value, 0, decimal=6) @pytest.mark.parametrize(('function'), doppler_functions) def test_doppler_frequency_circle(function): rest = 105.01 * u.GHz shifted = 105.03 * u.GHz velo = shifted.to(u.km/u.s, equivalencies=function(rest)) freq = velo.to(u.GHz, equivalencies=function(rest)) np.testing.assert_almost_equal(freq.value, shifted.value, decimal=7) @pytest.mark.parametrize(('function'), doppler_functions) def test_doppler_wavelength_circle(function): rest = 105.01 * u.nm shifted = 105.03 * u.nm velo = shifted.to(u.km / u.s, equivalencies=function(rest)) wav = velo.to(u.nm, equivalencies=function(rest)) np.testing.assert_almost_equal(wav.value, shifted.value, decimal=7) @pytest.mark.parametrize(('function'), doppler_functions) def test_doppler_energy_circle(function): rest = 1.0501 * u.eV shifted = 1.0503 * u.eV velo = shifted.to(u.km / u.s, equivalencies=function(rest)) en = velo.to(u.eV, equivalencies=function(rest)) np.testing.assert_almost_equal(en.value, shifted.value, decimal=7) values_ghz = (999.899940784289, 999.8999307714406, 999.8999357778647) @pytest.mark.parametrize(('function', 'value'), list(zip(doppler_functions, values_ghz))) def test_30kms(function, value): rest = 1000 * u.GHz velo = 30 * u.km/u.s shifted = velo.to(u.GHz, equivalencies=function(rest)) np.testing.assert_almost_equal(shifted.value, value, decimal=7) bad_values = (5, 5*u.Jy, None) @pytest.mark.parametrize(('function', 'value'), list(zip(doppler_functions, bad_values))) def test_bad_restfreqs(function, value): with pytest.raises(u.UnitsError): function(value) @pytest.mark.parametrize(('z', 'rv_ans'), [(0, 0 * (u.km / u.s)), (0.001, 299642.56184583 * (u.m / u.s)), (-1, -2.99792458e8 * (u.m / u.s))]) def test_doppler_redshift(z, rv_ans): z_in = z * u.dimensionless_unscaled rv_out = z_in.to(u.km / u.s, u.doppler_redshift()) z_out = rv_out.to(u.dimensionless_unscaled, u.doppler_redshift()) assert_quantity_allclose(rv_out, rv_ans) assert_quantity_allclose(z_out, z_in) # Check roundtrip def test_doppler_redshift_no_cosmology(): from astropy.cosmology.units import redshift with pytest.raises(u.UnitConversionError, match='not convertible'): (0 * (u.km / u.s)).to(redshift, u.doppler_redshift()) def test_massenergy(): # The relative tolerance of these tests is set by the uncertainties # in the charge of the electron, which is known to about # 3e-9 (relative tolerance). Therefore, we limit the # precision of the tests to 1e-7 to be safe. The masses are # (loosely) known to ~ 5e-8 rel tolerance, so we couldn't test to # 1e-7 if we used the values from astropy.constants; that is, # they might change by more than 1e-7 in some future update, so instead # they are hardwired here. # Electron, proton, neutron, muon, 1g mass_eV = u.Quantity([510.998928e3, 938.272046e6, 939.565378e6, 105.6583715e6, 5.60958884539e32], u.eV) mass_g = u.Quantity([9.10938291e-28, 1.672621777e-24, 1.674927351e-24, 1.88353147e-25, 1], u.g) # Test both ways assert np.allclose(mass_eV.to_value(u.g, equivalencies=u.mass_energy()), mass_g.value, rtol=1e-7) assert np.allclose(mass_g.to_value(u.eV, equivalencies=u.mass_energy()), mass_eV.value, rtol=1e-7) # Basic tests of 'derived' equivalencies # Surface density sdens_eV = u.Quantity(5.60958884539e32, u.eV / u.m**2) sdens_g = u.Quantity(1e-4, u.g / u.cm**2) assert np.allclose(sdens_eV.to_value(u.g / u.cm**2, equivalencies=u.mass_energy()), sdens_g.value, rtol=1e-7) assert np.allclose(sdens_g.to_value(u.eV / u.m**2, equivalencies=u.mass_energy()), sdens_eV.value, rtol=1e-7) # Density dens_eV = u.Quantity(5.60958884539e32, u.eV / u.m**3) dens_g = u.Quantity(1e-6, u.g / u.cm**3) assert np.allclose(dens_eV.to_value(u.g / u.cm**3, equivalencies=u.mass_energy()), dens_g.value, rtol=1e-7) assert np.allclose(dens_g.to_value(u.eV / u.m**3, equivalencies=u.mass_energy()), dens_eV.value, rtol=1e-7) # Power pow_eV = u.Quantity(5.60958884539e32, u.eV / u.s) pow_g = u.Quantity(1, u.g / u.s) assert np.allclose(pow_eV.to_value(u.g / u.s, equivalencies=u.mass_energy()), pow_g.value, rtol=1e-7) assert np.allclose(pow_g.to_value(u.eV / u.s, equivalencies=u.mass_energy()), pow_eV.value, rtol=1e-7) def test_is_equivalent(): assert u.m.is_equivalent(u.pc) assert u.cycle.is_equivalent(u.mas) assert not u.cycle.is_equivalent(u.dimensionless_unscaled) assert u.cycle.is_equivalent(u.dimensionless_unscaled, u.dimensionless_angles()) assert not (u.Hz.is_equivalent(u.J)) assert u.Hz.is_equivalent(u.J, u.spectral()) assert u.J.is_equivalent(u.Hz, u.spectral()) assert u.pc.is_equivalent(u.arcsecond, u.parallax()) assert u.arcminute.is_equivalent(u.au, u.parallax()) # Pass a tuple for multiple possibilities assert u.cm.is_equivalent((u.m, u.s, u.kg)) assert u.ms.is_equivalent((u.m, u.s, u.kg)) assert u.g.is_equivalent((u.m, u.s, u.kg)) assert not u.L.is_equivalent((u.m, u.s, u.kg)) assert not (u.km / u.s).is_equivalent((u.m, u.s, u.kg)) def test_parallax(): a = u.arcsecond.to(u.pc, 10, u.parallax()) assert_allclose(a, 0.10, rtol=1.e-12) b = u.pc.to(u.arcsecond, a, u.parallax()) assert_allclose(b, 10, rtol=1.e-12) a = u.arcminute.to(u.au, 1, u.parallax()) assert_allclose(a, 3437.746770785, rtol=1.e-12) b = u.au.to(u.arcminute, a, u.parallax()) assert_allclose(b, 1, rtol=1.e-12) val = (-1 * u.mas).to(u.pc, u.parallax()) assert np.isnan(val.value) val = (-1 * u.mas).to_value(u.pc, u.parallax()) assert np.isnan(val) def test_parallax2(): a = u.arcsecond.to(u.pc, [0.1, 2.5], u.parallax()) assert_allclose(a, [10, 0.4], rtol=1.e-12) def test_spectral(): a = u.AA.to(u.Hz, 1, u.spectral()) assert_allclose(a, 2.9979245799999995e+18) b = u.Hz.to(u.AA, a, u.spectral()) assert_allclose(b, 1) a = u.AA.to(u.MHz, 1, u.spectral()) assert_allclose(a, 2.9979245799999995e+12) b = u.MHz.to(u.AA, a, u.spectral()) assert_allclose(b, 1) a = u.m.to(u.Hz, 1, u.spectral()) assert_allclose(a, 2.9979245799999995e+8) b = u.Hz.to(u.m, a, u.spectral()) assert_allclose(b, 1) def test_spectral2(): a = u.nm.to(u.J, 500, u.spectral()) assert_allclose(a, 3.972891366538605e-19) b = u.J.to(u.nm, a, u.spectral()) assert_allclose(b, 500) a = u.AA.to(u.Hz, 1, u.spectral()) b = u.Hz.to(u.J, a, u.spectral()) c = u.AA.to(u.J, 1, u.spectral()) assert_allclose(b, c) c = u.J.to(u.Hz, b, u.spectral()) assert_allclose(a, c) def test_spectral3(): a = u.nm.to(u.Hz, [1000, 2000], u.spectral()) assert_allclose(a, [2.99792458e+14, 1.49896229e+14]) @pytest.mark.parametrize( ('in_val', 'in_unit'), [([0.1, 5000.0, 10000.0], u.AA), ([1e+5, 2.0, 1.0], u.micron ** -1), ([2.99792458e+19, 5.99584916e+14, 2.99792458e+14], u.Hz), ([1.98644568e-14, 3.97289137e-19, 1.98644568e-19], u.J)]) def test_spectral4(in_val, in_unit): """Wave number conversion w.r.t. wavelength, freq, and energy.""" # Spectroscopic and angular out_units = [u.micron ** -1, u.radian / u.micron] answers = [[1e+5, 2.0, 1.0], [6.28318531e+05, 12.5663706, 6.28318531]] for out_unit, ans in zip(out_units, answers): # Forward a = in_unit.to(out_unit, in_val, u.spectral()) assert_allclose(a, ans) # Backward b = out_unit.to(in_unit, ans, u.spectral()) assert_allclose(b, in_val) @pytest.mark.parametrize('wav', (3500 * u.AA, 8.5654988e+14 * u.Hz, 1 / (3500 * u.AA), 5.67555959e-19 * u.J)) def test_spectraldensity2(wav): # flux density flambda = u.erg / u.angstrom / u.cm ** 2 / u.s fnu = u.erg / u.Hz / u.cm ** 2 / u.s a = flambda.to(fnu, 1, u.spectral_density(wav)) assert_allclose(a, 4.086160166177361e-12) # integrated flux f_int = u.erg / u.cm ** 2 / u.s phot_int = u.ph / u.cm ** 2 / u.s a = f_int.to(phot_int, 1, u.spectral_density(wav)) assert_allclose(a, 1.7619408e+11) a = phot_int.to(f_int, 1, u.spectral_density(wav)) assert_allclose(a, 5.67555959e-12) # luminosity density llambda = u.erg / u.angstrom / u.s lnu = u.erg / u.Hz / u.s a = llambda.to(lnu, 1, u.spectral_density(wav)) assert_allclose(a, 4.086160166177361e-12) a = lnu.to(llambda, 1, u.spectral_density(wav)) assert_allclose(a, 2.44728537142857e11) def test_spectraldensity3(): # Define F_nu in Jy f_nu = u.Jy # Define F_lambda in ergs / cm^2 / s / micron f_lambda = u.erg / u.cm ** 2 / u.s / u.micron # 1 GHz one_ghz = u.Quantity(1, u.GHz) # Convert to ergs / cm^2 / s / Hz assert_allclose(f_nu.to(u.erg / u.cm ** 2 / u.s / u.Hz, 1.), 1.e-23, 10) # Convert to ergs / cm^2 / s at 10 Ghz assert_allclose(f_nu.to(u.erg / u.cm ** 2 / u.s, 1., equivalencies=u.spectral_density(one_ghz * 10)), 1.e-13, 10) # Convert to F_lambda at 1 Ghz assert_allclose(f_nu.to(f_lambda, 1., equivalencies=u.spectral_density(one_ghz)), 3.335640951981521e-20, 10) # Convert to Jy at 1 Ghz assert_allclose(f_lambda.to(u.Jy, 1., equivalencies=u.spectral_density(one_ghz)), 1. / 3.335640951981521e-20, 10) # Convert to ergs / cm^2 / s at 10 microns assert_allclose(f_lambda.to(u.erg / u.cm ** 2 / u.s, 1., equivalencies=u.spectral_density(u.Quantity(10, u.micron))), 10., 10) def test_spectraldensity4(): """PHOTLAM and PHOTNU conversions.""" flam = u.erg / (u.cm ** 2 * u.s * u.AA) fnu = u.erg / (u.cm ** 2 * u.s * u.Hz) photlam = u.photon / (u.cm ** 2 * u.s * u.AA) photnu = u.photon / (u.cm ** 2 * u.s * u.Hz) wave = u.Quantity([4956.8, 4959.55, 4962.3], u.AA) flux_photlam = [9.7654e-3, 1.003896e-2, 9.78473e-3] flux_photnu = [8.00335589e-14, 8.23668949e-14, 8.03700310e-14] flux_flam = [3.9135e-14, 4.0209e-14, 3.9169e-14] flux_fnu = [3.20735792e-25, 3.29903646e-25, 3.21727226e-25] flux_jy = [3.20735792e-2, 3.29903646e-2, 3.21727226e-2] flux_stmag = [12.41858665, 12.38919182, 12.41764379] flux_abmag = [12.63463143, 12.60403221, 12.63128047] # PHOTLAM <--> FLAM assert_allclose(photlam.to( flam, flux_photlam, u.spectral_density(wave)), flux_flam, rtol=1e-6) assert_allclose(flam.to( photlam, flux_flam, u.spectral_density(wave)), flux_photlam, rtol=1e-6) # PHOTLAM <--> FNU assert_allclose(photlam.to( fnu, flux_photlam, u.spectral_density(wave)), flux_fnu, rtol=1e-6) assert_allclose(fnu.to( photlam, flux_fnu, u.spectral_density(wave)), flux_photlam, rtol=1e-6) # PHOTLAM <--> Jy assert_allclose(photlam.to( u.Jy, flux_photlam, u.spectral_density(wave)), flux_jy, rtol=1e-6) assert_allclose(u.Jy.to( photlam, flux_jy, u.spectral_density(wave)), flux_photlam, rtol=1e-6) # PHOTLAM <--> PHOTNU assert_allclose(photlam.to( photnu, flux_photlam, u.spectral_density(wave)), flux_photnu, rtol=1e-6) assert_allclose(photnu.to( photlam, flux_photnu, u.spectral_density(wave)), flux_photlam, rtol=1e-6) # PHOTNU <--> FNU assert_allclose(photnu.to( fnu, flux_photnu, u.spectral_density(wave)), flux_fnu, rtol=1e-6) assert_allclose(fnu.to( photnu, flux_fnu, u.spectral_density(wave)), flux_photnu, rtol=1e-6) # PHOTNU <--> FLAM assert_allclose(photnu.to( flam, flux_photnu, u.spectral_density(wave)), flux_flam, rtol=1e-6) assert_allclose(flam.to( photnu, flux_flam, u.spectral_density(wave)), flux_photnu, rtol=1e-6) # PHOTLAM <--> STMAG assert_allclose(photlam.to( u.STmag, flux_photlam, u.spectral_density(wave)), flux_stmag, rtol=1e-6) assert_allclose(u.STmag.to( photlam, flux_stmag, u.spectral_density(wave)), flux_photlam, rtol=1e-6) # PHOTLAM <--> ABMAG assert_allclose(photlam.to( u.ABmag, flux_photlam, u.spectral_density(wave)), flux_abmag, rtol=1e-6) assert_allclose(u.ABmag.to( photlam, flux_abmag, u.spectral_density(wave)), flux_photlam, rtol=1e-6) def test_spectraldensity5(): """ Test photon luminosity density conversions. """ L_la = u.erg / (u.s * u.AA) L_nu = u.erg / (u.s * u.Hz) phot_L_la = u.photon / (u.s * u.AA) phot_L_nu = u.photon / (u.s * u.Hz) wave = u.Quantity([4956.8, 4959.55, 4962.3], u.AA) flux_phot_L_la = [9.7654e-3, 1.003896e-2, 9.78473e-3] flux_phot_L_nu = [8.00335589e-14, 8.23668949e-14, 8.03700310e-14] flux_L_la = [3.9135e-14, 4.0209e-14, 3.9169e-14] flux_L_nu = [3.20735792e-25, 3.29903646e-25, 3.21727226e-25] # PHOTLAM <--> FLAM assert_allclose(phot_L_la.to( L_la, flux_phot_L_la, u.spectral_density(wave)), flux_L_la, rtol=1e-6) assert_allclose(L_la.to( phot_L_la, flux_L_la, u.spectral_density(wave)), flux_phot_L_la, rtol=1e-6) # PHOTLAM <--> FNU assert_allclose(phot_L_la.to( L_nu, flux_phot_L_la, u.spectral_density(wave)), flux_L_nu, rtol=1e-6) assert_allclose(L_nu.to( phot_L_la, flux_L_nu, u.spectral_density(wave)), flux_phot_L_la, rtol=1e-6) # PHOTLAM <--> PHOTNU assert_allclose(phot_L_la.to( phot_L_nu, flux_phot_L_la, u.spectral_density(wave)), flux_phot_L_nu, rtol=1e-6) assert_allclose(phot_L_nu.to( phot_L_la, flux_phot_L_nu, u.spectral_density(wave)), flux_phot_L_la, rtol=1e-6) # PHOTNU <--> FNU assert_allclose(phot_L_nu.to( L_nu, flux_phot_L_nu, u.spectral_density(wave)), flux_L_nu, rtol=1e-6) assert_allclose(L_nu.to( phot_L_nu, flux_L_nu, u.spectral_density(wave)), flux_phot_L_nu, rtol=1e-6) # PHOTNU <--> FLAM assert_allclose(phot_L_nu.to( L_la, flux_phot_L_nu, u.spectral_density(wave)), flux_L_la, rtol=1e-6) assert_allclose(L_la.to( phot_L_nu, flux_L_la, u.spectral_density(wave)), flux_phot_L_nu, rtol=1e-6) def test_spectraldensity6(): """ Test surface brightness conversions. """ slam = u.erg / (u.cm ** 2 * u.s * u.AA * u.sr) snu = u.erg / (u.cm ** 2 * u.s * u.Hz * u.sr) wave = u.Quantity([4956.8, 4959.55, 4962.3], u.AA) sb_flam = [3.9135e-14, 4.0209e-14, 3.9169e-14] sb_fnu = [3.20735792e-25, 3.29903646e-25, 3.21727226e-25] # S(nu) <--> S(lambda) assert_allclose(snu.to( slam, sb_fnu, u.spectral_density(wave)), sb_flam, rtol=1e-6) assert_allclose(slam.to( snu, sb_flam, u.spectral_density(wave)), sb_fnu, rtol=1e-6) @pytest.mark.parametrize( ('from_unit', 'to_unit'), [(u.ph / u.cm ** 2 / u.s, (u.cm * u.cm * u.s) ** -1), (u.ph / u.cm ** 2 / u.s, u.erg / (u.cm * u.cm * u.s * u.keV)), (u.erg / u.cm ** 2 / u.s, (u.cm * u.cm * u.s) ** -1), (u.erg / u.cm ** 2 / u.s, u.erg / (u.cm * u.cm * u.s * u.keV))]) def test_spectraldensity_not_allowed(from_unit, to_unit): """Not allowed to succeed as per https://github.com/astropy/astropy/pull/10015 """ with pytest.raises(u.UnitConversionError, match='not convertible'): from_unit.to(to_unit, 1, u.spectral_density(1 * u.AA)) # The other way with pytest.raises(u.UnitConversionError, match='not convertible'): to_unit.to(from_unit, 1, u.spectral_density(1 * u.AA)) def test_equivalent_units(): from astropy.units import imperial with u.add_enabled_units(imperial): units = u.g.find_equivalent_units() units_set = set(units) match = set( [u.M_e, u.M_p, u.g, u.kg, u.solMass, u.t, u.u, u.M_earth, u.M_jup, imperial.oz, imperial.lb, imperial.st, imperial.ton, imperial.slug]) assert units_set == match r = repr(units) assert r.count('\n') == len(units) + 2 def test_equivalent_units2(): units = set(u.Hz.find_equivalent_units(u.spectral())) match = set( [u.AU, u.Angstrom, u.Hz, u.J, u.Ry, u.cm, u.eV, u.erg, u.lyr, u.lsec, u.m, u.micron, u.pc, u.solRad, u.Bq, u.Ci, u.k, u.earthRad, u.jupiterRad]) assert units == match from astropy.units import imperial with u.add_enabled_units(imperial): units = set(u.Hz.find_equivalent_units(u.spectral())) match = set( [u.AU, u.Angstrom, imperial.BTU, u.Hz, u.J, u.Ry, imperial.cal, u.cm, u.eV, u.erg, imperial.ft, imperial.fur, imperial.inch, imperial.kcal, u.lyr, u.m, imperial.mi, u.lsec, imperial.mil, u.micron, u.pc, u.solRad, imperial.yd, u.Bq, u.Ci, imperial.nmi, u.k, u.earthRad, u.jupiterRad]) assert units == match units = set(u.Hz.find_equivalent_units(u.spectral())) match = set( [u.AU, u.Angstrom, u.Hz, u.J, u.Ry, u.cm, u.eV, u.erg, u.lyr, u.lsec, u.m, u.micron, u.pc, u.solRad, u.Bq, u.Ci, u.k, u.earthRad, u.jupiterRad]) assert units == match def test_trivial_equivalency(): assert u.m.to(u.kg, equivalencies=[(u.m, u.kg)]) == 1.0 def test_invalid_equivalency(): with pytest.raises(ValueError): u.m.to(u.kg, equivalencies=[(u.m,)]) with pytest.raises(ValueError): u.m.to(u.kg, equivalencies=[(u.m, 5.0)]) def test_irrelevant_equivalency(): with pytest.raises(u.UnitsError): u.m.to(u.kg, equivalencies=[(u.m, u.l)]) def test_brightness_temperature(): omega_B = np.pi * (50 * u.arcsec) ** 2 nu = u.GHz * 5 tb = 7.052587837212582 * u.K np.testing.assert_almost_equal( tb.value, (1 * u.Jy).to_value( u.K, equivalencies=u.brightness_temperature(nu, beam_area=omega_B))) np.testing.assert_almost_equal( 1.0, tb.to_value( u.Jy, equivalencies=u.brightness_temperature(nu, beam_area=omega_B))) def test_swapped_args_brightness_temperature(): """ #5173 changes the order of arguments but accepts the old (deprecated) args """ omega_B = np.pi * (50 * u.arcsec) ** 2 nu = u.GHz * 5 tb = 7.052587837212582 * u.K with pytest.warns(AstropyDeprecationWarning) as w: result = (1*u.Jy).to( u.K, equivalencies=u.brightness_temperature(omega_B, nu)) roundtrip = result.to( u.Jy, equivalencies=u.brightness_temperature(omega_B, nu)) assert len(w) == 2 np.testing.assert_almost_equal(tb.value, result.value) np.testing.assert_almost_equal(roundtrip.value, 1) def test_surfacebrightness(): sb = 50*u.MJy/u.sr k = sb.to(u.K, u.brightness_temperature(50*u.GHz)) np.testing.assert_almost_equal(k.value, 0.650965, 5) assert k.unit.is_equivalent(u.K) def test_beam(): # pick a beam area: 2 pi r^2 = area of a Gaussina with sigma=50 arcsec omega_B = 2 * np.pi * (50 * u.arcsec) ** 2 new_beam = (5*u.beam).to(u.sr, u.equivalencies.beam_angular_area(omega_B)) np.testing.assert_almost_equal(omega_B.to(u.sr).value * 5, new_beam.value) assert new_beam.unit.is_equivalent(u.sr) # make sure that it's still consistent with 5 beams nbeams = new_beam.to(u.beam, u.equivalencies.beam_angular_area(omega_B)) np.testing.assert_almost_equal(nbeams.value, 5) # test inverse beam equivalency # (this is just a sanity check that the equivalency is defined; # it's not for testing numerical consistency) (5/u.beam).to(1/u.sr, u.equivalencies.beam_angular_area(omega_B)) # test practical case # (this is by far the most important one) flux_density = (5*u.Jy/u.beam).to(u.MJy/u.sr, u.equivalencies.beam_angular_area(omega_B)) np.testing.assert_almost_equal(flux_density.value, 13.5425483146382) def test_thermodynamic_temperature(): nu = 143 * u.GHz tb = 0.0026320501262630277 * u.K eq = u.thermodynamic_temperature(nu, T_cmb=2.7255 * u.K) np.testing.assert_almost_equal( tb.value, (1 * (u.MJy / u.sr)).to_value(u.K, equivalencies=eq)) np.testing.assert_almost_equal( 1.0, tb.to_value(u.MJy / u.sr, equivalencies=eq)) def test_equivalency_context(): with u.set_enabled_equivalencies(u.dimensionless_angles()): phase = u.Quantity(1., u.cycle) assert_allclose(np.exp(1j*phase), 1.) Omega = u.cycle / (1.*u.minute) assert_allclose(np.exp(1j*Omega*60.*u.second), 1.) # ensure we can turn off equivalencies even within the scope with pytest.raises(u.UnitsError): phase.to(1, equivalencies=None) # test the manager also works in the Quantity constructor. q1 = u.Quantity(phase, u.dimensionless_unscaled) assert_allclose(q1.value, u.cycle.to(u.radian)) # and also if we use a class that happens to have a unit attribute. class MyQuantityLookalike(np.ndarray): pass mylookalike = np.array(1.).view(MyQuantityLookalike) mylookalike.unit = 'cycle' # test the manager also works in the Quantity constructor. q2 = u.Quantity(mylookalike, u.dimensionless_unscaled) assert_allclose(q2.value, u.cycle.to(u.radian)) with u.set_enabled_equivalencies(u.spectral()): u.GHz.to(u.cm) eq_on = u.GHz.find_equivalent_units() with pytest.raises(u.UnitsError): u.GHz.to(u.cm, equivalencies=None) # without equivalencies, we should find a smaller (sub)set eq_off = u.GHz.find_equivalent_units() assert all(eq in set(eq_on) for eq in eq_off) assert set(eq_off) < set(eq_on) # Check the equivalency manager also works in ufunc evaluations, # not just using (wrong) scaling. [#2496] l2v = u.doppler_optical(6000 * u.angstrom) l1 = 6010 * u.angstrom assert l1.to(u.km/u.s, equivalencies=l2v) > 100. * u.km / u.s with u.set_enabled_equivalencies(l2v): assert l1 > 100. * u.km / u.s assert abs((l1 - 500. * u.km / u.s).to(u.angstrom)) < 1. * u.km/u.s def test_equivalency_context_manager(): base_registry = u.get_current_unit_registry() def just_to_from_units(equivalencies): return [(equiv[0], equiv[1]) for equiv in equivalencies] tf_dimensionless_angles = just_to_from_units(u.dimensionless_angles()) tf_spectral = just_to_from_units(u.spectral()) # <=1 b/c might have the dimensionless_redshift equivalency enabled. assert len(base_registry.equivalencies) <= 1 with u.set_enabled_equivalencies(u.dimensionless_angles()): new_registry = u.get_current_unit_registry() assert (set(just_to_from_units(new_registry.equivalencies)) == set(tf_dimensionless_angles)) assert set(new_registry.all_units) == set(base_registry.all_units) with u.set_enabled_equivalencies(u.spectral()): newer_registry = u.get_current_unit_registry() assert (set(just_to_from_units(newer_registry.equivalencies)) == set(tf_spectral)) assert (set(newer_registry.all_units) == set(base_registry.all_units)) assert (set(just_to_from_units(new_registry.equivalencies)) == set(tf_dimensionless_angles)) assert set(new_registry.all_units) == set(base_registry.all_units) with u.add_enabled_equivalencies(u.spectral()): newer_registry = u.get_current_unit_registry() assert (set(just_to_from_units(newer_registry.equivalencies)) == set(tf_dimensionless_angles) | set(tf_spectral)) assert (set(newer_registry.all_units) == set(base_registry.all_units)) assert base_registry is u.get_current_unit_registry() def test_temperature(): from astropy.units.imperial import deg_F, deg_R t_k = 0 * u.K assert_allclose(t_k.to_value(u.deg_C, u.temperature()), -273.15) assert_allclose(t_k.to_value(deg_F, u.temperature()), -459.67) t_k = 20 * u.K assert_allclose(t_k.to_value(deg_R, u.temperature()), 36.0) t_k = 20 * deg_R assert_allclose(t_k.to_value(u.K, u.temperature()), 11.11, atol=0.01) t_k = 20 * deg_F assert_allclose(t_k.to_value(deg_R, u.temperature()), 479.67) t_k = 20 * deg_R assert_allclose(t_k.to_value(deg_F, u.temperature()), -439.67) t_k = 20 * u.deg_C assert_allclose(t_k.to_value(deg_R, u.temperature()), 527.67) t_k = 20 * deg_R assert_allclose(t_k.to_value(u.deg_C, u.temperature()), -262.039, atol=0.01) def test_temperature_energy(): x = 1000 * u.K y = (x * constants.k_B).to(u.keV) assert_allclose(x.to_value(u.keV, u.temperature_energy()), y.value) assert_allclose(y.to_value(u.K, u.temperature_energy()), x.value) def test_molar_mass_amu(): x = 1 * (u.g/u.mol) y = 1 * u.u assert_allclose(x.to_value(u.u, u.molar_mass_amu()), y.value) assert_allclose(y.to_value(u.g/u.mol, u.molar_mass_amu()), x.value) with pytest.raises(u.UnitsError): x.to(u.u) def test_compose_equivalencies(): x = u.Unit("arcsec").compose(units=(u.pc,), equivalencies=u.parallax()) assert x[0] == u.pc x = u.Unit("2 arcsec").compose(units=(u.pc,), equivalencies=u.parallax()) assert x[0] == u.Unit(0.5 * u.pc) x = u.degree.compose(equivalencies=u.dimensionless_angles()) assert u.Unit(u.degree.to(u.radian)) in x x = (u.nm).compose(units=(u.m, u.s), equivalencies=u.doppler_optical(0.55*u.micron)) for y in x: if y.bases == [u.m, u.s]: assert y.powers == [1, -1] assert_allclose( y.scale, u.nm.to(u.m / u.s, equivalencies=u.doppler_optical(0.55 * u.micron))) break else: assert False, "Didn't find speed in compose results" def test_pixel_scale(): pix = 75*u.pix asec = 30*u.arcsec pixscale = 0.4*u.arcsec/u.pix pixscale2 = 2.5*u.pix/u.arcsec assert_quantity_allclose(pix.to(u.arcsec, u.pixel_scale(pixscale)), asec) assert_quantity_allclose(pix.to(u.arcmin, u.pixel_scale(pixscale)), asec) assert_quantity_allclose(pix.to(u.arcsec, u.pixel_scale(pixscale2)), asec) assert_quantity_allclose(pix.to(u.arcmin, u.pixel_scale(pixscale2)), asec) assert_quantity_allclose(asec.to(u.pix, u.pixel_scale(pixscale)), pix) assert_quantity_allclose(asec.to(u.pix, u.pixel_scale(pixscale2)), pix) def test_pixel_scale_invalid_scale_unit(): pixscale = 0.4 * u.arcsec pixscale2 = 0.4 * u.arcsec / u.pix ** 2 with pytest.raises(u.UnitsError, match="pixel dimension"): u.pixel_scale(pixscale) with pytest.raises(u.UnitsError, match="pixel dimension"): u.pixel_scale(pixscale2) def test_pixel_scale_acceptable_scale_unit(): pix = 75 * u.pix v = 3000 * (u.cm / u.s) pixscale = 0.4 * (u.m / u.s / u.pix) pixscale2 = 2.5 * (u.pix / (u.m / u.s)) assert_quantity_allclose(pix.to(u.m / u.s, u.pixel_scale(pixscale)), v) assert_quantity_allclose(pix.to(u.km / u.s, u.pixel_scale(pixscale)), v) assert_quantity_allclose(pix.to(u.m / u.s, u.pixel_scale(pixscale2)), v) assert_quantity_allclose(pix.to(u.km / u.s, u.pixel_scale(pixscale2)), v) assert_quantity_allclose(v.to(u.pix, u.pixel_scale(pixscale)), pix) assert_quantity_allclose(v.to(u.pix, u.pixel_scale(pixscale2)), pix) def test_plate_scale(): mm = 1.5*u.mm asec = 30*u.arcsec platescale = 20*u.arcsec/u.mm platescale2 = 0.05*u.mm/u.arcsec assert_quantity_allclose(mm.to(u.arcsec, u.plate_scale(platescale)), asec) assert_quantity_allclose(mm.to(u.arcmin, u.plate_scale(platescale)), asec) assert_quantity_allclose(mm.to(u.arcsec, u.plate_scale(platescale2)), asec) assert_quantity_allclose(mm.to(u.arcmin, u.plate_scale(platescale2)), asec) assert_quantity_allclose(asec.to(u.mm, u.plate_scale(platescale)), mm) assert_quantity_allclose(asec.to(u.mm, u.plate_scale(platescale2)), mm) def test_equivelency(): ps = u.pixel_scale(10*u.arcsec/u.pix) assert isinstance(ps, Equivalency) assert isinstance(ps.name, list) assert len(ps.name) == 1 assert ps.name[0] == "pixel_scale" assert isinstance(ps.kwargs, list) assert len(ps.kwargs) == 1 assert ps.kwargs[0] == dict({'pixscale': 10*u.arcsec/u.pix}) def test_add_equivelencies(): e1 = u.pixel_scale(10*u.arcsec/u.pixel) + u.temperature_energy() assert isinstance(e1, Equivalency) assert e1.name == ["pixel_scale", "temperature_energy"] assert isinstance(e1.kwargs, list) assert e1.kwargs == [dict({'pixscale': 10*u.arcsec/u.pix}), dict()] e2 = u.pixel_scale(10*u.arcsec/u.pixel) + [1, 2, 3] assert isinstance(e2, list) def test_pprint(): pprint_class = u.UnitBase.EquivalentUnitsList equiv_units_to_Hz = u.Hz.find_equivalent_units() assert pprint_class.__repr__(equiv_units_to_Hz).splitlines() == [ ' Primary name | Unit definition | Aliases ', '[', ' Bq | 1 / s | becquerel ,', ' Ci | 3.7e+10 / s | curie ,', ' Hz | 1 / s | Hertz, hertz ,', ']' ] assert pprint_class._repr_html_(equiv_units_to_Hz) == ( '<table style="width:50%">' '<tr><th>Primary name</th><th>Unit definition</th>' '<th>Aliases</th></tr>' '<tr><td>Bq</td><td>1 / s</td><td>becquerel</td></tr>' '<tr><td>Ci</td><td>3.7e+10 / s</td><td>curie</td></tr>' '<tr><td>Hz</td><td>1 / s</td><td>Hertz, hertz</td></tr></table>' )
ad5a817c858328178f97958b4a5127bc1f006ba6d98b1cc76db3b4d3b0dcc3c5
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """Test setting and adding unit aliases.""" import pytest import astropy.units as u trials = [ ({"Angstroms": u.AA}, "Angstroms", u.AA), ({"counts": u.count}, "counts/s", u.count / u.s), ({"ergs": u.erg, "Angstroms": u.AA}, "ergs/(s cm**2 Angstroms)", u.erg / (u.s * u.cm**2 * u.AA))] class TestAliases: def teardown_method(self): u.set_enabled_aliases({}) def teardown_class(self): assert u.get_current_unit_registry().aliases == {} @pytest.mark.parametrize('format_', [None, 'fits', 'ogip', 'vounit', 'cds']) @pytest.mark.parametrize('aliases,bad,unit', trials) def test_set_enabled_aliases_context_manager(self, aliases, bad, unit, format_): if format_ == 'cds': bad = bad.replace(' ', '.').replace('**', '') with u.set_enabled_aliases(aliases): assert u.get_current_unit_registry().aliases == aliases assert u.Unit(bad) == unit assert u.get_current_unit_registry().aliases == {} with pytest.raises(ValueError): u.Unit(bad) @pytest.mark.parametrize('aliases,bad,unit', trials) def test_add_enabled_aliases_context_manager(self, aliases, bad, unit): with u.add_enabled_aliases(aliases): assert u.get_current_unit_registry().aliases == aliases assert u.Unit(bad) == unit assert u.get_current_unit_registry().aliases == {} with pytest.raises(ValueError): u.Unit(bad) def test_set_enabled_aliases(self): for i, (aliases, bad, unit) in enumerate(trials): u.set_enabled_aliases(aliases) assert u.get_current_unit_registry().aliases == aliases assert u.Unit(bad) == unit for _, bad2, unit2 in trials: if bad2 == bad or bad2 in aliases: assert u.Unit(bad2) == unit2 else: with pytest.raises(ValueError): u.Unit(bad2) def test_add_enabled_aliases(self): expected_aliases = {} for i, (aliases, bad, unit) in enumerate(trials): u.add_enabled_aliases(aliases) expected_aliases.update(aliases) assert u.get_current_unit_registry().aliases == expected_aliases assert u.Unit(bad) == unit for j, (_, bad2, unit2) in enumerate(trials): if j <= i: assert u.Unit(bad2) == unit2 else: with pytest.raises(ValueError): u.Unit(bad2) def test_cannot_alias_existing_unit(self): with pytest.raises(ValueError, match='already means'): u.set_enabled_aliases({'pct': u.Unit(1e-12*u.count)}) def test_cannot_alias_existing_alias_to_another_unit(self): u.set_enabled_aliases({'counts': u.count}) with pytest.raises(ValueError, match='already is an alias'): u.add_enabled_aliases({'counts': u.adu})
306dff63a30d8f6cf82a6f28d3f87c72c7b560e1d43c96cf21ce08fa6b7e67c7
# coding: utf-8 # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Test utilities for `astropy.units`. """ import numpy as np from numpy import finfo from astropy.units.utils import sanitize_scale from astropy.units.utils import quantity_asanyarray from astropy.units.quantity import Quantity _float_finfo = finfo(float) def test_quantity_asanyarray(): array_of_quantities = [Quantity(1), Quantity(2), Quantity(3)] quantity_array = quantity_asanyarray(array_of_quantities) assert isinstance(quantity_array, Quantity) array_of_integers = [1, 2, 3] np_array = quantity_asanyarray(array_of_integers) assert isinstance(np_array, np.ndarray) def test_sanitize_scale(): assert sanitize_scale(complex(2, _float_finfo.eps)) == 2 assert sanitize_scale(complex(_float_finfo.eps, 2)) == 2j
5962e3b3e0d0c9bd7de33a8730f50b568374546e55b5a05f3732c3236165c758
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """Regression tests for deprecated units or those that are "soft" deprecated because they are required for VOUnit support but are not in common use.""" import pytest from astropy.units import deprecated, required_by_vounit from astropy import units as u def test_emu(): with pytest.raises(AttributeError): u.emu assert u.Bi.to(deprecated.emu, 1) == 1 with deprecated.enable(): assert u.Bi.compose()[0] == deprecated.emu assert u.Bi.compose()[0] == u.Bi # test that the earth/jupiter mass/rad are also in the deprecated bunch for body in ('earth', 'jupiter'): for phystype in ('Mass', 'Rad'): # only test a couple prefixes to same time for prefix in ('n', 'y'): namewoprefix = body + phystype unitname = prefix + namewoprefix with pytest.raises(AttributeError): getattr(u, unitname) assert (getattr(deprecated, unitname).represents.bases[0] == getattr(u, namewoprefix)) def test_required_by_vounit(): # The tests below could be replicated with all the various prefixes, but it # seems unnecessary because they all come as a set. So we only use nano for # the purposes of this test. with pytest.raises(AttributeError): # nano-solar mass/rad/lum shouldn't be in the base unit namespace u.nsolMass u.nsolRad u.nsolLum # but they should be enabled by default via required_by_vounit, to allow # the Unit constructor to accept them assert u.Unit('nsolMass') == required_by_vounit.nsolMass assert u.Unit('nsolRad') == required_by_vounit.nsolRad assert u.Unit('nsolLum') == required_by_vounit.nsolLum # but because they are prefixes, they shouldn't be in find_equivalent_units assert required_by_vounit.nsolMass not in u.solMass.find_equivalent_units() assert required_by_vounit.nsolRad not in u.solRad.find_equivalent_units() assert required_by_vounit.nsolLum not in u.solLum.find_equivalent_units()
387570f98abd09cdb70ad3b97be1c75e7cc3c7ec2f5115b8cb183c2195916ad8
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst # STDLIB import sys import typing as T # THIRD PARTY import pytest # LOCAL from astropy import units as u from astropy.units import Quantity from astropy.units._typing import HAS_ANNOTATED, Annotated def test_ignore_generic_type_annotations(): """Test annotations that are not unit related are ignored. This test passes if the function works. """ # one unit, one not (should be ignored) @u.quantity_input def func(x: u.m, y: str): return x, y i_q, i_str = 2 * u.m, "cool string" o_q, o_str = func(i_q, i_str) # if this doesn't fail, it worked. assert i_q == o_q assert i_str == o_str @pytest.mark.skipif(not HAS_ANNOTATED, reason="need `Annotated`") class TestQuantityUnitAnnotations: """Test Quantity[Unit] type annotation.""" def test_simple_annotation(self): @u.quantity_input def func(x: Quantity[u.m], y: str): return x, y i_q, i_str = 2 * u.m, "cool string" o_q, o_str = func(i_q, i_str) assert i_q == o_q assert i_str == o_str # checks the input on the 1st arg with pytest.raises(u.UnitsError): func(1 * u.s, i_str) # but not the second o_q, o_str = func(i_q, {"not": "a string"}) assert i_q == o_q assert i_str != o_str def test_multiple_annotation(self): @u.quantity_input def multi_func(a: Quantity[u.km]) -> Quantity[u.m]: return a i_q = 2 * u.km o_q = multi_func(i_q) assert o_q == i_q assert o_q.unit == u.m @pytest.mark.skipif(not HAS_ANNOTATED, reason="need `Annotated`") def test_optional_and_annotated(self): @u.quantity_input def opt_func(x: T.Optional[Quantity[u.m]] = None) -> Quantity[u.km]: if x is None: return 1 * u.km return x i_q = 250 * u.m o_q = opt_func(i_q) assert o_q.unit == u.km assert o_q == i_q i_q = None o_q = opt_func(i_q) assert o_q == 1 * u.km @pytest.mark.skipif(not HAS_ANNOTATED, reason="need `Annotated`") def test_union_and_annotated(self): # Union and Annotated @u.quantity_input def union_func(x: T.Union[Quantity[u.m], Quantity[u.s], None]): if x is None: return None else: return 2 * x i_q = 1 * u.m o_q = union_func(i_q) assert o_q == 2 * i_q i_q = 1 * u.s o_q = union_func(i_q) assert o_q == 2 * i_q i_q = None o_q = union_func(i_q) assert o_q is None def test_not_unit_or_ptype(self): with pytest.raises(TypeError, match="unit annotation is not"): Quantity["definitely not a unit"] @pytest.mark.skipif(HAS_ANNOTATED, reason="requires py3.8 behavior") def test_not_unit_or_ptype(): """ Same as above test, but different behavior for python 3.8 b/c it passes Quantity right through. """ with pytest.warns(Warning): annot = Quantity[u.km] assert annot == u.km @pytest.mark.parametrize("solarx_unit,solary_unit", [ (u.arcsec, u.arcsec), ('angle', 'angle')]) def test_args3(solarx_unit, solary_unit): @u.quantity_input def myfunc_args(solarx: solarx_unit, solary: solary_unit): return solarx, solary solarx, solary = myfunc_args(1*u.arcsec, 1*u.arcsec) assert isinstance(solarx, Quantity) assert isinstance(solary, Quantity) assert solarx.unit == u.arcsec assert solary.unit == u.arcsec @pytest.mark.parametrize("solarx_unit,solary_unit", [ (u.arcsec, u.arcsec), ('angle', 'angle')]) def test_args_noconvert3(solarx_unit, solary_unit): @u.quantity_input() def myfunc_args(solarx: solarx_unit, solary: solary_unit): return solarx, solary solarx, solary = myfunc_args(1*u.deg, 1*u.arcmin) assert isinstance(solarx, Quantity) assert isinstance(solary, Quantity) assert solarx.unit == u.deg assert solary.unit == u.arcmin @pytest.mark.parametrize("solarx_unit", [ u.arcsec, 'angle']) def test_args_nonquantity3(solarx_unit): @u.quantity_input def myfunc_args(solarx: solarx_unit, solary): return solarx, solary solarx, solary = myfunc_args(1*u.arcsec, 100) assert isinstance(solarx, Quantity) assert isinstance(solary, int) assert solarx.unit == u.arcsec @pytest.mark.parametrize("solarx_unit,solary_unit", [ (u.arcsec, u.eV), ('angle', 'energy')]) def test_arg_equivalencies3(solarx_unit, solary_unit): @u.quantity_input(equivalencies=u.mass_energy()) def myfunc_args(solarx: solarx_unit, solary: solary_unit): return solarx, solary+(10*u.J) # Add an energy to check equiv is working solarx, solary = myfunc_args(1*u.arcsec, 100*u.gram) assert isinstance(solarx, Quantity) assert isinstance(solary, Quantity) assert solarx.unit == u.arcsec assert solary.unit == u.gram @pytest.mark.parametrize("solarx_unit,solary_unit", [ (u.arcsec, u.deg), ('angle', 'angle')]) def test_wrong_unit3(solarx_unit, solary_unit): @u.quantity_input def myfunc_args(solarx: solarx_unit, solary: solary_unit): return solarx, solary with pytest.raises(u.UnitsError) as e: solarx, solary = myfunc_args(1*u.arcsec, 100*u.km) str_to = str(solary_unit) assert str(e.value) == f"Argument 'solary' to function 'myfunc_args' must be in units convertible to '{str_to}'." @pytest.mark.parametrize("solarx_unit,solary_unit", [ (u.arcsec, u.deg), ('angle', 'angle')]) def test_not_quantity3(solarx_unit, solary_unit): @u.quantity_input def myfunc_args(solarx: solarx_unit, solary: solary_unit): return solarx, solary with pytest.raises(TypeError) as e: solarx, solary = myfunc_args(1*u.arcsec, 100) assert str(e.value) == "Argument 'solary' to function 'myfunc_args' has no 'unit' attribute. You should pass in an astropy Quantity instead." def test_decorator_override(): @u.quantity_input(solarx=u.arcsec) def myfunc_args(solarx: u.km, solary: u.arcsec): return solarx, solary solarx, solary = myfunc_args(1*u.arcsec, 1*u.arcsec) assert isinstance(solarx, Quantity) assert isinstance(solary, Quantity) assert solarx.unit == u.arcsec assert solary.unit == u.arcsec @pytest.mark.parametrize("solarx_unit,solary_unit", [ (u.arcsec, u.deg), ('angle', 'angle')]) def test_kwargs3(solarx_unit, solary_unit): @u.quantity_input def myfunc_args(solarx: solarx_unit, solary, myk: solary_unit=1*u.arcsec): return solarx, solary, myk solarx, solary, myk = myfunc_args(1*u.arcsec, 100, myk=100*u.deg) assert isinstance(solarx, Quantity) assert isinstance(solary, int) assert isinstance(myk, Quantity) assert myk.unit == u.deg @pytest.mark.parametrize("solarx_unit,solary_unit", [ (u.arcsec, u.deg), ('angle', 'angle')]) def test_unused_kwargs3(solarx_unit, solary_unit): @u.quantity_input def myfunc_args(solarx: solarx_unit, solary, myk: solary_unit=1*u.arcsec, myk2=1000): return solarx, solary, myk, myk2 solarx, solary, myk, myk2 = myfunc_args(1*u.arcsec, 100, myk=100*u.deg, myk2=10) assert isinstance(solarx, Quantity) assert isinstance(solary, int) assert isinstance(myk, Quantity) assert isinstance(myk2, int) assert myk.unit == u.deg assert myk2 == 10 @pytest.mark.parametrize("solarx_unit,energy", [ (u.arcsec, u.eV), ('angle', 'energy')]) def test_kwarg_equivalencies3(solarx_unit, energy): @u.quantity_input(equivalencies=u.mass_energy()) def myfunc_args(solarx: solarx_unit, energy: energy=10*u.eV): return solarx, energy+(10*u.J) # Add an energy to check equiv is working solarx, energy = myfunc_args(1*u.arcsec, 100*u.gram) assert isinstance(solarx, Quantity) assert isinstance(energy, Quantity) assert solarx.unit == u.arcsec assert energy.unit == u.gram @pytest.mark.parametrize("solarx_unit,solary_unit", [ (u.arcsec, u.deg), ('angle', 'angle')]) def test_kwarg_wrong_unit3(solarx_unit, solary_unit): @u.quantity_input def myfunc_args(solarx: solarx_unit, solary: solary_unit=10*u.deg): return solarx, solary with pytest.raises(u.UnitsError) as e: solarx, solary = myfunc_args(1*u.arcsec, solary=100*u.km) str_to = str(solary_unit) assert str(e.value) == f"Argument 'solary' to function 'myfunc_args' must be in units convertible to '{str_to}'." @pytest.mark.parametrize("solarx_unit,solary_unit", [ (u.arcsec, u.deg), ('angle', 'angle')]) def test_kwarg_not_quantity3(solarx_unit, solary_unit): @u.quantity_input def myfunc_args(solarx: solarx_unit, solary: solary_unit=10*u.deg): return solarx, solary with pytest.raises(TypeError) as e: solarx, solary = myfunc_args(1*u.arcsec, solary=100) assert str(e.value) == "Argument 'solary' to function 'myfunc_args' has no 'unit' attribute. You should pass in an astropy Quantity instead." @pytest.mark.parametrize("solarx_unit,solary_unit", [ (u.arcsec, u.deg), ('angle', 'angle')]) def test_kwarg_default3(solarx_unit, solary_unit): @u.quantity_input def myfunc_args(solarx: solarx_unit, solary: solary_unit=10*u.deg): return solarx, solary solarx, solary = myfunc_args(1*u.arcsec) def test_return_annotation(): @u.quantity_input def myfunc_args(solarx: u.arcsec) -> u.deg: return solarx solarx = myfunc_args(1*u.arcsec) assert solarx.unit is u.deg def test_return_annotation_none(): @u.quantity_input def myfunc_args(solarx: u.arcsec) -> None: pass solarx = myfunc_args(1*u.arcsec) assert solarx is None def test_return_annotation_notUnit(): @u.quantity_input def myfunc_args(solarx: u.arcsec) -> int: return 0 solarx = myfunc_args(1*u.arcsec) assert solarx == 0 def test_enum_annotation(): # Regression test for gh-9932 from enum import Enum, auto class BasicEnum(Enum): AnOption = auto() @u.quantity_input def myfunc_args(a: BasicEnum, b: u.arcsec) -> None: pass myfunc_args(BasicEnum.AnOption, 1*u.arcsec)
491e76724d23fbe787cc9bfbd98fecf41b14520ad58f9f37c6bec7fa79159053
# coding: utf-8 # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Tests for the photometric module. Note that this is shorter than might be expected because a lot of the relevant tests that deal with magnidues are in `test_logarithmic.py` """ from astropy.tests.helper import assert_quantity_allclose from astropy.units import Magnitude, mgy, nmgy, ABflux, STflux, zero_point_flux, Jy from astropy.units import erg, cm, s, AA def test_maggies(): assert_quantity_allclose(1e-9*mgy, 1*nmgy) assert_quantity_allclose(Magnitude((1*nmgy).to(mgy)).value, 22.5) def test_maggies_zpts(): assert_quantity_allclose((1*nmgy).to(ABflux, zero_point_flux(1*ABflux)), 3631e-9*Jy, rtol=1e-3) ST_base_unit = erg * cm**-2 / s / AA stmgy = (10*mgy).to(STflux, zero_point_flux(1*ST_base_unit)) assert_quantity_allclose(stmgy, 10*ST_base_unit) mgyst = (2*ST_base_unit).to(mgy, zero_point_flux(0.5*ST_base_unit)) assert_quantity_allclose(mgyst, 4*mgy) nmgyst = (5.e-10*ST_base_unit).to(mgy, zero_point_flux(0.5*ST_base_unit)) assert_quantity_allclose(nmgyst, 1*nmgy)
4dc1fae0dc4c1df85d60cefa8b076b6f1fe3e84bcd3cd4853a05599cf0239a47
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Regression tests for the units.format package """ import warnings from contextlib import nullcontext from fractions import Fraction import pytest import numpy as np from numpy.testing import assert_allclose from astropy import units as u from astropy.constants import si from astropy.units import core, dex, UnitsWarning from astropy.units import format as u_format from astropy.units.utils import is_effectively_unity @pytest.mark.parametrize('strings, unit', [ (["m s", "m*s", "m.s"], u.m * u.s), (["m/s", "m*s**-1", "m /s", "m / s", "m/ s"], u.m / u.s), (["m**2", "m2", "m**(2)", "m**+2", "m+2", "m^(+2)"], u.m ** 2), (["m**-3", "m-3", "m^(-3)", "/m3"], u.m ** -3), (["m**(1.5)", "m(3/2)", "m**(3/2)", "m^(3/2)"], u.m ** 1.5), (["2.54 cm"], u.Unit(u.cm * 2.54)), (["10+8m"], u.Unit(u.m * 1e8)), # This is the VOUnits documentation, but doesn't seem to follow the # unity grammar (["3.45 10**(-4)Jy"], 3.45 * 1e-4 * u.Jy) (["sqrt(m)"], u.m ** 0.5), (["dB(mW)", "dB (mW)"], u.DecibelUnit(u.mW)), (["mag"], u.mag), (["mag(ct/s)"], u.MagUnit(u.ct / u.s)), (["dex"], u.dex), (["dex(cm s**-2)", "dex(cm/s2)"], u.DexUnit(u.cm / u.s**2)), ]) def test_unit_grammar(strings, unit): for s in strings: print(s) unit2 = u_format.Generic.parse(s) assert unit2 == unit @pytest.mark.parametrize('string', ['sin( /pixel /s)', 'mag(mag)', 'dB(dB(mW))', 'dex()']) def test_unit_grammar_fail(string): with pytest.raises(ValueError): print(string) u_format.Generic.parse(string) @pytest.mark.parametrize('strings, unit', [ (["0.1nm"], u.AA), (["mW/m2"], u.Unit(u.erg / u.cm ** 2 / u.s)), (["mW/(m2)"], u.Unit(u.erg / u.cm ** 2 / u.s)), (["km/s", "km.s-1"], u.km / u.s), (["10pix/nm"], u.Unit(10 * u.pix / u.nm)), (["1.5x10+11m"], u.Unit(1.5e11 * u.m)), (["1.5×10+11m"], u.Unit(1.5e11 * u.m)), (["m2"], u.m ** 2), (["10+21m"], u.Unit(u.m * 1e21)), (["2.54cm"], u.Unit(u.cm * 2.54)), (["20%"], 0.20 * u.dimensionless_unscaled), (["10+9"], 1.e9 * u.dimensionless_unscaled), (["2x10-9"], 2.e-9 * u.dimensionless_unscaled), (["---"], u.dimensionless_unscaled), (["ma"], u.ma), (["mAU"], u.mAU), (["uarcmin"], u.uarcmin), (["uarcsec"], u.uarcsec), (["kbarn"], u.kbarn), (["Gbit"], u.Gbit), (["Gibit"], 2 ** 30 * u.bit), (["kbyte"], u.kbyte), (["mRy"], 0.001 * u.Ry), (["mmag"], u.mmag), (["Mpc"], u.Mpc), (["Gyr"], u.Gyr), (["°"], u.degree), (["°/s"], u.degree / u.s), (["Å"], u.AA), (["Å/s"], u.AA / u.s), (["\\h"], si.h), (["[cm/s2]"], dex(u.cm / u.s ** 2)), (["[K]"], dex(u.K)), (["[-]"], dex(u.dimensionless_unscaled))]) def test_cds_grammar(strings, unit): for s in strings: print(s) unit2 = u_format.CDS.parse(s) assert unit2 == unit @pytest.mark.parametrize('string', [ '0.1 nm', 'solMass(3/2)', 'km / s', 'km s-1', 'pix0.1nm', 'pix/(0.1nm)', 'km*s', 'km**2', '5x8+3m', '0.1---', '---m', 'm---', '--', '0.1-', '-m', 'm-', 'mag(s-1)', 'dB(mW)', 'dex(cm s-2)', '[--]']) def test_cds_grammar_fail(string): with pytest.raises(ValueError): print(string) u_format.CDS.parse(string) def test_cds_dimensionless(): assert u.Unit('---', format='cds') == u.dimensionless_unscaled assert u.dimensionless_unscaled.to_string(format='cds') == "---" def test_cds_log10_dimensionless(): assert u.Unit('[-]', format='cds') == u.dex(u.dimensionless_unscaled) assert u.dex(u.dimensionless_unscaled).to_string(format='cds') == "[-]" # These examples are taken from the EXAMPLES section of # https://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/general/ogip_93_001/ @pytest.mark.parametrize('strings, unit', [ (["count /s", "count/s", "count s**(-1)", "count / s", "count /s "], u.count / u.s), (["/pixel /s", "/(pixel * s)"], (u.pixel * u.s) ** -1), (["count /m**2 /s /eV", "count m**(-2) * s**(-1) * eV**(-1)", "count /(m**2 * s * eV)"], u.count * u.m ** -2 * u.s ** -1 * u.eV ** -1), (["erg /pixel /s /GHz", "erg /s /GHz /pixel", "erg /pixel /(s * GHz)"], u.erg / (u.s * u.GHz * u.pixel)), (["keV**2 /yr /angstrom", "10**(10) keV**2 /yr /m"], # Though this is given as an example, it seems to violate the rules # of not raising scales to powers, so I'm just excluding it # "(10**2 MeV)**2 /yr /m" u.keV**2 / (u.yr * u.angstrom)), (["10**(46) erg /s", "10**46 erg /s", "10**(39) J /s", "10**(39) W", "10**(15) YW", "YJ /fs"], 10**46 * u.erg / u.s), (["10**(-7) J /cm**2 /MeV", "10**(-9) J m**(-2) eV**(-1)", "nJ m**(-2) eV**(-1)", "nJ /m**2 /eV"], 10 ** -7 * u.J * u.cm ** -2 * u.MeV ** -1), (["sqrt(erg /pixel /s /GHz)", "(erg /pixel /s /GHz)**(0.5)", "(erg /pixel /s /GHz)**(1/2)", "erg**(0.5) pixel**(-0.5) s**(-0.5) GHz**(-0.5)"], (u.erg * u.pixel ** -1 * u.s ** -1 * u.GHz ** -1) ** 0.5), (["(count /s) (/pixel /s)", "(count /s) * (/pixel /s)", "count /pixel /s**2"], (u.count / u.s) * (1.0 / (u.pixel * u.s)))]) def test_ogip_grammar(strings, unit): for s in strings: print(s) unit2 = u_format.OGIP.parse(s) assert unit2 == unit @pytest.mark.parametrize('string', [ 'log(photon /m**2 /s /Hz)', 'sin( /pixel /s)', 'log(photon /cm**2 /s /Hz) /(sin( /pixel /s))', 'log(photon /cm**2 /s /Hz) (sin( /pixel /s))**(-1)', 'dB(mW)', 'dex(cm/s**2)']) def test_ogip_grammar_fail(string): with pytest.raises(ValueError): print(string) u_format.OGIP.parse(string) class RoundtripBase: deprecated_units = set() def check_roundtrip(self, unit, output_format=None): if output_format is None: output_format = self.format_ with warnings.catch_warnings(): warnings.simplefilter('ignore') # Same warning shows up multiple times s = unit.to_string(output_format) if s in self.deprecated_units: with pytest.warns(UnitsWarning, match='deprecated') as w: a = core.Unit(s, format=self.format_) assert len(w) == 1 else: a = core.Unit(s, format=self.format_) # No warning assert_allclose(a.decompose().scale, unit.decompose().scale, rtol=1e-9) def check_roundtrip_decompose(self, unit): ud = unit.decompose() s = ud.to_string(self.format_) assert ' ' not in s a = core.Unit(s, format=self.format_) assert_allclose(a.decompose().scale, ud.scale, rtol=1e-5) class TestRoundtripGeneric(RoundtripBase): format_ = 'generic' @pytest.mark.parametrize('unit', [ unit for unit in u.__dict__.values() if (isinstance(unit, core.UnitBase) and not isinstance(unit, core.PrefixUnit))]) def test_roundtrip(self, unit): self.check_roundtrip(unit) self.check_roundtrip(unit, output_format='unicode') self.check_roundtrip_decompose(unit) class TestRoundtripVOUnit(RoundtripBase): format_ = 'vounit' deprecated_units = u_format.VOUnit._deprecated_units @pytest.mark.parametrize('unit', [ unit for unit in u_format.VOUnit._units.values() if (isinstance(unit, core.UnitBase) and not isinstance(unit, core.PrefixUnit))]) def test_roundtrip(self, unit): self.check_roundtrip(unit) if unit not in (u.mag, u.dB): self.check_roundtrip_decompose(unit) class TestRoundtripFITS(RoundtripBase): format_ = 'fits' deprecated_units = u_format.Fits._deprecated_units @pytest.mark.parametrize('unit', [ unit for unit in u_format.Fits._units.values() if (isinstance(unit, core.UnitBase) and not isinstance(unit, core.PrefixUnit))]) def test_roundtrip(self, unit): self.check_roundtrip(unit) class TestRoundtripCDS(RoundtripBase): format_ = 'cds' @pytest.mark.parametrize('unit', [ unit for unit in u_format.CDS._units.values() if (isinstance(unit, core.UnitBase) and not isinstance(unit, core.PrefixUnit))]) def test_roundtrip(self, unit): self.check_roundtrip(unit) if unit == u.mag: # Skip mag: decomposes into dex, which is unknown to CDS. return self.check_roundtrip_decompose(unit) @pytest.mark.parametrize('unit', [u.dex(unit) for unit in (u.cm/u.s**2, u.K, u.Lsun)]) def test_roundtrip_dex(self, unit): string = unit.to_string(format='cds') recovered = u.Unit(string, format='cds') assert recovered == unit class TestRoundtripOGIP(RoundtripBase): format_ = 'ogip' deprecated_units = u_format.OGIP._deprecated_units | {'d'} @pytest.mark.parametrize('unit', [ unit for unit in u_format.OGIP._units.values() if (isinstance(unit, core.UnitBase) and not isinstance(unit, core.PrefixUnit))]) def test_roundtrip(self, unit): if str(unit) in ('d', '0.001 Crab'): # Special-case day, which gets auto-converted to hours, and mCrab, # which the default check does not recognize as a deprecated unit. with pytest.warns(UnitsWarning): s = unit.to_string(self.format_) a = core.Unit(s, format=self.format_) assert_allclose(a.decompose().scale, unit.decompose().scale, rtol=1e-9) else: self.check_roundtrip(unit) if str(unit) in ('mag', 'byte', 'Crab'): # Skip mag and byte, which decompose into dex and bit, resp., # both of which are unknown to OGIP, as well as Crab, which does # not decompose, and thus gives a deprecated unit warning. return power_of_ten = np.log10(unit.decompose().scale) if abs(power_of_ten - round(power_of_ten)) > 1e-3: ctx = pytest.warns(UnitsWarning, match='power of 10') elif str(unit) == '0.001 Crab': ctx = pytest.warns(UnitsWarning, match='deprecated') else: ctx = nullcontext() with ctx: self.check_roundtrip_decompose(unit) def test_fits_units_available(): u_format.Fits._units def test_vo_units_available(): u_format.VOUnit._units def test_cds_units_available(): u_format.CDS._units def test_cds_non_ascii_unit(): """Regression test for #5350. This failed with a decoding error as μas could not be represented in ascii.""" from astropy.units import cds with cds.enable(): u.radian.find_equivalent_units(include_prefix_units=True) def test_latex(): fluxunit = u.erg / (u.cm ** 2 * u.s) assert fluxunit.to_string('latex') == r'$\mathrm{\frac{erg}{s\,cm^{2}}}$' def test_new_style_latex(): fluxunit = u.erg / (u.cm ** 2 * u.s) assert f"{fluxunit:latex}" == r'$\mathrm{\frac{erg}{s\,cm^{2}}}$' def test_latex_scale(): fluxunit = u.Unit(1.e-24 * u.erg / (u.cm ** 2 * u.s * u.Hz)) latex = r'$\mathrm{1 \times 10^{-24}\,\frac{erg}{Hz\,s\,cm^{2}}}$' assert fluxunit.to_string('latex') == latex def test_latex_inline_scale(): fluxunit = u.Unit(1.e-24 * u.erg / (u.cm ** 2 * u.s * u.Hz)) latex_inline = (r'$\mathrm{1 \times 10^{-24}\,erg' r'\,Hz^{-1}\,s^{-1}\,cm^{-2}}$') assert fluxunit.to_string('latex_inline') == latex_inline @pytest.mark.parametrize('format_spec, string', [ ('generic', 'erg / (cm2 s)'), ('s', 'erg / (cm2 s)'), ('console', ' erg \n ------\n s cm^2'), ('latex', '$\\mathrm{\\frac{erg}{s\\,cm^{2}}}$'), ('latex_inline', '$\\mathrm{erg\\,s^{-1}\\,cm^{-2}}$'), ('>20s', ' erg / (cm2 s)')]) def test_format_styles(format_spec, string): fluxunit = u.erg / (u.cm ** 2 * u.s) assert format(fluxunit, format_spec) == string def test_flatten_to_known(): myunit = u.def_unit("FOOBAR_One", u.erg / u.Hz) assert myunit.to_string('fits') == 'erg Hz-1' myunit2 = myunit * u.bit ** 3 assert myunit2.to_string('fits') == 'bit3 erg Hz-1' def test_flatten_impossible(): myunit = u.def_unit("FOOBAR_Two") with u.add_enabled_units(myunit), pytest.raises(ValueError): myunit.to_string('fits') def test_console_out(): """ Issue #436. """ u.Jy.decompose().to_string('console') def test_flexible_float(): assert u.min._represents.to_string('latex') == r'$\mathrm{60\,s}$' def test_fits_to_string_function_error(): """Test function raises TypeError on bad input. This instead of returning None, see gh-11825. """ with pytest.raises(TypeError, match='unit argument must be'): u_format.Fits.to_string(None) def test_fraction_repr(): area = u.cm ** 2.0 assert '.' not in area.to_string('latex') fractional = u.cm ** 2.5 assert '5/2' in fractional.to_string('latex') assert fractional.to_string('unicode') == 'cm⁵⸍²' def test_scale_effectively_unity(): """Scale just off unity at machine precision level is OK. Ensures #748 does not recur """ a = (3. * u.N).cgs assert is_effectively_unity(a.unit.scale) assert len(a.__repr__().split()) == 3 def test_percent(): """Test that the % unit is properly recognized. Since % is a special symbol, this goes slightly beyond the round-tripping tested above.""" assert u.Unit('%') == u.percent == u.Unit(0.01) assert u.Unit('%', format='cds') == u.Unit(0.01) assert u.Unit(0.01).to_string('cds') == '%' with pytest.raises(ValueError): u.Unit('%', format='fits') with pytest.raises(ValueError): u.Unit('%', format='vounit') def test_scaled_dimensionless(): """Test that scaled dimensionless units are properly recognized in generic and CDS, but not in fits and vounit.""" assert u.Unit('0.1') == u.Unit(0.1) == 0.1 * u.dimensionless_unscaled assert u.Unit('1.e-4') == u.Unit(1.e-4) assert u.Unit('10-4', format='cds') == u.Unit(1.e-4) assert u.Unit('10+8').to_string('cds') == '10+8' with pytest.raises(ValueError): u.Unit(0.15).to_string('fits') assert u.Unit(0.1).to_string('fits') == '10**-1' with pytest.raises(ValueError): u.Unit(0.1).to_string('vounit') def test_deprecated_did_you_mean_units(): with pytest.raises(ValueError) as exc_info: u.Unit('ANGSTROM', format='fits') assert 'Did you mean Angstrom or angstrom?' in str(exc_info.value) with pytest.raises(ValueError) as exc_info: u.Unit('crab', format='ogip') assert 'Crab (deprecated)' in str(exc_info.value) assert 'mCrab (deprecated)' in str(exc_info.value) with pytest.warns(UnitsWarning, match=r'.* Did you mean 0\.1nm, Angstrom ' r'\(deprecated\) or angstrom \(deprecated\)\?') as w: u.Unit('ANGSTROM', format='vounit') assert len(w) == 1 assert str(w[0].message).count('0.1nm') == 1 with pytest.warns(UnitsWarning, match=r'.* 0\.1nm\.') as w: u.Unit('angstrom', format='vounit') assert len(w) == 1 @pytest.mark.parametrize('string', ['mag(ct/s)', 'dB(mW)', 'dex(cm s**-2)']) def test_fits_function(string): # Function units cannot be written, so ensure they're not parsed either. with pytest.raises(ValueError): print(string) u_format.Fits().parse(string) @pytest.mark.parametrize('string', ['mag(ct/s)', 'dB(mW)', 'dex(cm s**-2)']) def test_vounit_function(string): # Function units cannot be written, so ensure they're not parsed either. with pytest.raises(ValueError), warnings.catch_warnings(): warnings.simplefilter('ignore') # ct, dex also raise warnings - irrelevant here. u_format.VOUnit().parse(string) def test_vounit_binary_prefix(): u.Unit('KiB', format='vounit') == u.Unit('1024 B') u.Unit('Kibyte', format='vounit') == u.Unit('1024 B') u.Unit('Kibit', format='vounit') == u.Unit('1024 B') with pytest.warns(UnitsWarning) as w: u.Unit('kibibyte', format='vounit') assert len(w) == 1 def test_vounit_unknown(): assert u.Unit('unknown', format='vounit') is None assert u.Unit('UNKNOWN', format='vounit') is None assert u.Unit('', format='vounit') is u.dimensionless_unscaled def test_vounit_details(): with pytest.warns(UnitsWarning, match='deprecated') as w: assert u.Unit('Pa', format='vounit') is u.Pascal assert len(w) == 1 # The da- prefix is not allowed, and the d- prefix is discouraged assert u.dam.to_string('vounit') == '10m' assert u.Unit('dam dag').to_string('vounit') == '100g.m' # Parse round-trip with pytest.warns(UnitsWarning, match='deprecated'): flam = u.erg / u.cm / u.cm / u.s / u.AA x = u.format.VOUnit.to_string(flam) assert x == 'Angstrom**-1.cm**-2.erg.s**-1' new_flam = u.format.VOUnit.parse(x) assert new_flam == flam @pytest.mark.parametrize('unit, vounit, number, scale, voscale', [('nm', 'nm', 0.1, '10^-1', '0.1'), ('fm', 'fm', 100.0, '10+2', '100'), ('m^2', 'm**2', 100.0, '100.0', '100'), ('cm', 'cm', 2.54, '2.54', '2.54'), ('kg', 'kg', 1.898124597e27, '1.898124597E27', '1.8981246e+27'), ('m/s', 'm.s**-1', 299792458.0, '299792458', '2.9979246e+08'), ('cm2', 'cm**2', 1.e-20, '10^(-20)', '1e-20')]) def test_vounit_scale_factor(unit, vounit, number, scale, voscale): x = u.Unit(f'{scale} {unit}') assert x == number * u.Unit(unit) assert x.to_string(format='vounit') == voscale + vounit def test_vounit_custom(): x = u.Unit("'foo' m", format='vounit') x_vounit = x.to_string('vounit') assert x_vounit == "'foo'.m" x_string = x.to_string() assert x_string == "foo m" x = u.Unit("m'foo' m", format='vounit') assert x.bases[1]._represents.scale == 0.001 x_vounit = x.to_string('vounit') assert x_vounit == "m.m'foo'" x_string = x.to_string() assert x_string == 'm mfoo' def test_vounit_implicit_custom(): # Yikes, this becomes "femto-urlong"... But at least there's a warning. with pytest.warns(UnitsWarning) as w: x = u.Unit("furlong/week", format="vounit") assert x.bases[0]._represents.scale == 1e-15 assert x.bases[0]._represents.bases[0].name == 'urlong' assert len(w) == 2 assert 'furlong' in str(w[0].message) assert 'week' in str(w[1].message) @pytest.mark.parametrize('scale, number, string', [('10+2', 100, '10**2'), ('10(+2)', 100, '10**2'), ('10**+2', 100, '10**2'), ('10**(+2)', 100, '10**2'), ('10^+2', 100, '10**2'), ('10^(+2)', 100, '10**2'), ('10**2', 100, '10**2'), ('10**(2)', 100, '10**2'), ('10^2', 100, '10**2'), ('10^(2)', 100, '10**2'), ('10-20', 10**(-20), '10**-20'), ('10(-20)', 10**(-20), '10**-20'), ('10**-20', 10**(-20), '10**-20'), ('10**(-20)', 10**(-20), '10**-20'), ('10^-20', 10**(-20), '10**-20'), ('10^(-20)', 10**(-20), '10**-20'), ]) def test_fits_scale_factor(scale, number, string): x = u.Unit(scale + ' erg/(s cm**2 Angstrom)', format='fits') assert x == number * (u.erg / u.s / u.cm ** 2 / u.Angstrom) assert x.to_string(format='fits') == string + ' Angstrom-1 cm-2 erg s-1' x = u.Unit(scale + '*erg/(s cm**2 Angstrom)', format='fits') assert x == number * (u.erg / u.s / u.cm ** 2 / u.Angstrom) assert x.to_string(format='fits') == string + ' Angstrom-1 cm-2 erg s-1' def test_fits_scale_factor_errors(): with pytest.raises(ValueError): x = u.Unit('1000 erg/(s cm**2 Angstrom)', format='fits') with pytest.raises(ValueError): x = u.Unit('12 erg/(s cm**2 Angstrom)', format='fits') x = u.Unit(1.2 * u.erg) with pytest.raises(ValueError): x.to_string(format='fits') x = u.Unit(100.0 * u.erg) assert x.to_string(format='fits') == '10**2 erg' def test_double_superscript(): """Regression test for #5870, #8699, #9218; avoid double superscripts.""" assert (u.deg).to_string("latex") == r'$\mathrm{{}^{\circ}}$' assert (u.deg**2).to_string("latex") == r'$\mathrm{deg^{2}}$' assert (u.arcmin).to_string("latex") == r'$\mathrm{{}^{\prime}}$' assert (u.arcmin**2).to_string("latex") == r'$\mathrm{arcmin^{2}}$' assert (u.arcsec).to_string("latex") == r'$\mathrm{{}^{\prime\prime}}$' assert (u.arcsec**2).to_string("latex") == r'$\mathrm{arcsec^{2}}$' assert (u.hourangle).to_string("latex") == r'$\mathrm{{}^{h}}$' assert (u.hourangle**2).to_string("latex") == r'$\mathrm{hourangle^{2}}$' assert (u.electron).to_string("latex") == r'$\mathrm{e^{-}}$' assert (u.electron**2).to_string("latex") == r'$\mathrm{electron^{2}}$' @pytest.mark.parametrize('power,expected', ( (1., 'm'), (2., 'm2'), (-10, '1 / m10'), (1.5, 'm(3/2)'), (2/3, 'm(2/3)'), (7/11, 'm(7/11)'), (-1/64, '1 / m(1/64)'), (1/100, 'm(1/100)'), (2/101, 'm(0.019801980198019802)'), (Fraction(2, 101), 'm(2/101)'))) def test_powers(power, expected): """Regression test for #9279 - powers should not be oversimplified.""" unit = u.m ** power s = unit.to_string() assert s == expected assert unit == s @pytest.mark.parametrize('string,unit', [ ('\N{MICRO SIGN}g', u.microgram), ('\N{GREEK SMALL LETTER MU}g', u.microgram), ('g\N{MINUS SIGN}1', u.g**(-1)), ('m\N{SUPERSCRIPT MINUS}\N{SUPERSCRIPT ONE}', 1 / u.m), ('m s\N{SUPERSCRIPT MINUS}\N{SUPERSCRIPT ONE}', u.m / u.s), ('m\N{SUPERSCRIPT TWO}', u.m**2), ('m\N{SUPERSCRIPT PLUS SIGN}\N{SUPERSCRIPT TWO}', u.m**2), ('m\N{SUPERSCRIPT THREE}', u.m**3), ('m\N{SUPERSCRIPT ONE}\N{SUPERSCRIPT ZERO}', u.m**10), ('\N{GREEK CAPITAL LETTER OMEGA}', u.ohm), ('\N{OHM SIGN}', u.ohm), # deprecated but for compatibility ('\N{MICRO SIGN}\N{GREEK CAPITAL LETTER OMEGA}', u.microOhm), ('\N{ANGSTROM SIGN}', u.Angstrom), ('\N{ANGSTROM SIGN} \N{OHM SIGN}', u.Angstrom * u.Ohm), ('\N{LATIN CAPITAL LETTER A WITH RING ABOVE}', u.Angstrom), ('\N{LATIN CAPITAL LETTER A}\N{COMBINING RING ABOVE}', u.Angstrom), ('m\N{ANGSTROM SIGN}', u.milliAngstrom), ('°C', u.deg_C), ('°', u.deg), ('M⊙', u.Msun), # \N{CIRCLED DOT OPERATOR} ('L☉', u.Lsun), # \N{SUN} ('M⊕', u.Mearth), # normal earth symbol = \N{CIRCLED PLUS} ('M♁', u.Mearth), # be generous with \N{EARTH} ('R♃', u.Rjup), # \N{JUPITER} ('′', u.arcmin), # \N{PRIME} ('R∞', u.Ry), ('Mₚ', u.M_p), ]) def test_unicode(string, unit): assert u_format.Generic.parse(string) == unit assert u.Unit(string) == unit @pytest.mark.parametrize('string', [ 'g\N{MICRO SIGN}', 'g\N{MINUS SIGN}', 'm\N{SUPERSCRIPT MINUS}1', 'm+\N{SUPERSCRIPT ONE}', 'm\N{MINUS SIGN}\N{SUPERSCRIPT ONE}', 'k\N{ANGSTROM SIGN}', ]) def test_unicode_failures(string): with pytest.raises(ValueError): u.Unit(string) @pytest.mark.parametrize('format_', ('unicode', 'latex', 'latex_inline')) def test_parse_error_message_for_output_only_format(format_): with pytest.raises(NotImplementedError, match='not parse'): u.Unit('m', format=format_) def test_unknown_parser(): with pytest.raises(ValueError, match=r"Unknown.*unicode'\] for output only"): u.Unit('m', format='foo')