Skip to content

Commit 95ec1e5

Browse files
committed
Merge pull request astropy#171 from astrofrog/fix-noncelestial-angular-wcs
Fix subtle unit bug for angular axes
2 parents c601bfa + a7d7fca commit 95ec1e5

7 files changed

Lines changed: 90 additions & 4 deletions

File tree

‎CHANGES.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
0.5 (unreleased)
22
----------------
33

4-
- No changes yet.
4+
- Fix a bug that caused ticks and labels to be incorrect if a WCS object was
5+
used that was not recognized as celestial by WCSlib but had angular units for
6+
the axes, when setting the coord_type to longitude/latitude. [#171]
57

68
0.4 (2015-06-07)
79
----------------

‎wcsaxes/coordinate_helpers.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,8 +146,13 @@ def set_coord_type(self, coord_type, coord_wrap=None):
146146

147147
# Initialize tick formatter/locator
148148
if coord_type == 'scalar':
149+
self._coord_unit_scale = None
149150
self._formatter_locator = ScalarFormatterLocator(unit=self.coord_unit)
150151
elif coord_type in ['longitude', 'latitude']:
152+
if self.coord_unit is u.deg:
153+
self._coord_unit_scale = None
154+
else:
155+
self._coord_unit_scale = self.coord_unit.to(u.deg)
151156
self._formatter_locator = AngleFormatterLocator()
152157
else:
153158
raise ValueError("coord_type should be one of 'scalar', 'longitude', or 'latitude'")
@@ -174,16 +179,25 @@ def format_coord(self, value):
174179
Given the value of a coordinate, will format it according to the
175180
format of the formatter_locator.
176181
"""
182+
177183
if not hasattr(self, "_fl_spacing"):
178184
return "" # _update_ticks has not been called yet
185+
179186
fl = self._formatter_locator
180187
if isinstance(fl, AngleFormatterLocator):
188+
189+
# Convert to degrees if needed
190+
if self._coord_unit_scale is not None:
191+
value *= self._coord_unit_scale
192+
181193
if self.coord_type == 'longitude':
182194
value = wrap_angle_at(value, self.coord_wrap)
183195
value = value * u.degree
184196
value = value.to(fl._unit).value
197+
185198
spacing = self._fl_spacing
186199
string = fl.formatter(values=[value] * fl._unit, spacing=spacing)
200+
187201
return string[0]
188202

189203
def set_separator(self, separator):
@@ -460,6 +474,10 @@ def _update_ticks(self, renderer):
460474
# Rotate by 90 degrees
461475
dx, dy = -dy, dx
462476

477+
if self._coord_unit_scale is not None:
478+
dx *= self._coord_unit_scale
479+
dy *= self._coord_unit_scale
480+
463481
if self.coord_type == 'longitude':
464482
# Here we wrap at 180 not self.coord_wrap since we want to
465483
# always ensure abs(dx) < 180 and abs(dy) < 180
@@ -479,6 +497,11 @@ def _update_ticks(self, renderer):
479497
# longitudes.
480498
w1 = spine.world[:-1, self.coord_index]
481499
w2 = spine.world[1:, self.coord_index]
500+
501+
if self._coord_unit_scale is not None:
502+
w1 = w1 * self._coord_unit_scale
503+
w2 = w2 * self._coord_unit_scale
504+
482505
if self.coord_type == 'longitude':
483506
w1 = wrap_angle_at(w1, self.coord_wrap)
484507
w2 = wrap_angle_at(w2, self.coord_wrap)
@@ -631,6 +654,11 @@ def _update_grid_lines(self):
631654
# single go rather than doing this in the gridline to path conversion
632655
# to fully benefit from vectorized coordinate transformations.
633656

657+
# Currently xy_world is in deg, but transform function needs it in
658+
# native units
659+
if self._coord_unit_scale is not None:
660+
xy_world /= self._coord_unit_scale
661+
634662
# Transform line to pixel coordinates
635663
pixel = self.transform.inverted().transform(xy_world)
636664

‎wcsaxes/coordinate_range.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import warnings
44

55
import numpy as np
6+
from astropy import units as u
67

78
from . import settings
89

@@ -16,7 +17,7 @@ def wrap_180(values):
1617
return values_new
1718

1819

19-
def find_coordinate_range(transform, extent, coord_types):
20+
def find_coordinate_range(transform, extent, coord_types, coord_units):
2021
'''
2122
Find the range of coordinates to use for ticks/grids
2223
@@ -32,6 +33,8 @@ def find_coordinate_range(transform, extent, coord_types):
3233
coord_types : list of str
3334
Whether each coordinate is a ``'longitude'``, ``'latitude'``, or
3435
``'scalar'`` value.
36+
coord_units : list of `astropy.units.Unit`
37+
The units for each coordinate
3538
'''
3639

3740
# Sample coordinates on a NX x NY grid.
@@ -49,6 +52,9 @@ def find_coordinate_range(transform, extent, coord_types):
4952

5053
if coord_type in ['longitude', 'latitude']:
5154

55+
unit = coord_units[coord_index]
56+
xw = xw * unit.to(u.deg)
57+
5258
# Iron out coordinates along first row
5359
wjump = xw[0, 1:] - xw[0, :-1]
5460
with np.errstate(invalid='ignore'):

‎wcsaxes/coordinates_map.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,4 +113,5 @@ def get_coord_range(self):
113113
ymin, ymax = self._axes.get_ylim()
114114
return find_coordinate_range(self._transform,
115115
[xmin, xmax, ymin, ymax],
116-
[coord.coord_type for coord in self])
116+
[coord.coord_type for coord in self],
117+
[coord.coord_unit for coord in self])

‎wcsaxes/core.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,8 +133,18 @@ def reset_wcs(self, wcs=None, slices=None, transform=None, coord_meta=None):
133133

134134
# Here determine all the coordinate axes that should be shown.
135135
if wcs is None and transform is None:
136+
136137
self.wcs = IDENTITY
138+
137139
else:
140+
141+
# We now force call 'set', which ensures the WCS object is
142+
# consistent, which will only be important if the WCS has been set
143+
# by hand. For example if the user sets a celestial WCS by hand and
144+
# forgets to set the units, WCS.wcs.set() will do this.
145+
if wcs is not None:
146+
wcs.wcs.set()
147+
138148
self.wcs = wcs
139149

140150
# If we are making a new WCS, we need to preserve the path object since
9.59 KB
Loading

‎wcsaxes/tests/test_images.py‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,19 @@
22
import os
33
import shutil
44
import tempfile
5+
6+
import numpy as np
57
import matplotlib.pyplot as plt
68
from matplotlib.testing.compare import compare_images
79
from matplotlib.patches import Circle
8-
from ..rc_utils import rc_context
910

1011
from astropy import units as u
1112
from astropy.io import fits
1213
from astropy.tests.helper import pytest
1314
from astropy.tests.helper import remote_data
15+
16+
from ..rc_utils import rc_context
17+
1418
from .. import datasets, WCS, WCSAxes
1519

1620

@@ -357,3 +361,38 @@ def test_axislabels_regression(self):
357361
ax.coords[1].set_axislabel("Label 2")
358362
ax.coords[1].ticklabels.set_visible(False)
359363
return fig
364+
365+
@pytest.mark.mpl_image_compare(savefig_kwargs={'bbox_inches': 'tight'},
366+
tolerance=1.5)
367+
def test_noncelestial_angular(self, tmpdir):
368+
# Regression test for a bug that meant that when passing a WCS that had
369+
# angular axes and using set_coord_type to set the coordinates to
370+
# longitude/latitude, but where the WCS wasn't recognized as celestial,
371+
# the WCS units are not converted to deg, so we can't assume that
372+
# transform will always return degrees.
373+
374+
wcs = WCS(naxis=2)
375+
376+
wcs.wcs.ctype = ['solar-x', 'solar-y']
377+
wcs.wcs.cunit = ['arcsec', 'arcsec']
378+
379+
fig = plt.figure(figsize=(3, 3))
380+
ax = fig.add_subplot(1,1,1,projection=wcs)
381+
382+
ax.imshow(np.zeros([1024, 1024]), origin='lower')
383+
384+
ax.coords[0].set_coord_type('longitude', coord_wrap=180)
385+
ax.coords[1].set_coord_type('latitude')
386+
387+
ax.coords[0].set_major_formatter('s.s')
388+
ax.coords[1].set_major_formatter('s.s')
389+
390+
ax.grid(color='white', ls='solid')
391+
392+
# Force drawing (needed for format_coord)
393+
fig.savefig(tmpdir.join('nothing').strpath)
394+
395+
# TODO: the formatted string should show units
396+
assert ax.format_coord(512, 512) == "513.0 513.0 (world)"
397+
398+
return fig

0 commit comments

Comments
 (0)