Created
July 15, 2025 10:30
-
-
Save astrofrog/a0c88718992029198b79245114469d81 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import timeit | |
| import numpy as np | |
| from astropy.wcs import WCS | |
| from astropy.io import fits | |
| HEADER_WITH_NON_SI_UNITS = """ | |
| WCSAXES = 5 | |
| CTYPE1 = 'RA---TAN' | |
| CTYPE2 = 'FREQ' | |
| CTYPE3 = 'DEC--TAN' | |
| CTYPE4 = 'WAVE' | |
| CTYPE5 = 'OFFSET' | |
| CUNIT1 = 'arcsec' | |
| CUNIT2 = 'GHz' | |
| CUNIT3 = 'arcsec' | |
| CUNIT4 = 'nm' | |
| CUNIT5 = 'arcmin' | |
| CRVAL1 = 4 | |
| CRVAL2 = 5 | |
| CRVAL3 = 6 | |
| CRVAL4 = 7 | |
| CRVAL5 = 8 | |
| CRPIX1 = 1 | |
| CRPIX2 = 2 | |
| CRPIX3 = 3 | |
| CRPIX4 = 4 | |
| CRPIX5 = 5 | |
| CDELT1 = 4 | |
| CDELT2 = 3 | |
| CDELT3 = 2 | |
| CDELT4 = 1 | |
| CDELT5 = 6 | |
| """.strip() | |
| header = fits.Header.fromstring(HEADER_WITH_NON_SI_UNITS, sep="\n") | |
| wcs_default = WCS(header) | |
| wcs_preserve = WCS(header, preserve_units=True) | |
| scale = np.array([1 / 3600, 1e9, 1 / 3600, 1e-9, 1]) | |
| pixel_coords = np.random.random((10000, 5)) | |
| world_coords_si = pixel_coords * scale | |
| world_coords_native = pixel_coords | |
| # Check that world2pix returns consistent results | |
| np.testing.assert_allclose( | |
| wcs_default.all_world2pix(world_coords_si, 0), | |
| wcs_preserve.all_world2pix(world_coords_native, 0), | |
| ) | |
| chunks = [ | |
| "wcs_default.all_pix2world(2, 3, 8, 1, 2, 0)", | |
| "wcs_default.all_pix2world(pixel_coords, 0)", | |
| "wcs_default.all_world2pix(2, 3, 8, 1, 2, 0)", | |
| "wcs_default.all_world2pix(world_coords_si, 0)", | |
| "wcs_preserve.all_pix2world(2, 3, 8, 1, 2, 0)", | |
| "wcs_preserve.all_pix2world(pixel_coords, 0)", | |
| "wcs_preserve.all_world2pix(2, 3, 8, 1, 2, 0)", | |
| "wcs_preserve.all_world2pix(world_coords_native, 0)", | |
| ] | |
| n_initial = 100 | |
| n_iter = 10 | |
| for code in chunks: | |
| approx = timeit.timeit(code, number=n_initial, globals=locals()) | |
| # number = 10**(int(log10(n_initial / approx))) | |
| number = 1000 | |
| timings = [] | |
| for iteration in range(n_iter): | |
| timings.append( | |
| timeit.timeit(code, number=number, globals=locals()) * 1000 / number | |
| ) | |
| print(f"{code:50s} {np.mean(timings):.3f} +/- {np.std(timings):.3f} ms") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment