From 1baa46d1516cbecd0776984ffc5efcd349383db0 Mon Sep 17 00:00:00 2001 From: Bradley Sappington <101193271+BradleySappington@users.noreply.github.com> Date: Mon, 13 May 2024 12:25:40 -0400 Subject: [PATCH] ruff auto-fix and format imports (#846) --- dev_utils/compute_psf_library.py | 15 ++++---- .../field_dependence/read_codev_dat_fits.py | 14 +++---- dev_utils/make-minimal-datafiles.py | 2 - dev_utils/wfe_benchmark.py | 16 ++++---- docs/exts/numfig.py | 3 +- webbpsf/jupyter_gui.py | 17 ++++----- webbpsf/mast_wss.py | 8 ++-- webbpsf/match_data.py | 7 +--- webbpsf/opds.py | 33 ++++++++-------- webbpsf/optical_budget.py | 33 ++++++++-------- webbpsf/optics.py | 23 +++++------ webbpsf/roman.py | 15 +++----- webbpsf/surs.py | 6 +-- webbpsf/tests/test_errorhandling.py | 12 ++---- webbpsf/tests/test_fgs.py | 8 +--- webbpsf/tests/test_nircam.py | 21 +++++----- webbpsf/tests/test_niriss.py | 5 +-- webbpsf/tests/test_nirspec.py | 14 ++----- webbpsf/tests/test_opds.py | 8 ++-- webbpsf/tests/test_roman.py | 7 ++-- webbpsf/tests/test_utils.py | 10 +---- webbpsf/tests/test_webbpsf.py | 14 +++---- webbpsf/tests/validate_webbpsf.py | 17 ++++----- webbpsf/trending.py | 23 ++++++----- webbpsf/utils.py | 24 ++++++------ webbpsf/webbpsf_core.py | 38 ++++++++----------- 26 files changed, 169 insertions(+), 224 deletions(-) diff --git a/dev_utils/compute_psf_library.py b/dev_utils/compute_psf_library.py index fafda886..cef8d274 100644 --- a/dev_utils/compute_psf_library.py +++ b/dev_utils/compute_psf_library.py @@ -1,12 +1,12 @@ -import sys -import multiprocessing +import datetime import logging import logging.handlers -import datetime -import time -from os.path import abspath, sep, join, exists, isdir, split +import multiprocessing import os -from itertools import product, chain +import sys +from itertools import chain, product +from os.path import abspath, exists, isdir, join, split + import matplotlib matplotlib.use('Agg') @@ -16,8 +16,7 @@ if not os.environ.get('WEBBPSF_PATH'): os.environ['WEBBPSF_PATH'] = '/grp/jwst/ote/webbpsf-data' -import webbpsf - +import webbpsf # noqa N_PROCESSES = 16 diff --git a/dev_utils/field_dependence/read_codev_dat_fits.py b/dev_utils/field_dependence/read_codev_dat_fits.py index 46c82dce..0997c5bd 100644 --- a/dev_utils/field_dependence/read_codev_dat_fits.py +++ b/dev_utils/field_dependence/read_codev_dat_fits.py @@ -1,11 +1,11 @@ +from datetime import datetime + +import astropy.io.fits as fits +import basis import numpy as np import pint units = pint.UnitRegistry() -import astropy.io.fits as fits -import basis -import matplotlib.pyplot as plt -from datetime import datetime # Script that reads in a set of CodeV Pupil map OPD files across fields and instruments and fits Zernikes to the OPD # distribution at each field point and then Legendres to the variation of each Zernike coefficient across field. The @@ -19,9 +19,9 @@ def read_codeV_data_file(filename): for i, line in enumerate(fh): if i is headerlines: break - if i is 6: + if i == 6: x_field_deg = float(str.split(line)[3]) - if i is 7: + if i == 7: y_field_deg = float(str.split(line)[3]) data = np.loadtxt(filename, skiprows=headerlines) data_defined = data != -99999 @@ -36,7 +36,7 @@ def main(): num_wf_pts_x = 256 num_wf_pts_y = 256 - instruments = [ + instruments = [ 'fgs', 'nircam', 'miri', diff --git a/dev_utils/make-minimal-datafiles.py b/dev_utils/make-minimal-datafiles.py index 37da33b7..9b6a3964 100755 --- a/dev_utils/make-minimal-datafiles.py +++ b/dev_utils/make-minimal-datafiles.py @@ -3,9 +3,7 @@ # This is used to make a stripped-down version of the data files for use on GitHub Actions import os, sys -import astropy.io.fits as fits import subprocess -import glob try: inputfile = sys.argv[1] diff --git a/dev_utils/wfe_benchmark.py b/dev_utils/wfe_benchmark.py index 7b31c538..e8a30aab 100644 --- a/dev_utils/wfe_benchmark.py +++ b/dev_utils/wfe_benchmark.py @@ -5,7 +5,7 @@ webbpsf.webbpsf_core.poppy.conf.use_fftw = False webbpsf.webbpsf_core.poppy.conf.use_multiprocessing = True ncores = 8 -webbpsf.webbpsf_core.poppy.conf.n_processes = ncores +webbpsf.webbpsf_core.poppy.conf.n_processes = ncores inst = webbpsf.NIRCam() inst.filter = "F430M" @@ -13,21 +13,21 @@ # Baseline test: No SI WFE, no distortion inst.include_si_wfe = False -%timeit psf = inst.calc_psf(add_distortion=False, monochromatic=4.3e-6) +%timeit psf = inst.calc_psf(add_distortion=False, monochromatic=4.3e-6) # noqa # Result: 911 ms ± 5.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) -%timeit psf = inst.calc_psf(add_distortion=False, nlambda=ncores) +%timeit psf = inst.calc_psf(add_distortion=False, nlambda=ncores) # noqa # Result: 5.62 s ± 177 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # Turn on SI WFE at center of detector (will use interpolation) inst.include_si_wfe = True -%timeit psf = inst.calc_psf(add_distortion=False, monochromatic=4.3e-6) +%timeit psf = inst.calc_psf(add_distortion=False, monochromatic=4.3e-6) # noqa # Result: 1.41 s ± 12.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) -%timeit psf = inst.calc_psf(add_distortion=False, nlambda=ncores) +%timeit psf = inst.calc_psf(add_distortion=False, nlambda=ncores) # noqa # Result: 6.1 s ± 96.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # Use pixel (0,0) to force extrapolation algorithm inst.detector_position = (0,0) -%timeit psf = inst.calc_psf(add_distortion=False, monochromatic=4.3e-6) +%timeit psf = inst.calc_psf(add_distortion=False, monochromatic=4.3e-6) # noqa # Result: 1.8 s ± 12.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) -%timeit psf = inst.calc_psf(add_distortion=False, nlambda=ncores) -# Result: 6.53 s ± 85.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) \ No newline at end of file +%timeit psf = inst.calc_psf(add_distortion=False, nlambda=ncores) # noqa +# Result: 6.53 s ± 85.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) diff --git a/docs/exts/numfig.py b/docs/exts/numfig.py index 31343827..e9d63e27 100644 --- a/docs/exts/numfig.py +++ b/docs/exts/numfig.py @@ -1,7 +1,6 @@ -from docutils.nodes import figure, caption, Text, reference, raw, SkipNode, Element +from docutils.nodes import SkipNode, Text, caption, figure, raw, reference from sphinx.roles import XRefRole - # Element classes class page_ref(reference): diff --git a/webbpsf/jupyter_gui.py b/webbpsf/jupyter_gui.py index 76166b18..9c55699d 100644 --- a/webbpsf/jupyter_gui.py +++ b/webbpsf/jupyter_gui.py @@ -1,12 +1,9 @@ import logging -import matplotlib -import astropy.io.fits as fits +import astropy.io.fits as fits import poppy -from . import webbpsf_core -from . import roman -from . import utils +from . import roman, webbpsf_core _log = logging.getLogger('webbpsf') @@ -35,16 +32,17 @@ def show_notebook_interface_wfi(instrument): # (Currently not a hard dependency for the full webbpsf package, so we import # within the function.) import ipywidgets as widgets - from IPython.display import display, clear_output + from IPython.display import clear_output, display from matplotlib import pyplot as plt try: import synphot except ImportError: - raise ImportError(f'For now, synphot must be installed to use the notebook interface') + raise ImportError('For now, synphot must be installed to use the notebook interface') # Clean up some warnings we know about so as not to scare the users import warnings + from matplotlib.cbook import MatplotlibDeprecationWarning warnings.simplefilter('ignore', MatplotlibDeprecationWarning) @@ -219,7 +217,7 @@ def show_notebook_interface_jwst(instrument): # (Currently not a hard dependency for the full webbpsf package, so we import # within the function.) import ipywidgets as widgets - from IPython.display import display, clear_output + from IPython.display import clear_output, display from matplotlib import pyplot as plt if isinstance(instrument, str): @@ -228,10 +226,11 @@ def show_notebook_interface_jwst(instrument): try: import synphot except ImportError: - raise ImportError(f'For now, synphot must be installed to use the notebook interface') + raise ImportError('For now, synphot must be installed to use the notebook interface') # Clean up some warnings we know about so as not to scare the users import warnings + from matplotlib.cbook import MatplotlibDeprecationWarning warnings.simplefilter('ignore', MatplotlibDeprecationWarning) diff --git a/webbpsf/mast_wss.py b/webbpsf/mast_wss.py index 735fca96..482632fc 100644 --- a/webbpsf/mast_wss.py +++ b/webbpsf/mast_wss.py @@ -1,8 +1,8 @@ # Functions for interacting with the MAST archive and JWST measured data -import os import functools +import os import astropy import astropy.io.fits as fits @@ -10,7 +10,6 @@ import astropy.units as u import numpy as np from astropy.time import Time, TimeDelta - from astroquery.mast import Mast, Observations import webbpsf.utils @@ -285,7 +284,7 @@ def import_wss_opd(filename, npix_out=1024, verbose=False): # initial coarse resolution on the segment gaps mask = inputOPD != 0 paddedOPD = webbpsf.utils.border_extrapolate_pad(inputOPD, mask) - wasopd[0].header.add_history(f' Dilated OPD values to fill adjacent invalid pixels (i.e. fill in gaps)') + wasopd[0].header.add_history(' Dilated OPD values to fill adjacent invalid pixels (i.e. fill in gaps)') # interpolate to larger size newopd = webbpsf.utils.rescale_interpolate_opd(paddedOPD, npix_out) @@ -753,9 +752,10 @@ def get_visit_nrc_ta_image(visitid, verbose=True, kind='cal'): except urllib.error.HTTPError as err: if err.code == 401: # Unauthorized # Use MAST API to allow retrieval of exclusive access data, if relevant - import astroquery import tempfile + import astroquery + mast_api_token = os.environ.get('MAST_API_TOKEN', None) mast_obs = astroquery.mast.ObservationsClass(mast_api_token) uri = f'mast:JWST/product/{filename}' diff --git a/webbpsf/match_data.py b/webbpsf/match_data.py index c2f0facb..7e6e4777 100644 --- a/webbpsf/match_data.py +++ b/webbpsf/match_data.py @@ -1,12 +1,9 @@ ## Functions to match or fit PSFs to observed JWST data import astropy -import astropy.units as u import astropy.io.fits as fits - -import scipy.optimize +import pysiaf import webbpsf -import pysiaf def setup_sim_to_match_file(filename_or_HDUList, verbose=True, plot=False, choice='closest'): @@ -30,7 +27,7 @@ def setup_sim_to_match_file(filename_or_HDUList, verbose=True, plot=False, choic else: header = filename_or_HDUList[0].header if verbose: - print(f'Setting up sim to match provided FITS HDUList object') + print('Setting up sim to match provided FITS HDUList object') inst = webbpsf.instrument(header['INSTRUME']) diff --git a/webbpsf/opds.py b/webbpsf/opds.py index 537fd073..7bfa93db 100644 --- a/webbpsf/opds.py +++ b/webbpsf/opds.py @@ -26,32 +26,29 @@ # prescription, as published for instance in Lightsey et al. 2012 Opt. Eng. # ############################################################################### +import copy import functools -import os -import numpy as np -import matplotlib.pyplot as plt -import matplotlib -import scipy.special as sp -import scipy -import astropy.table -import astropy.io.fits as fits -import astropy.units as u import logging -from collections import OrderedDict +import os import warnings -from packaging.version import Version -import copy +from collections import OrderedDict +import astropy.io.fits as fits +import astropy.table +import astropy.units as u +import matplotlib +import matplotlib.pyplot as plt +import numpy as np import poppy import poppy.zernike as zernike +import scipy +import scipy.special as sp +from packaging.version import Version -import pysiaf - -from . import constants -from . import surs -from . import utils import webbpsf +from . import constants, surs, utils + _log = logging.getLogger('webbpsf') __doc__ = """ @@ -1651,7 +1648,7 @@ def _get_field_dependence_secondary_mirror(self, v2v3): wfe_sign = 1 for i in range(3, 9): - self.opd_header[f'SMIF_H{i}'] = (z_coeffs[i], f'Hexike coeff from S.M. influence fn model') + self.opd_header[f'SMIF_H{i}'] = (z_coeffs[i], 'Hexike coeff from S.M. influence fn model') self.opd_header['HISTORY'] = 'Field point (x,y): ({})'.format(v2v3) self.opd_header['HISTORY'] = 'Control point: {} ({})'.format( self.control_point_fieldpoint.upper(), self.ote_control_point diff --git a/webbpsf/optical_budget.py b/webbpsf/optical_budget.py index 1f7a083c..37e84481 100644 --- a/webbpsf/optical_budget.py +++ b/webbpsf/optical_budget.py @@ -1,12 +1,13 @@ import os -import numpy as np -import matplotlib.pyplot as plt -import webbpsf -import poppy + import astropy.table as table import astropy.units as u -from webbpsf.utils import rms +import matplotlib.pyplot as plt +import numpy as np +import poppy +import webbpsf +from webbpsf.utils import rms ### JWST Optical Budgets Information # This module makes extensive use of information from the JWST Optical Budget @@ -290,7 +291,7 @@ def visualize_wfe_budget(inst, slew_delta_time=14 * u.day, slew_case='EOL', ptt_ show_opd( wfe_ote_static, aperture, - title=f'OTE total static wavefront', + title='OTE total static wavefront', ax=axes[1, 0], annotate_budget='OTE total static', instname=inst.name, @@ -300,7 +301,7 @@ def visualize_wfe_budget(inst, slew_delta_time=14 * u.day, slew_case='EOL', ptt_ show_opd( wfe_ote_controllable, aperture, - title=f'OTE controllable mode residuals\n(low+mid s.f.)', + title='OTE controllable mode residuals\n(low+mid s.f.)', ax=axes[1, 1], annotate_budget='OTE residual controllable modes (mid freq)', instname=inst.name, @@ -308,7 +309,7 @@ def visualize_wfe_budget(inst, slew_delta_time=14 * u.day, slew_case='EOL', ptt_ show_opd( wfe_ote_uncontrollable, aperture, - title=f'OTE uncontrollable WFE\n(high s.f.)', + title='OTE uncontrollable WFE\n(high s.f.)', ax=axes[1, 2], annotate_budget='OTE uncontrollable high freq', instname=inst.name, @@ -316,7 +317,7 @@ def visualize_wfe_budget(inst, slew_delta_time=14 * u.day, slew_case='EOL', ptt_ show_opd( wfe_ote_field_dep, aperture, - title=f'OTE field-dependent WFE\n(low s.f.)', + title='OTE field-dependent WFE\n(low s.f.)', ax=axes[1, 3], annotate_budget='OTE residual low freq (field dep)', instname=inst.name, @@ -325,7 +326,7 @@ def visualize_wfe_budget(inst, slew_delta_time=14 * u.day, slew_case='EOL', ptt_ show_opd( wfe_ote_dynamic, aperture, - title=f'OTE total dynamic wavefront', + title='OTE total dynamic wavefront', ax=axes[2, 0], annotate_budget='OTE total dynamic', instname=inst.name, @@ -334,7 +335,7 @@ def visualize_wfe_budget(inst, slew_delta_time=14 * u.day, slew_case='EOL', ptt_ ax = show_opd( wfe_ote_dynamic_thermal, aperture, - title=f'OTE thermal drifts', + title='OTE thermal drifts', ax=axes[2, 1], annotate_budget='OTE stability', instname=inst.name, @@ -348,12 +349,12 @@ def visualize_wfe_budget(inst, slew_delta_time=14 * u.day, slew_case='EOL', ptt_ horizontalalignment='right', ) show_opd( - wfe_ote_dynamic_vibe, aperture, title=f'OTE vibe', ax=axes[2, 2], annotate_budget='OTE vibe', instname=inst.name + wfe_ote_dynamic_vibe, aperture, title='OTE vibe', ax=axes[2, 2], annotate_budget='OTE vibe', instname=inst.name ) ax = show_opd( wfe_for_imagemotion, aperture, - title=f'image motion$^*$ (as equiv. WFE)', + title='image motion$^*$ (as equiv. WFE)', ax=axes[2, 3], annotate_budget='Image motion (as equiv. WFE)', instname=inst.name, @@ -364,7 +365,7 @@ def visualize_wfe_budget(inst, slew_delta_time=14 * u.day, slew_case='EOL', ptt_ show_opd( wfe_si, aperture, - title=f'ISIM+SI total ', + title='ISIM+SI total ', ax=axes[3, 0], annotate_budget='ISIM+SI total', instname=inst.name, @@ -381,7 +382,7 @@ def visualize_wfe_budget(inst, slew_delta_time=14 * u.day, slew_case='EOL', ptt_ show_opd( wfe_si * 0, aperture, - title=f'ISIM struct. align.', + title='ISIM struct. align.', ax=axes[3, 2], annotate_budget='ISIM structural', instname=inst.name, @@ -389,7 +390,7 @@ def visualize_wfe_budget(inst, slew_delta_time=14 * u.day, slew_case='EOL', ptt_ show_opd( wfe_si_dynamic, aperture, - title=f'ISIM+SI instability', + title='ISIM+SI instability', ax=axes[3, 3], annotate_budget='ISIM+SI instability', instname=inst.name, diff --git a/webbpsf/optics.py b/webbpsf/optics.py index 2b99a2ff..9916c635 100644 --- a/webbpsf/optics.py +++ b/webbpsf/optics.py @@ -1,26 +1,21 @@ +import logging import os -import poppy -import poppy.utils -import numpy as np -import matplotlib -import matplotlib.pyplot as plt -from astropy.table import Table import astropy.io.fits as fits import astropy.units as units - -from scipy.interpolate import griddata, RegularGridInterpolator +import matplotlib +import matplotlib.pyplot as plt +import numpy as np +import poppy +import poppy.utils +from astropy.table import Table +from scipy.interpolate import RegularGridInterpolator, griddata from scipy.ndimage import rotate -from . import webbpsf_core -from . import utils -from . import constants - -import logging +from . import constants, utils, webbpsf_core _log = logging.getLogger('webbpsf') -import pysiaf ####### Classes for modeling aspects of JWST's segmented active primary ##### diff --git a/webbpsf/roman.py b/webbpsf/roman.py index 5c49bf9c..df8f6fe4 100644 --- a/webbpsf/roman.py +++ b/webbpsf/roman.py @@ -8,19 +8,16 @@ mirror polishing errors, which are taken from HST). """ +import logging import os.path -import poppy -import numpy as np -from scipy.interpolate import griddata, RegularGridInterpolator -from astropy.io import fits import astropy.units as u -import logging +import numpy as np +import poppy +from astropy.io import fits +from scipy.interpolate import griddata -from . import utils -from . import webbpsf_core -from . import distortion -from .optics import _fix_zgrid_NaNs +from . import distortion, utils, webbpsf_core _log = logging.getLogger('webbpsf') import pprint diff --git a/webbpsf/surs.py b/webbpsf/surs.py index f512ba5f..910d83e0 100644 --- a/webbpsf/surs.py +++ b/webbpsf/surs.py @@ -99,14 +99,14 @@ def to_global(self): if self.coord == 'global': return self.moves else: - raise NotImplemented('Error') + raise NotImplementedError('Error') def to_local(self): """Return moves cast to local coordinates""" if self.coord == 'local': return self.moves else: - raise NotImplemented('Error') + raise NotImplementedError('Error') # TO implement based on Ball's 'pmglobal_to_seg' in ./wfsc_core_algs/was_core_pmglobal_to_seg.pro # or the code in ./segment_control/mcs_hexapod_obj__define.pro @@ -171,7 +171,7 @@ def describe(self): def xmltext(self): """The XML text representation of a given move""" text = """ - {self.configuration_name} diff --git a/webbpsf/tests/test_errorhandling.py b/webbpsf/tests/test_errorhandling.py index 0fd5d7bb..006fb6fe 100644 --- a/webbpsf/tests/test_errorhandling.py +++ b/webbpsf/tests/test_errorhandling.py @@ -1,22 +1,16 @@ # This file contains code for testing various error handlers and user interface edge cases, # as opposed to testing the main body of functionality of the code. -import sys, os -import os.path import logging +import os +import os.path _log = logging.getLogger('test_webbpsf') _log.addHandler(logging.NullHandler()) -import numpy as np -import matplotlib.pyplot as plt -import astropy.io.fits as fits import pytest -import poppy -from .. import webbpsf_core -from .. import utils -from .. import conf +from .. import conf, utils, webbpsf_core def _exception_message_starts_with(excinfo, message_body): diff --git a/webbpsf/tests/test_fgs.py b/webbpsf/tests/test_fgs.py index 74c625d0..a3f42a75 100644 --- a/webbpsf/tests/test_fgs.py +++ b/webbpsf/tests/test_fgs.py @@ -1,20 +1,14 @@ -import sys, os -import numpy as np -import matplotlib.pyplot as plt -import astropy.io.fits as fits import logging _log = logging.getLogger('test_webbpsf') _log.addHandler(logging.NullHandler()) -from .. import webbpsf_core -import poppy # ------------------ FGS Tests ---------------------------- -from .test_webbpsf import generic_output_test, do_test_source_offset, do_test_set_position_from_siaf +from .test_webbpsf import do_test_set_position_from_siaf, do_test_source_offset, generic_output_test test_fgs = lambda: generic_output_test('FGS') test_fgs_source_offset_00 = lambda: do_test_source_offset('FGS', theta=0.0, monochromatic=2.5e-6) diff --git a/webbpsf/tests/test_nircam.py b/webbpsf/tests/test_nircam.py index 19ba3d3b..80edd94e 100644 --- a/webbpsf/tests/test_nircam.py +++ b/webbpsf/tests/test_nircam.py @@ -1,23 +1,23 @@ -import sys, os -import numpy as np -import matplotlib.pyplot as plt -import astropy.io.fits as fits import copy - import logging +import os + +import astropy.io.fits as fits +import matplotlib.pyplot as plt +import numpy as np _log = logging.getLogger('test_webbpsf') _log.addHandler(logging.NullHandler()) +import pytest + import webbpsf + from .. import webbpsf_core from .test_errorhandling import _exception_message_starts_with -import pytest - - # ------------------ NIRCam Tests ---------------------------- -from .test_webbpsf import generic_output_test, do_test_source_offset, do_test_set_position_from_siaf +from .test_webbpsf import do_test_set_position_from_siaf, do_test_source_offset, generic_output_test test_nircam = lambda: generic_output_test('NIRCam') test_nircam_source_offset_00 = lambda: do_test_source_offset('NIRCam', theta=0.0, monochromatic=2e-6) @@ -390,7 +390,7 @@ def test_nircam_coron_wfe_offset(fov_pix=15, oversample=2, fit_gaussian=True): # Disable Gaussian fit if astropy not installed if fit_gaussian: try: - from astropy.modeling import models, fitting + from astropy.modeling import fitting, models except ImportError: fit_gaussian = False @@ -458,7 +458,6 @@ def test_nircam_auto_aperturename(): """ Test that correct apertures are chosen depending on channel, module, detector, mode, etc. """ - import pysiaf nc = webbpsf_core.NIRCam() diff --git a/webbpsf/tests/test_niriss.py b/webbpsf/tests/test_niriss.py index aef8a90e..ce6f19f2 100644 --- a/webbpsf/tests/test_niriss.py +++ b/webbpsf/tests/test_niriss.py @@ -1,15 +1,12 @@ -import logging import numpy as np # _log = logging.getLogger('test_webbpsf') # _log.addHandler(logging.NullHandler()) - from .. import webbpsf_core # ------------------ NIRISS Tests ---------------------------- - -from .test_webbpsf import generic_output_test, do_test_source_offset, do_test_set_position_from_siaf +from .test_webbpsf import do_test_set_position_from_siaf, do_test_source_offset, generic_output_test test_niriss = lambda: generic_output_test('NIRISS') test_niriss_source_offset_00 = lambda: do_test_source_offset('NIRISS', theta=0.0, monochromatic=3.0e-6) diff --git a/webbpsf/tests/test_nirspec.py b/webbpsf/tests/test_nirspec.py index 7b432c4d..53c10ee6 100644 --- a/webbpsf/tests/test_nirspec.py +++ b/webbpsf/tests/test_nirspec.py @@ -1,22 +1,16 @@ -import sys, os -import numpy as np -import matplotlib.pyplot as plt -import astropy.io.fits as fits +import logging + import astropy.units as u +import numpy as np import pysiaf -import logging - _log = logging.getLogger('test_webbpsf') _log.addHandler(logging.NullHandler()) from .. import webbpsf_core -import poppy - # ------------------ NIRSpec Tests ---------------------------- - -from .test_webbpsf import generic_output_test, do_test_source_offset, do_test_set_position_from_siaf +from .test_webbpsf import do_test_set_position_from_siaf, do_test_source_offset, generic_output_test test_nirspec = lambda: generic_output_test('NIRSpec') diff --git a/webbpsf/tests/test_opds.py b/webbpsf/tests/test_opds.py index a6407a41..970f43fc 100644 --- a/webbpsf/tests/test_opds.py +++ b/webbpsf/tests/test_opds.py @@ -3,15 +3,14 @@ """ import os -from astropy.io import fits import astropy.units as u import matplotlib import matplotlib.pyplot as plt import numpy as np import pysiaf import pytest + import webbpsf -import matplotlib.pyplot as plt # Set up a pinned pysiaf version so as not to break tests with any pysiaf value updates prd_data_dir = pysiaf.constants.JWST_PRD_DATA_ROOT.rsplit('PRD', 1)[0] @@ -242,9 +241,10 @@ def test_sur_basics(): def test_move_sur(plot=False): """Test we can move mirrors using Segment Update Requests""" - import webbpsf - import os import glob + import os + + import webbpsf surdir = os.path.join(webbpsf.__path__[0], 'tests', 'surs') surs = glob.glob(surdir + '/*sur.xml') diff --git a/webbpsf/tests/test_roman.py b/webbpsf/tests/test_roman.py index 932c4729..422eca37 100644 --- a/webbpsf/tests/test_roman.py +++ b/webbpsf/tests/test_roman.py @@ -1,10 +1,11 @@ import os + import numpy as np import pytest -from webbpsf import roman, measure_fwhm from astropy.table import Table from numpy import allclose +from webbpsf import measure_fwhm, roman GRISM_FILTERS = roman.GRISM_FILTERS PRISM_FILTERS = roman.PRISM_FILTERS @@ -118,7 +119,7 @@ def test_WFI_pupil_controller(): # test unlock wfi.unlock_pupil_mask() - assert wfi.pupil == pupil_path(wfi), f'Pupil mask unlock failed' + assert wfi.pupil == pupil_path(wfi), 'Pupil mask unlock failed' assert wfi._pupil_controller._auto_pupil, 'Pupil is locked and should not be' assert wfi._pupil_controller._auto_pupil_mask, 'Pupil mask is locked and should not be' @@ -132,7 +133,7 @@ def test_WFI_pupil_controller(): assert wfi.pupil == this_file, 'Pupil did not lock to proper file.' wfi.unlock_pupil() - assert wfi.pupil == pupil_path(wfi), f'Pupil unlock failed.' + assert wfi.pupil == pupil_path(wfi), 'Pupil unlock failed.' assert wfi._pupil_controller._auto_pupil, 'Pupil is locked and should not be' assert wfi._pupil_controller._auto_pupil_mask, 'Pupil mask is locked and should not be' diff --git a/webbpsf/tests/test_utils.py b/webbpsf/tests/test_utils.py index c1fadb34..fe3ffc58 100644 --- a/webbpsf/tests/test_utils.py +++ b/webbpsf/tests/test_utils.py @@ -1,10 +1,7 @@ -import sys, os -import numpy as np -import matplotlib.pyplot as plt import astropy.io.fits as fits +import numpy as np try: - import pytest _HAVE_PYTEST = True except: @@ -15,12 +12,9 @@ _log = logging.getLogger('test_webbpsf') _log.addHandler(logging.NullHandler()) +from .. import conf, utils, webbpsf_core from .test_errorhandling import _exception_message_starts_with -from .. import webbpsf_core -from .. import utils -from .. import conf - def test_logging_restart(): """Test turning off and on the logging, and then put it back the way it was.""" diff --git a/webbpsf/tests/test_webbpsf.py b/webbpsf/tests/test_webbpsf.py index 4fdc285f..9393751b 100644 --- a/webbpsf/tests/test_webbpsf.py +++ b/webbpsf/tests/test_webbpsf.py @@ -1,17 +1,15 @@ -import sys, os -import numpy as np -import matplotlib.pyplot as plt -import astropy.io.fits as fits - - import logging +import os + +import numpy as np _log = logging.getLogger('test_webbpsf') _log.addHandler(logging.NullHandler()) -from .. import webbpsf_core import poppy + +from .. import webbpsf_core from .test_errorhandling import _exception_message_starts_with @@ -175,8 +173,8 @@ def test_cast_to_str(): def test_return_intermediates(): - import poppy import astropy.io.fits + import poppy nc = webbpsf_core.NIRCam() nc.image_mask = 'maskswb' diff --git a/webbpsf/tests/validate_webbpsf.py b/webbpsf/tests/validate_webbpsf.py index 3d2fe6bf..9b32ccc6 100644 --- a/webbpsf/tests/validate_webbpsf.py +++ b/webbpsf/tests/validate_webbpsf.py @@ -1,15 +1,14 @@ +import logging import os -from astropy.io import fits -import numpy as N + import matplotlib -import pylab as P -import logging +import numpy as N import poppy - +import pylab as P +from astropy.io import fits from .. import webbpsf_core - __doc__ = """ Validation Tests for Webb PSF. These functions perform simulations using WebbPSF and compare @@ -42,7 +41,7 @@ def validate_vs_russ_plot7(base_opd='OPD_RevV_nircam_155.fits'): ax2.set_ybound(0, 0.18) ax2.set_yticks([0.0, 0.05, 0.10, 0.15]) ax2.set_xbound(0.6, 6) - ax2.set_xlabel('Wavelength ($\mu$m)') + ax2.set_xlabel(r'Wavelength ($\mu$m)') ax2.set_ylabel('FWHM (arcsec)') ax1.set_ylabel('Flux within 0.15 arcsec') @@ -445,8 +444,8 @@ def validate_vs_krist_sims(clobber=False, normalize=False, which='spot', no_sam= fig.text(0.50, 0.95, 'Perrin', horizontalalignment='center', size=18) fig.text(0.80, 0.95, 'Difference P-K', horizontalalignment='center', size=18) - fig.text(0.05, 1.0 / 6, 'off-axis 4.6$\mu$m', verticalalignment='center', rotation='vertical', size=18) - fig.text(0.05, 0.48, 'occulted 4.6$\mu$m', verticalalignment='center', rotation='vertical', size=18) + fig.text(0.05, 1.0 / 6, r'off-axis 4.6$\mu$m', verticalalignment='center', rotation='vertical', size=18) + fig.text(0.05, 0.48, r'occulted 4.6$\mu$m', verticalalignment='center', rotation='vertical', size=18) fig.text(0.05, 5.0 / 6 - 0.05, image_mask + ' occulter', verticalalignment='center', rotation='vertical', size=18) P.subplot(331) diff --git a/webbpsf/trending.py b/webbpsf/trending.py index dbb181d6..3ad0fc54 100644 --- a/webbpsf/trending.py +++ b/webbpsf/trending.py @@ -1,5 +1,4 @@ import calendar -import datetime import functools import os @@ -7,14 +6,14 @@ import astropy.io.fits as fits import astropy.time import astropy.units as u -from astroquery.mast import Observations import matplotlib import matplotlib.pyplot as plt -from matplotlib.backends.backend_pdf import PdfPages import numpy as np +import poppy import scipy.interpolate +from astroquery.mast import Observations +from matplotlib.backends.backend_pdf import PdfPages -import poppy import webbpsf @@ -399,7 +398,7 @@ def wfe_histogram_plot( ) if thresh: - axes[0].axhline(thresh, color='C2', label=f'OTE Correction threshold', linestyle='dashed') + axes[0].axhline(thresh, color='C2', label='OTE Correction threshold', linestyle='dashed') axes[0].tick_params(right=True, which='both', direction='in') @@ -751,7 +750,7 @@ def single_measurement_trending_plot( iax = axes[0, 3] show_opd_image((post_opd - opd) * nanmask, ax=iax, title=None, vmax=vmax, mask=mask, maskc3=mask_without_C3) - iax.set_title(f'Mirror Move Measured\nDelta WFE', fontsize=fontsize) + iax.set_title('Mirror Move Measured\nDelta WFE', fontsize=fontsize) else: for ax in axes[0, 1:4]: @@ -775,12 +774,12 @@ def single_measurement_trending_plot( # Panel 2-3: proposed correction iax = axes[1, 2] show_opd_image(fit, ax=iax, vmax=vmax, deltatime_hrs=deltatime_hrs, fontsize=fontsize) - iax.set_title(f'Controllable Modes\nin difference', fontsize=fontsize * 1.1) + iax.set_title('Controllable Modes\nin difference', fontsize=fontsize * 1.1) # Panel 2-4: iax = axes[1, 3] show_opd_image(delta_opd - fit, ax=iax, vmax=vmax, fontsize=fontsize) - iax.set_title(f'High order WFE\nin difference', fontsize=fontsize * 1.1) + iax.set_title('High order WFE\nin difference', fontsize=fontsize * 1.1) ####### Row 3 @@ -803,18 +802,18 @@ def single_measurement_trending_plot( correction -= np.nanmean(correction[correction_mask == 1]) show_opd_image(-correction, ax=iax, vmax=vmax, mask=correction_mask, fontsize=fontsize) - iax.set_title(f'Controllable modes\nfrom WSS proposed correction', fontsize=fontsize * 1.1) + iax.set_title('Controllable modes\nfrom WSS proposed correction', fontsize=fontsize * 1.1) # show_opd_image(fit2, ax=axes[2,3], vmax=vmax, mask=mask, fontsize=fontsize) else: show_opd_image(fit2, ax=iax, vmax=vmax, mask=mask, fontsize=fontsize) - iax.set_title(f'Controllable Modes\nin difference', fontsize=fontsize * 1.1) + iax.set_title('Controllable Modes\nin difference', fontsize=fontsize * 1.1) # Panel 3-4: iax = axes[2, 3] show_opd_image(delta_opd2 - fit2, ax=iax, vmax=vmax, maskc3=mask_without_C3, fontsize=fontsize) - iax.set_title(f'High order WFE\nin difference', fontsize=fontsize * 1.1) + iax.set_title('High order WFE\nin difference', fontsize=fontsize * 1.1) cax = fig.add_axes([0.91, 0.41, 0.01, 0.4]) @@ -2085,7 +2084,7 @@ def nrc_ta_image_comparison(visitid, verbose=False, show_centroids=False): nrc = webbpsf.setup_sim_to_match_file(hdul, verbose=False) opdname = nrc.pupilopd[0].header['CORR_ID'] + '-NRCA3_FP1-1.fits' if verbose: - print(f'Calculating PSF to match that TA image...') + print('Calculating PSF to match that TA image...') psf = nrc.calc_psf(fov_pixels=im_obs.shape[0]) # Align and Shift: diff --git a/webbpsf/utils.py b/webbpsf/utils.py index 2dfee5d8..8dd15188 100644 --- a/webbpsf/utils.py +++ b/webbpsf/utils.py @@ -1,13 +1,15 @@ -from collections import OrderedDict -import os, sys +import logging +import os +import sys import warnings +from collections import OrderedDict + import astropy.io.fits as fits -from astropy.nddata import NDData -import numpy as np +import astropy.units as u import matplotlib.pyplot as plt +import numpy as np import scipy -import astropy.units as u -import logging +from astropy.nddata import NDData _log = logging.getLogger('webbpsf') @@ -309,9 +311,9 @@ def system_diagnostic(): # There is probably a more clever way to do the following via introspection? import platform - import os - import poppy + import numpy + import poppy import scipy try: @@ -491,9 +493,10 @@ def measure_strehl(HDUlist_or_filename=None, ext=0, slice=0, center=None, displa """ - from .webbpsf_core import instrument from poppy import display_psf + from .webbpsf_core import instrument + if isinstance(HDUlist_or_filename, str): HDUlist = fits.open(HDUlist_or_filename) elif isinstance(HDUlist_or_filename, fits.HDUList): @@ -790,7 +793,6 @@ def _run_benchmark(timer, iterations=1): def benchmark_imaging(iterations=1, nlambda=1, add_distortion=True): """Performance benchmark function for standard imaging""" - import poppy import timeit timer = timeit.Timer( @@ -808,7 +810,6 @@ def benchmark_imaging(iterations=1, nlambda=1, add_distortion=True): def benchmark_nircam_coronagraphy(iterations=1, nlambda=1, add_distortion=True): """Performance benchmark function for standard imaging""" - import poppy import timeit timer = timeit.Timer( @@ -828,7 +829,6 @@ def benchmark_nircam_coronagraphy(iterations=1, nlambda=1, add_distortion=True): def benchmark_miri_coronagraphy(iterations=1, nlambda=1): """Performance benchmark function for standard imaging""" - import poppy import timeit timer = timeit.Timer( diff --git a/webbpsf/webbpsf_core.py b/webbpsf/webbpsf_core.py index dae390a9..070f1910 100644 --- a/webbpsf/webbpsf_core.py +++ b/webbpsf/webbpsf_core.py @@ -19,33 +19,25 @@ Code by Marshall Perrin """ -import os -import glob -from collections import namedtuple, OrderedDict import functools -import numpy as np -import scipy.interpolate, scipy.ndimage +import glob +import os +from collections import OrderedDict, namedtuple import astropy -import astropy.io.fits as fits import astropy.io.ascii as ioascii +import astropy.io.fits as fits import astropy.units as units - +import numpy as np import poppy - import pysiaf +import scipy.interpolate +import scipy.ndimage -from . import conf -from . import utils -from . import optics -from . import DATA_VERSION_MIN -from . import detectors -from . import distortion -from . import gridded_library -from . import opds -from . import constants import webbpsf.mast_wss +from . import DATA_VERSION_MIN, constants, detectors, distortion, gridded_library, opds, optics, utils + try: from .version import version except ImportError: @@ -1507,7 +1499,8 @@ def get_wfe(self, kind='si', wavelength=2e-6, plot=False): raise NotImplementedError(f'Not a known kind of WFE: {kind}') if plot: - import matplotlib, matplotlib.pyplot as plt + import matplotlib + import matplotlib.pyplot as plt plt.imshow(opd, vmin=-5e-7, vmax=5e-7, cmap=matplotlib.cm.RdBu_r, origin='lower') plt.title(kind + ' WFE') @@ -1598,7 +1591,8 @@ def load_wss_opd(self, filename, output_path=None, backout_si_wfe=True, verbose= # "[nm] RMS Observatory WFE (i.e. OTE+SI) at sensing field pt") if plot: - import matplotlib, matplotlib.pyplot as plt + import matplotlib + import matplotlib.pyplot as plt fig, axes = plt.subplots(figsize=(16, 9), ncols=3, nrows=2) vm = 2e-7 @@ -1711,7 +1705,7 @@ def load_wss_opd(self, filename, output_path=None, backout_si_wfe=True, verbose= ) opdhdu_at_si_fp[0].header.add_history(f' Selected instrument field point is at V2,V3 = {v2v3}.') opdhdu_at_si_fp[0].header.add_history( - f'Saving out total estimated OTE WFE (global+field dep) at that field point.' + 'Saving out total estimated OTE WFE (global+field dep) at that field point.' ) opdhdu_at_si_fp[0].header['INSTRUME'] = self.name opdhdu_at_si_fp[0].header['DETECTOR'] = self.detector @@ -2873,7 +2867,7 @@ def _addAdditionalOptics(self, optsys, oversample=2): See Table 3-6 of NIRSpec Ops Concept Document, ESA-JWST-TN-0297 / JWST-OPS-003212 """ - from .optics import NIRSpec_three_MSA_shutters, NIRSpec_MSA_open_grid + from .optics import NIRSpec_MSA_open_grid, NIRSpec_three_MSA_shutters trySAM = False # semi-analytic method never applicable here. SAM_box_size = None @@ -2986,7 +2980,7 @@ def _addAdditionalOptics(self, optsys, oversample=2): are present, so we might as well still provide the ability to simulate 'em. """ - from .optics import NIRISS_GR700XD_Grism, NIRISS_CLEARP + from .optics import NIRISS_CLEARP, NIRISS_GR700XD_Grism if self.image_mask == 'CORON058': radius = 0.58 / 2