Skip to content

Commit

Permalink
Merge pull request #2491 from astrofrog/affine-nan-issue
Browse files Browse the repository at this point in the history
Make WCSLink.as_affine_link more robust to NaN values and raise an error if no overlap
  • Loading branch information
astrofrog authored May 10, 2024
2 parents c2c5cfa + 8e39c2e commit 7ad868f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
26 changes: 26 additions & 0 deletions glue/plugins/wcs_autolinking/tests/test_wcs_autolinking.py
Original file line number Diff line number Diff line change
Expand Up @@ -591,3 +591,29 @@ def test_wcs_no_approximation():

with pytest.raises(NoAffineApproximation):
link.as_affine_link(tolerance=0.1)


def test_no_wcs_overlap():

wcs1 = WCS(naxis=2)
wcs1.wcs.ctype = 'RA---TAN', 'DEC--TAN'
wcs1.wcs.crval = 10, 20
wcs1.wcs.set()

data1 = Data(label='Data 1')
data1.coords = wcs1
data1['x'] = np.ones((2, 3))

wcs2 = WCS(naxis=2)
wcs2.wcs.ctype = 'RA---TAN', 'DEC--TAN'
wcs2.wcs.crval = 190, -20
wcs2.wcs.set()

data2 = Data(label='Data 2')
data2.coords = wcs2
data2['x'] = np.ones((2, 3))

link = WCSLink(data1, data2)

with pytest.raises(NoAffineApproximation, match='no overlap'):
link.as_affine_link()
17 changes: 16 additions & 1 deletion glue/plugins/wcs_autolinking/wcs_autolinking.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,13 +260,28 @@ def as_affine_link(self, n_samples=1000, tolerance=1):
# Convert to pixel positions in data2
pixel2 = self.forwards(*pixel1)

keep = np.ones(n_samples, dtype=bool)
for p in pixel1 + pixel2:
keep[np.isnan(p)] = False

if not np.any(keep):
raise NoAffineApproximation(f'Could not find a good affine approximation to '
f'WCSLink with tolerance={tolerance}, as no overlap')

pixel1 = [p[keep] for p in pixel1]
pixel2 = [p[keep] for p in pixel2]

# First try simple offset

def transform_offset(offsets):
pixel1_tr = pixel1[0] - offsets[0], pixel1[1] - offsets[1]
return np.hypot(pixel2[0] - pixel1_tr[0], pixel2[1] - pixel1_tr[1])

best, _ = leastsq(transform_offset, (0, 0))
best, status = leastsq(transform_offset, (0, 0))

if status not in [1, 2, 3, 4]:
raise NoAffineApproximation(f'Could not find a good affine approximation to '
f'WCSLink with tolerance={tolerance}, as fitting failed')

max_deviation = np.max(transform_offset(best))

Expand Down

0 comments on commit 7ad868f

Please sign in to comment.