### Setup simulation to match file Source: https://stpsf.readthedocs.io/en/latest/jwst_matching_psfs_to_data.html Execute the setup function to configure the instrument object and load the closest-in-time wavefront sensing visit data. ```python inst = stpsf.setup_sim_to_match_file(filename) ``` -------------------------------- ### STPSF simulation setup output Source: https://stpsf.readthedocs.io/en/latest/jwst_psf_subtraction.html Example console output showing the MAST OPD query and instrument configuration details. ```text Setting up sim to match jw02725-o484_t097_nircam_clear-f356w-nrcalong_wfscmb-04.fits iterating query, tdelta=3.0 MAST OPD query around UTC: 2022-11-29T17:26:06.893 MJD: 59912.72646866898 OPD immediately preceding the given datetime: URI: mast:JWST/product/R2022112903-NRCA3_FP1-1.fits Date (MJD): 59912.7265 Delta time: -0.0000 days OPD immediately following the given datetime: URI: mast:JWST/product/R2022120203-NRCA3_FP1-1.fits Date (MJD): 59915.1683 Delta time: 2.4418 days User requested choosing OPD time closest in time to 2022-11-29T17:26:06.893, which is R2022112903-NRCA3_FP1-1.fits, delta time -0.000 days Importing and format-converting OPD from /Users/mperrin/software/stpsf-data/MAST_JWST_WSS_OPDs/R2022112903-NRCA3_FP1-1.fits Backing out SI WFE and OTE field dependence at the WF sensing field point Configured simulation instrument for: Instrument: NIRCam Filter: F356W Detector: NRCA5 Apername: NRCA5_FULL Det. Pos.: (1024, 1024) Image plane mask: None Pupil plane mask: None ``` -------------------------------- ### WebbPSF logging configuration output Source: https://stpsf.readthedocs.io/en/latest/field_dependence/multifield_documentation.html Example output showing the logging configuration for WebbPSF. ```text WebbPSF log messages of level ERROR and above will be shown. WebbPSF log outputs will be directed to the screen. ``` -------------------------------- ### Instrument Initialization and Property Setup Source: https://stpsf.readthedocs.io/en/latest/_modules/stpsf/stpsf_core.html Initializes core instrument attributes including filters, masks, and detector configurations. ```python self.pupil_radius = None # Set in subclass for JWST or Roman self.options = {} # dict for storing other arbitrary options. # filter_list available filter names in order by wavelength for public api # _filters a dict of named tuples with name, filename, & default_nlambda # with the filter name as the key self.filter_list, self._filters = self._get_filters() # choose a default filter, in case the user doesn't specify one self.filter = self.filter_list[0] self._rotation = None self._image_mask = None self.image_mask_list = [] 'List of available image_masks' self._pupil_mask = None self.pupil_mask_list = [] 'List of available pupil_masks' self.pixelscale = pixelscale 'Detector pixel scale, in arcsec/pixel' self._spectra_cache = {} # for caching synphot results. # n.b.STInstrument subclasses must set these self._detectors = {} self._detector = None self._detector_npixels = 2048 ``` -------------------------------- ### Setup STPSF environment Source: https://stpsf.readthedocs.io/en/latest/_sources/field_dependence/multifield_documentation.ipynb.txt Initializes the environment for STPSF by configuring matplotlib and importing necessary modules. ```python %matplotlib inline matplotlib.rcParams['image.origin'] = 'lower' import stpsf import astropy.units as u stpsf.setup_logging() ``` -------------------------------- ### setup_logging Source: https://stpsf.readthedocs.io/en/latest/api_reference.html Allows selection of logging detail and output locations (screen and/or file). ```APIDOC ## setup_logging ### Description Allows selection of logging detail and output locations (screen and/or file). ### Method Function ### Signature `setup_logging([level, filename])` ### Parameters - `level` (optional) - Logging level. - `filename` (optional) - Output filename for log file. ### Returns Configures logging settings. ``` -------------------------------- ### Install STPSF with pip Source: https://stpsf.readthedocs.io/en/latest/_sources/installation.rst.txt Standard installation command for STPSF and its dependencies from the Python Package Index. ```bash $ pip install --upgrade stpsf [... progress report ...] Successfully installed stpsf ``` -------------------------------- ### Set up NIRCam instrument instance Source: https://stpsf.readthedocs.io/en/latest/jwst_measured_opds.html Instantiates a NIRCam instrument, sets the filter to F200W, selects detector NRCB2, and sets the detector position to (1024, 1024). This is the initial setup required before loading wavefront OPDs. ```python nrc = stpsf.NIRCam() nrc.filter='F200W' nrc.detector = 'NRCB2' nrc.detector_position = (1024,1024) ``` -------------------------------- ### Import STPSF Source: https://stpsf.readthedocs.io/en/latest/webbpsf_to_stpsf.html Preferred transition method: import STPSF and replace all WebbPSF calls with STPSF. Requires installing STPSF, downloading stpsf-data-LATEST.tar.gz, and setting the STPSF_PATH environment variable. ```python import stpsf ``` -------------------------------- ### Define time range for WFE retrieval Source: https://stpsf.readthedocs.io/en/latest/jwst_iec_wfe.html Defines a time range using `astropy.time.Time` and `numpy.arange` with `astropy.units.minute` to create an array of 60 times starting from the given start time. ```python tstart = astropy.time.Time('2022-07-10T16:00:00') trange = tstart + np.arange(60) * astropy.units.minute ``` -------------------------------- ### Initialize WFI and generate PSF grid Source: https://stpsf.readthedocs.io/en/latest/_modules/stpsf/stpsf_core.html Example of initializing the WFI instrument, setting filter and detector properties, and generating a PSF grid. ```python wfi = stpsf.WFI() wfi.filter = "Z087" wfi.detector = "WFI02" grid = wfi.psf_grid(all_detectors=False, oversample=5, fov_pixels=101) ``` -------------------------------- ### Download example NIRCam observation Source: https://stpsf.readthedocs.io/en/latest/jwst_psf_subtraction.html Downloads the example F356W NIRCam observation from the Wavefront Sensing Maintenance program (PID 2725, obs 484). The file is cached locally. ```python file = 'jw02725-o484_t097_nircam_clear-f356w-nrcalong_wfscmb-04.fits' mast_retrieve_files(file) ``` -------------------------------- ### Install STPSF and POPPY development versions via pip Source: https://stpsf.readthedocs.io/en/latest/_sources/installation.rst.txt Use this command to install the current development versions of STPSF and POPPY directly from their respective GitHub repositories. This creates local clones in a ./src directory. ```bash $ pip install -e git+https://github.com/spacetelescope/poppy.git#egg=poppy \ -e git+https://github.com/spacetelescope/stpsf.git#egg=stpsf ``` -------------------------------- ### stpsf.setup_logging(level='INFO', filename=None) Source: https://stpsf.readthedocs.io/en/latest/api/stpsf.setup_logging.html Configures logging for stpsf and poppy, allowing selection of log detail level and output to screen and/or file. This is a convenience wrapper to Python's built-in logging package. ```APIDOC ## stpsf.setup_logging(level='INFO', filename=None) ### Description Allows selection of logging detail and output locations (screen and/or file). This is a convenience wrapper to Python's built-in logging package, as used by `stpsf` and `poppy`. By default, this sets up log messages to be written to the screen, but the user can also request logging to a file. ### Method Function call ### Endpoint stpsf.setup_logging(level='INFO', filename=None) ### Parameters - **level** (str) - Optional - Name of log output to show. Defaults to 'INFO', set to 'DEBUG' for more extensive messages, or to 'WARN' or 'ERROR' for fewer. - **filename** (str) - Optional - Filename to write the log output to. If not set, output will just be displayed on screen. (Default: None) ### Request Example python >>> stpsf.setup_logging(filename='stpsflog.txt') ### Response No return value. The function configures logging settings. ### Response Example No response body. The function configures logging settings. ### Notes - Editing the STPSF config file to set `autoconfigure_logging = True` (and any of the logging settings you wish to persist) instructs STPSF to apply your settings on import. (This is not done by default in case you have configured `logging` yourself and don't wish to overwrite your configuration.) - For more advanced log handling, see the Python logging module's own documentation. ### Examples python >>> stpsf.setup_logging(filename='stpsflog.txt') This will save all log messages to 'stpsflog.txt' in the current directory. If you later start another copy of stpsf in a different directory, that session will also write to 'stpsflog.txt' in _that_ directory. Alternatively you can specify a fully qualified absolute path to save all your logs to one specific file. python >>> stpsf.setup_logging(level='WARN') This will show only WARNING or ERROR messages on screen, and not save any logs to files at all (since the filename argument is None). ``` -------------------------------- ### NIRCam Coronagraph Shift Source: https://stpsf.readthedocs.io/en/latest/_modules/stpsf/stpsf_core.html Example of setting coronagraph shifts for NIRCam simulations. ```python nc.options['coron_shift_x'] = 3 # Shifts mask 3" to right, equivalent to source 3" to left. ``` -------------------------------- ### setup_logging function Source: https://stpsf.readthedocs.io/en/latest/_modules/stpsf/utils.html Convenience wrapper to Python's logging package for stpsf and poppy. Configures screen and optional file logging. Default level is 'INFO'; set to 'DEBUG', 'WARN', or 'ERROR' for different verbosity. If filename is None, no file logging is set up. ```python [docs] def setup_logging(level='INFO', filename=None): """Allows selection of logging detail and output locations (screen and/or file) This is a convenience wrapper to Python's built-in logging package, as used by `stpsf` and `poppy`. By default, this sets up log messages to be written to the screen, but the user can also request logging to a file. Editing the STPSF config file to set `autoconfigure_logging = True` (and any of the logging settings you wish to persist) instructs STPSF to apply your settings on import. (This is not done by default in case you have configured `logging` yourself and don't wish to overwrite your configuration.) For more advanced log handling, see the Python logging module's own documentation. Parameters ---------- level : str Name of log output to show. Defaults to 'INFO', set to 'DEBUG' for more extensive messages, or to 'WARN' or 'ERROR' for fewer. filename : str, optional Filename to write the log output to. If not set, output will just be displayed on screen. (Default: None) Examples -------- >>> stpsf.setup_logging(filename='stpsflog.txt') This will save all log messages to 'stpsflog.txt' in the current directory. If you later start another copy of stpsf in a different directory, that session will also write to 'stpsflog.txt' in *that* directory. Alternatively you can specify a fully qualified absolute path to save all your logs to one specific file. >>> stpsf.setup_logging(level='WARN') This will show only WARNING or ERROR messages on screen, and not save any logs to files at all (since the filename argument is None) """ ``` -------------------------------- ### specFromSpectralType Source: https://stpsf.readthedocs.io/en/latest/api_reference.html Gets synphot Spectrum object from a user-friendly spectral type string. ```APIDOC ## specFromSpectralType ### Description Get synphot Spectrum object from a user-friendly spectral type string. ### Method Function ### Signature `specFromSpectralType(sptype[, return_list, ...])` ### Parameters - `sptype` (string) - Spectral type string. - `return_list` (optional) - Whether to return a list. - Additional parameters as supported by the function. ### Returns Returns a synphot Spectrum object (or list of objects). ``` -------------------------------- ### STPSF Module Initialization and Configuration Source: https://stpsf.readthedocs.io/en/latest/_modules/stpsf.html This snippet contains the package-level setup, including the minimum Python version check, the definition of the Conf configuration class, and the import of core instrument classes and utility functions. ```python # Licensed under a 3-clause BSD style license - see LICENSE.rst """ STPSF: Simulated Point Spread Functions for the James Webb Space Telescope ---------------------------------------------------------------------------- STPSF produces simulated PSFs for the James Webb Space Telescope, NASA's next flagship infrared space telescope. STPSF can simulate images for any of the four science instruments plus the fine guidance sensor, including both direct imaging and coronagraphic modes. Developed by Marshall Perrin and collaborators at STScI, 2010-2018. Documentation can be found online at https://stpsf.readthedocs.io/ """ import sys from astropy import config as _config try: from .version import __version__ except ImportError: __version__ = "" __minimum_python_version__ = "3.10" [docs] class UnsupportedPythonError(Exception): pass if sys.version_info < tuple( (int(val) for val in __minimum_python_version__.split(".")) ): raise UnsupportedPythonError( "stpsf does not support Python < {}".format(__minimum_python_version__) ) # This tuple gives the *minimum* version of the STPSF data package # required. If changes to the code and data mean STPSF won't work # properly with an old data package, increment this version number. # (It's checked against $STPSF_DATA/version.txt) DATA_VERSION_MIN = (2, 1, 0) [docs] class Conf(_config.ConfigNamespace): """ Configuration parameters for `stpsf`. """ default_oversampling = _config.ConfigItem( 4, "Default " + "oversampling factor: number of times more finely sampled than " + "an integer pixel for the grid spacing in the PSF calculation.", ) default_output_mode = _config.ConfigItem( "both", "Should output include the oversampled PSF, a copy rebinned onto the integer detector spacing, or both?\ Options: 'oversampled','detector','both' ", ) default_fov_arcsec = _config.ConfigItem( 5.0, "Default field of view size, in arcseconds per side of the square " ) # Should be package settings: STPSF_PATH = _config.ConfigItem( "from_environment_variable", "Directory path to data files required for STPSF calculations, such as OPDs and filter transmissions.\ This will be overridden by the environment variable $STPSF_PATH, if present.", ) autoconfigure_logging = _config.ConfigItem( False, "Should STPSF configure logging for itself and POPPY? This adds handlers that report " "calculation progress and information", ) logging_level = _config.ConfigItem( ["INFO", "DEBUG", "WARN", "ERROR", "CRITICAL", "NONE"], # (the default value is the first item in the options list) "Desired logging level for STPSF optical calculations.", ) logging_filename = _config.ConfigItem( "none", "Desired filename to save log messages to." ) logging_format_screen = _config.ConfigItem( "[%(name)7s] %(message)s", "Format for lines logged to the screen." ) logging_format_file = _config.ConfigItem( "%(asctime)s [%(name)s:%(levelname)s] %(filename)s:%(lineno)d: %(message)s", "Format for lines logged to a file.", ) conf = Conf() from . import utils # noqa - must go after config from . import trending # noqa - must go after config from .utils import setup_logging, restart_logging, system_diagnostic, measure_strehl # noqa - must go after config from poppy import ( # noqa display_psf, display_psf_difference, display_ee, measure_ee, display_profiles, radial_profile, measure_radial, measure_fwhm, measure_sharpness, measure_centroid, specFromSpectralType, fwcentroid, ) from .stpsf_core import ( # noqa instrument, SpaceTelescopeInstrument, JWInstrument, NIRCam, NIRISS, NIRSpec, MIRI, FGS, ) from .opds import enable_adjustable_ote # noqa from .roman import WFI # noqa from .match_data import setup_sim_to_match_file # noqa ``` -------------------------------- ### Colorbar output from OPD plot Source: https://stpsf.readthedocs.io/en/latest/field_dependence/multifield_documentation.html Output from the colorbar command in the OPD plotting example. ```text ``` -------------------------------- ### Show only warnings and errors with stpsf.setup_logging Source: https://stpsf.readthedocs.io/en/latest/api/stpsf.setup_logging.html Calls stpsf.setup_logging with level='WARN' to display only WARNING or ERROR messages on screen. Since filename is None, no logs are saved to files. ```python >>> stpsf.setup_logging(level='WARN') ``` -------------------------------- ### List detectors and select a different detector Source: https://stpsf.readthedocs.io/en/latest/_sources/roman.rst.txt Shows how to list all available detectors and change the detector by assigning a new name to the 'detector' attribute. The example selects 'WFI03'. ```python >>> wfi.detector_list ['WFI01', 'WFI02', 'WFI03', 'WFI04', 'WFI05', 'WFI06', 'WFI07', 'WFI08', 'WFI09', 'WFI10', 'WFI11', 'WFI12', 'WFI13', 'WFI14', 'WFI15', 'WFI16', 'WFI17', 'WFI18'] >>> wfi.detector = 'WFI03' ``` -------------------------------- ### Configure Image Array with setup_image_array Source: https://stpsf.readthedocs.io/en/latest/_modules/stpsf/opds.html Applies tilts to telescope segments to arrange them in an image array configuration. Requires an OTE_Linear_Model_WSS instance. ```python def setup_image_array( ote, radius=1, size=None, inverted=False, reset=False, verbose=False, acfs_only=False, guide_seg=None, guide_radius=10.0 ): """ Apply tilts to put the segments in an image array configuration. Parameters ---------- ote : OTE_Linear_Model_WSS instance The telescope model to be adjusted. This will be modified by this function. radius : float Desired radius to B segments, in arcseconds as seen on the focal plane. size : string, optional Another way of specifying the image array size. Use one of 'small', 'medium', or 'large' for the standard sizes used in OTE commissioning. Or 'cmimf' for the size used in Coarse MIMF, which is in between small and medium. guide_seg : string relevant mostly for coarse MIMF and image stacking. Kick out a segment to guide? The segment will be offset during coarse MIMF to its position desired during GA2, i.e. to its position in the large array. acfs_only : bool Only tilt the ACFs (applicable to JSC OTIS only) inverted : bool Invert the array reset : bool Discard any previously applied mirror moves if true verbose : bool Print more text about moves. """ assert isinstance(ote, OTE_Linear_Model_WSS), 'First argument has to be a linear optical model instance.' nircam_pixelscale = 0.0311 standard_sizes = { 'small': 80 * nircam_pixelscale, 'cmimf': 120 * nircam_pixelscale, 'medium': 300 * nircam_pixelscale, 'large': 812 * nircam_pixelscale, } if size is not None: radius = standard_sizes[size] # how many microradians of segment tilt per arcsecond of PSF motion? # note factor of 2 since reflection arcsec_urad = (1 * u.arcsec).to(u.urad).value / 2 if reset: ote.reset() # Image Arrays used in flight size = radius * -1 if inverted else radius for i in range(1, 7): ote.move_seg_local('A' + str(i), xtilt=size * arcsec_urad / 2, delay_update=True) ote.move_seg_local('B' + str(i), xtilt=-size * arcsec_urad, delay_update=True) ote.move_seg_local('C' + str(i), ytilt=size * np.sqrt(3) / 2 * arcsec_urad, delay_update=True) if guide_seg is not None: # Undo the regular tilt for this segment, and then move it to # the side. if 'A' in guide_seg: xtilt = (-size + standard_sizes['large']) / 2 * arcsec_urad ytilt = 0 elif 'B' in guide_seg: xtilt = -size * arcsec_urad ytilt = guide_radius * arcsec_urad else: ytilt = (size * np.sqrt(3) / 2 + guide_radius) * arcsec_urad xtilt = 0 ote.move_seg_local(guide_seg, xtilt=xtilt, ytilt=ytilt, delay_update=True) ote.update_opd(verbose=verbose) ``` -------------------------------- ### Initialize NIRCam pupil Source: https://stpsf.readthedocs.io/en/latest/_modules/stpsf/stpsf_core.html Example of initializing a NIRCam object and setting a single segment pupil. ```python nc = stpsf.NIRCam() nc.pupil = stpsf.one_segment_pupil('B1') ``` -------------------------------- ### NIRCam Coronagraph Bar Offset Source: https://stpsf.readthedocs.io/en/latest/_modules/stpsf/stpsf_core.html Example of setting a bar offset for NIRCam coronagraph simulations. ```python nc.image_mask = 'MASKLWB' nc.options['bar_offset'] = 3 # 3 arcseconds towards the right (narrow end on module A) ```