Giter VIP home page Giter VIP logo

webbpsf's Introduction

WebbPSF: Simulated Point Spread Functions for the James Webb and Nancy Grace Roman Space Telescopes

image

Badge showing current released PyPI version

Github Actions CI Status

image

image

WebbPSF produces simulated PSFs for the James Webb Space Telescope, NASA's flagship infrared space telescope. WebbPSF can simulate images for any of the four science instruments plus the fine guidance sensor, including both direct imaging and coronagraphic modes.

WebbPSF also supports simulating PSFs for the upcoming Nancy Grace Roman Space Telescope (formerly WFIRST), including its Wide Field Instrument and a preliminary version of the Coronagraph Instrument.

Developed by Marshall Perrin, Joseph Long, Neil Zimmerman, Robel Geda, Shannon Osborne, Marcio Melendez Hernandez, Lauren Chambers, Keira Brooks, Charles-Phillipe Lajoie, Jarron Leisenring, Alden Jurling, and collaborators, 2010-2020.

Documentation can be found online at https://webbpsf.readthedocs.io

WebbPSF requires input data for its simulations, including optical path difference (OPD) maps, filter transmission curves, and coronagraph Lyot mask shapes. These data files are not included in this source distribution. Please see the documentation to download the required data files.

webbpsf's People

Contributors

aldenjurling avatar astrofrog avatar bmorris3 avatar bradleysappington avatar braingram avatar cdeil avatar dependabot[bot] avatar embray avatar eteq avatar jarronl avatar joseph-long avatar josephoenix avatar jsoref avatar kbarbary avatar kstlaurent avatar kulpster85 avatar larrybradley avatar mdboom avatar mperrin avatar mwcraig avatar naincykumariknoldus avatar neilzim avatar obi-wan76 avatar ojustino avatar pllim avatar robelgeda avatar shanosborne avatar skyhawk172 avatar wkerzendorf avatar zacharyburnett avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

webbpsf's Issues

NIRISS should toggle pupil between CLEAR and CLEARP automatically

Issue by mperrin
Tuesday Feb 17, 2015 at 05:06 GMT
Originally opened as mperrin/webbpsf#48


In fact the class doc string says it does but it doesn't look like this was implemented.

Filters F277W and longer wavelength in imaging mode must use the CLEARP pupil (or NRM or GR700XD) See http://www.stsci.edu/jwst/instruments/niriss/docarchive/NIRISS-pocket-guide.pdf

Implementation should be in _validateConfig similar to NIRCam pixel scale swap.

Failing test: test_miri_fqpm

Issue by josePhoenix
Tuesday Dec 09, 2014 at 19:04 GMT
Originally opened as mperrin/webbpsf#29


This test is failing with TclError: no display name and no $DISPLAY environment variable when run in a headless environment. It needs to be updated not to initialize the matplotlib GUI functionality (should just be display=False).

Roll-your-own source spectra don't work as described

Issue by josePhoenix
Tuesday Nov 25, 2014 at 22:16 GMT
Originally opened as mperrin/webbpsf#28


The docs say source spectra can be provided a variety of ways, but it looks like options 2 and 3 are not currently functional. We should update the docs and/or POPPY.

The following are valid sources:

  1. A pysynphot.Spectrum object. This is the best option, providing maximum ease and accuracy, but requires the user to have pysynphot installed. In this case, the Spectrum object is combined with a pysynphot.ObsBandpass for the selected instrument and filter to derive the effective stimulus in detected photoelectrons versus wavelength. This is binned to the number of wavelengths set by the nlambda parameter.

  2. A dictionary with elements source["wavelengths"] and source["weights"] giving the wavelengths in meters and the relative weights for each. These should be numpy arrays or lists. In this case, the wavelengths and weights are used exactly as provided, without applying the instrumental filter profile.

    src = {'wavelengths': [2.0e-6, 2.1e-6, 2.2e-6], 'weights': [0.3, 0.5, 0.2]}
    nc.calcPSF(source=src, outfile='psf_for_src.fits')

  3. A tuple or list containing the numpy arrays (wavelength, weights) instead.

Reported by @kvangorkom.

To reproduce:

Run this code and note the output. Specifically, the part that says Pysynphot unavailable (or invalid source supplied)! Assuming flat # of counts versus wavelength.

It looks like poppy/instrument.py line 611 (_getWeights) is the section of interest in poppy.

import webbpsf
miri = webbpsf.MIRI()
test_src = {'wavelengths':[2.0e-6, 2.1e-6, 2.2e-6], 'weights': [0.3, 0.5, 0.2]}
miri.calcPSF(source=test_src)

Output:

webbpsf : INFO Setting up PSF calculation for MIRI
webbpsf : INFO PSF calc using fov_arcsec = 12.000000, oversample = 4, nlambda = 9
poppy : WARNING Pysynphot unavailable (or invalid source supplied)! Assuming flat # of counts versus wavelength.
poppy : WARNING CAUTION: no WAVEUNIT keyword found in filter file /Users/kgorkom/webbpsf-data//MIRI//filters/F560W_throughput.fits. Assuming = Angstroms by default
poppy : WARNING CAUTION: Just interpolating rather than integrating filter profile, over 9 steps
webbpsf : INFO Creating optical system model:
poppy : INFO Initialized OpticalSystem: JWST+MIRI
poppy : INFO JWST Pupil: Loaded amplitude transmission from /Users/kgorkom/webbpsf-data/pupil_RevV.fits
poppy : INFO JWST Pupil: Loaded OPD from /Users/kgorkom/webbpsf-data//MIRI/OPD/OPD_RevV_miri_421.fits
poppy : INFO The supplied pupil OPD is a datacube but no slice was specified. Defaulting to use slice 0.
poppy : INFO Rotated optic by 4.561000 degrees counter clockwise.
poppy : INFO Added pupil plane: JWST Pupil
poppy : INFO Added detector: MIRI detector, with pixelscale=0.110000 arcsec/pixel and oversampling=4
poppy : INFO Calculating PSF with 9 wavelengths
poppy : INFO Propagating wavelength = 5.04e-06 meters with weight=0.06
poppy : INFO Propagating wavelength = 5.1825e-06 meters with weight=0.11
poppy : INFO Propagating wavelength = 5.325e-06 meters with weight=0.10
poppy : INFO Propagating wavelength = 5.4675e-06 meters with weight=0.12
poppy : INFO Propagating wavelength = 5.61e-06 meters with weight=0.13
poppy : INFO Propagating wavelength = 5.7525e-06 meters with weight=0.13
poppy : INFO Propagating wavelength = 5.895e-06 meters with weight=0.14
poppy : INFO Propagating wavelength = 6.0375e-06 meters with weight=0.14
poppy : INFO Propagating wavelength = 6.18e-06 meters with weight=0.06
poppy : INFO Calculation completed in 5.627 s
poppy : INFO PSF Calculation completed.
poppy : INFO Downsampling to detector pixel scale. 

Pretty up the last plot in the example notebook

Issue by josePhoenix
Monday Oct 27, 2014 at 22:00 GMT
Originally opened as mperrin/webbpsf#22


Mainly, I wanted to make the last plot in the notebook prettier. I also made the pylab import explicit, and set the origin of image plots to be lower so the notebook will look the more or less the same if/when users run it on their own machines.

(It appears that axis tick labels don't change with the image.origin setting, leading to ambiguous plots. We should perhaps change that in poppy.)


josePhoenix included the following code: https://github.com/mperrin/webbpsf/pull/22/commits

PyFFTW3 vs pyFFTW

Issue by mperrin
Wednesday Apr 24, 2013 at 21:13 GMT
Originally opened as mperrin/webbpsf#10


Argh, there are two packaged for FFTW access in Python. Should evaluate & compare.

See: astropy/astropy#660
for some discussion in astropy.

TBD how best to work with planning to support stored wisdom for large 2D FFTs to minimize replanning.

Drop Python 2.6 compatibility?

Issue by josePhoenix
Thursday Oct 09, 2014 at 20:00 GMT
Originally opened as mperrin/webbpsf#21


It looks like the promise of Python 2.6 compatibility is no longer true for WebbPSF. I'm fine with dropping it, and moving towards a bilingual codebase with Python 3 support (i.e. #2 ).

I notice plhstins1 and the witservs have older Python installs, so it may be necessary to maintain compatibility. If so, we should see if we can configure Travis-CI to test on Python 2.6. Or, at least, write up some instructions for setting up a Python 2.6 testing environment to make sure it's all still working.

Refresh documentation

Issue by mperrin
Monday Jun 25, 2012 at 05:57 GMT
Originally opened as mperrin/webbpsf#4


Documentation issues checklist

  • Remove commented text from webbpsf.rst (and elsewhere)
  • Mention :py:attr:JWInstrument.options where appropriate in webbpsf.rst #24
  • Update instrument subclassing example (refers to webbpsf.TFI, ThinLens without radius)
  • Move poppy.rst into POPPY (if there's information there that isn't already in the POPPY docs). Should leave just enough discussion in webbpsf docs to explain at a high level what POPPY is and how it is used in WebbPSF, just so that WebbPSF users can have some technical sense of how it works under the hood without having to jump to the full POPPY documentation.
  • Change the module index to link directly to the webbpsf module page
  • Remove all mention of Python 2.6.x support #27
  • Explain (or explain in POPPY docs and link to) how to set use_multiprocessing #23
  • Set up intersphinx for references to POPPY
  • Link to poppy.Instrument options attribute docs from JWInstrument (depends on intersphinx?)
  • Add documentation for image jitter options to WebbPSF docs.
  • Add documentation for package level configuration settings
  • ttk interface screenshots look worse than the ttk interface actually does these days... time to update them
  • Figure out why some :py:meth:'foo' style links (with backticks) won't resolve
  • anything to improve for logging functionality docs?
  • how to output intermediate step images

New SIAFs for webbpsf-data package

Issue by josePhoenix
Thursday Jan 15, 2015 at 19:42 GMT
Originally opened as mperrin/webbpsf#34


Upon investigating the current public SIAFs, it appears the SIAF parsing code in jwxml.py now expects a slightly different format. As far as I know, WebbPSF doesn't use SIAFs in its calculations (yet!) but we should update them anyway. (That way when field dependence support lands, it'll require a code update but not [necessarily] a data update.)

Update the test suite

Issue by mperrin
Monday Jun 25, 2012 at 05:52 GMT
Originally opened as mperrin/webbpsf#1


Test suite is completely broken following repackaging. Set up to run properly; investigate using some continuous validation tool(s).

option in GUI for monochromatic calculations

Issue by mperrin
Thursday Jan 24, 2013 at 20:43 GMT
Originally opened as mperrin/webbpsf#8


There should be some easy way to do a monochromatic calculation in the GUI.

Implementation idea: on the options panel, have a toggle between monochromatic and broadband. If monochromatic, repurpose and relabel the # of wavelengths box in the GUI.

parity of forward & inverse MFT transforms

Issue by mperrin
Thursday Jan 15, 2015 at 21:42 GMT
Originally opened as mperrin/webbpsf#35


Begin forwarded message:

From: Anand Sivaramakrishnan [email protected]
Subject: troubles with parity of forward & inverse mDFT transforms...
Date: January 15, 2015 at 2:42:48 PM EST

Hi Joseph & Marshall

I use matrixDFT from WebbPSF as a standalone (to try to unify my code with WebbPSF utilities), and I'm having some trouble with coordinate flips when transforming forwards, then back.

I start with a psf in this example, transform it forwards to visibilities, then I try to transform it backwards as well as forwards - but get a flipped PSF both times. Running "matrixDFT_test.py" in the attached tar file will do these things, and give you two convenient ds9 commands to cut'n'paste to see the results.

This is a bit worrying, as matrixDFT is at the core of many things I do.

I also include matrixDFT.py copied from WebbPSF, with a print statement to show that I'm actually using this file from the *_test.py driver.

Any comments or suggestions would be great! If I should be using a different 'entry point' into the dft (such as SFT) please do let me know.

(I don't see any straightforward way to attach the file attachment to a github issue, but we have it in our inboxes)

Fix issue with ElementTree when lxml is not available

Issue by embray
Friday Dec 13, 2013 at 15:26 GMT
Originally opened as mperrin/webbpsf#13


I noticed this trying to get the webbpsfgui working on my Windows machine, where I don't have lxml installed. So it tries falling back to using Python's built-in xml.etree.cElementTree. However there are several places that are using lxml.etree.Element.iterchildren which is not supported in xml.etree so we have to provide an approximate replacement for it.

Once I got this going I was able to get the GUI to at least launch--not sure if there other issues but at least it runs.


embray included the following code: https://github.com/mperrin/webbpsf/pull/13/commits

Revalidate multiprocessing; optimize

Issue by mperrin
Monday Jun 25, 2012 at 05:55 GMT
Originally opened as mperrin/webbpsf#3


Some of the multi-CPU options have not been tested extensively in a while. Needs to be revalidated, and the defaults possible improved. Overall an analysis of performance optimization would be a good idea.

Allow unicode in filter names and other options

Issue by mperrin
Thursday Sep 25, 2014 at 22:58 GMT
Originally opened as mperrin/webbpsf#18


Bug report from Brian York:

A quick update.

On the one hand, issue diagnosed and worked around. It turns out 
that webbpsf can't deal with filter names in unicode, so by explicitly 
encoding filters as ASCII before passing them in I avoid crashes.

On the other hand, not handling unicode strings is probably something 
to fix if you should ever happen to have the time and resources.

Instrument options keyword argument doesn't validate option names

Issue by josePhoenix
Friday Nov 14, 2014 at 16:12 GMT
Originally opened as mperrin/webbpsf#24


Passing in instrument.options['foo'] doesn't validate that 'foo' is actually an option provided by WebbPSF/POPPY. Also, I am told we don't have clear documentation of all the available options.

Ideally, we'd validate that options provided by the user are really allowed. I need to look at where the options dict goes in its path through the code and see if that's feasible. This may not be an easy fix, but it's worth mentioning so we're at least aware users are getting tripped up by it.

Improve robustness of setup.py in the absence of certain dependencies

Issue by josePhoenix
Monday Oct 06, 2014 at 19:17 GMT
Originally opened as mperrin/webbpsf#19


Three changes to improve installation for users who may not already have all the dependencies installed:

  • a warning when NumPy is not already installed, because setuptools customizations don't play well with automatic dependency installation in NumPy's case (users are advised to install NumPy separately)
  • retrieve long description without importing webbpsf -- webbpsf/__init__.py imports from POPPY, which will not (necessarily) be available when setup.py is run. (imp and ast are standard library modules used to add this functionality)
  • adding numpy to install_requires and setup_requires. (Currently, one of the AstroPy helpers tries to import NumPy, so it's necessary in setup_requires according to the documented meaning of that option. It's possible this won't be needed if the AstroPy helpers are changed not to have a hard dependency on NumPy at this point in the install.)

josePhoenix included the following code: https://github.com/mperrin/webbpsf/pull/19/commits

ThinLens update to use explicit radius argument

Issue by josePhoenix
Thursday Nov 20, 2014 at 22:04 GMT
Originally opened as mperrin/webbpsf#25


Note: this remains a work-in-progress. WebbPSF master does not work for the commit I based this branch at, so there's something else going on.

Per mperrin/poppy#15, poppy.ThinLens now requires a radius argument to be given explicitly.

Some of the corresponding changes are:

In WebbPSF:

  • JWInstrument gains a pupil_radius attribute from the poppy.FITSOpticalElement generated in _getOpticalSystem
  • NIRCam thin lenses gain a radius keyword argument where they are instantiated
  • the ThinLens created when defocus_waves is supplied as an option gains a radius keyword argument

In POPPY:

  • addPupil, addRotation, addImage, addDetector all return the element they add (allowing API users to retain a reference to any FITSOpticalElements or others created transparently from their arguments)

josePhoenix included the following code: https://github.com/mperrin/webbpsf/pull/25/commits

Move WebbPSF docs to pythonhosted.org

Issue by josePhoenix
Thursday Oct 09, 2014 at 19:47 GMT
Originally opened as mperrin/webbpsf#20


I noticed that the current docs at http://www.stsci.edu/~mperrin/software/webbpsf/ are being served with incorrect encoding information. (Note the appearance of the paragraph links that appear when mousing over headings.)

While we could probably fix that with a .htaccess change, it might be worth moving the docs to a service like readthedocs.org (which AstroPy) uses. Then we can build docs from the development head automatically, as well as from the latest stable release.

Jitter functionality is incomplete

Issue by josePhoenix
Tuesday Jan 27, 2015 at 19:06 GMT
Originally opened as mperrin/webbpsf#40


In the documentation for WebbPSF.JWInstrument, we have

    jitter : string "gaussian" or None
        Type of jitter model to apply. Currently only convolution with a Gaussian kernel of specified
        width `jitter_sigma` is implemented. (default: None)
    jitter_sigma : float
        Width of the jitter kernel in arcseconds (default: 0.007 arcsec)

However, this test code shows no difference between a PSF with jitter enabled and a PSF with no jitter:

import webbpsf
nc = webbpsf.NIRCam()
nc.options['jitter'] = None
psf = nc.calcPSF(nlambda=3)

nc.options['jitter'] = 'gaussian'
psf_jitter = nc.calcPSF(nlambda=3)
webbpsf.display_PSF_difference(psf, psf_jitter)

I think this is because calcPSF is completely rewritten for JWInstrument and doesn't automatically get updates we make to poppy.Instrument. Refactoring that is something to tackle for v0.4.

WFIRST test case fails if no pysynphot is present

Issue by mperrin
Friday Feb 13, 2015 at 01:48 GMT
Originally opened as mperrin/webbpsf#46


The WFIRST imager class fails for the fallback code for the no-pysynphot case. Looks like something minor in terms of the filter file setup or header, hopefully easy to fix.

I'm going to make it xfail for now, in the hopes of almost having the tests actually pass on Travis.

webbpsf/tests/test_wfirst.py:3: test_wfirstimager_psf FAILED

====================================================================================== FAILURES =======================================================================================
________________________________________________________________________________ test_wfirstimager_psf ________________________________________________________________________________

    def test_wfirstimager_psf():
        """Just test that instantiating WFIRSTImager works and can compute a PSF"""
        wi = wfirst.WFIRSTImager()
>       wi.calcPSF()

webbpsf/tests/test_wfirst.py:6:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <webbpsf.wfirst.WFIRSTImager object at 0x1101dd610>, outfile = None, source = None, filter = None, nlambda = 10, monochromatic = None, fov_arcsec = 5.0, fov_pixels = None
oversample = 4, detector_oversample = 4, fft_oversample = 4, calc_oversample = None, rebin = True, clobber = True, display = False, return_intermediates = False, kwargs = {}
local_options = {'detector_oversample': 4, 'fft_oversample': 4, 'monochromatic': None, 'nlambda': 10}, fov_spec = 'arcsec = 5.000000'

    def calcPSF(self, outfile=None, source=None, filter=None, nlambda=None, monochromatic=None,
                fov_arcsec=None, fov_pixels=None,  oversample=None, detector_oversample=None,
                fft_oversample=None, calc_oversample=None, rebin=True, clobber=True, display=False,
                return_intermediates=False, **kwargs):
        """ Compute a PSF.

            The result can either be written to disk (set outfile="filename") or else will be returned as
            an astropy.io.fits HDUList object.


            Output sampling may be specified in one of two ways:

            1) Set `oversample=<number>`. This will use that oversampling factor beyond detector pixels
               for output images, and beyond Nyquist sampling for any FFTs to prior optical planes.
            2) set `detector_oversample=<number>` and `fft_oversample=<other_number>`. This syntax lets
               you specify distinct oversampling factors for intermediate and final planes. This is generally
               only relevant in the case of coronagraphic calculations.

            By default, both oversampling factors are set equal to 4. This default can be changed in your
            webbpsf configuration file.

            Notes
            -----
            More advanced PSF computation options (pupil shifts, source positions, jitter, ...)
            may be set by configuring the `.options` dictionary attribute of this class.

            Parameters
            ----------
            filter : string, optional
                Filter name. Setting this is just a shortcut for setting the object's filter first, then
                calling calcPSF afterwards.
            source : pysynphot.SourceSpectrum or dict or tuple
                specification of source input spectrum. Default is a 5700 K sunlike star.
            nlambda : int
                How many wavelengths to model for broadband?
                The default depends on how wide the filter is, as set by a lookup table in the webbpsf data distribution.
            monochromatic : float, optional
                Setting this to a wavelength value (in meters) will compute a monochromatic PSF at that
                wavelength, overriding filter and nlambda parameters.
            fov_arcsec : float
                field of view in arcsec. Default=5
            fov_pixels : int
                field of view in pixels. This is an alternative to fov_arcsec.
            outfile : string
                Filename to write. If None, then result is returned as an HDUList
            oversample, detector_oversample, fft_oversample : int
                How much to oversample. Default=4. By default the same factor is used for final output
                pixels and intermediate optical planes, but you may optionally use different factors
                if so desired.
            rebin : bool, optional
                If set, the output file will contain a FITS image extension containing the PSF rebinned
                onto the actual detector pixel scale. Thus, setting oversample=<N> and rebin=True is
                the proper way to obtain high-fidelity PSFs computed on the detector scale. Default is True.
            clobber : bool
                overwrite output FITS file if it already exists?
            display : bool
                Whether to display the PSF when done or not.
            save_intermediates, return_intermediates : bool
                Options for saving to disk or returning to the calling function the intermediate optical planes during the propagation.
                This is useful if you want to e.g. examine the intensity in the Lyot plane for a coronagraphic propagation. These have no
                effect for simple direct imaging calculations.


            For additional arguments, see the documentation for poppy.OpticalSystem.calcPSF()


            Returns
            -------
            outfits : fits.HDUList
                The output PSF is returned as a fits.HDUlist object.
                If `outfile` is set to a valid filename, the output is also written to that file.


            """

        if calc_oversample is not None:
            raise DeprecationWarning("The calc_oversample parameter is deprecated and will be removed in webbpsf 0.4. User fft_oversample instead.")
            fft_oversample = calc_oversample # back compatibility hook for deprecated arg name.

        _log.info("Setting up PSF calculation for "+self.name)

        # first make sure that webbpsf's configuration is used to override any of the
        # same configuration options in poppy. This is admittedly perhaps overbuilt to have identical
        # settings in both packages, but the intent is to shield typical users of webbpsf
        # from having to think about the existence of the underlying library. They can
        # just deal with one set of settings.
        #config._apply_settings_to_poppy()

        if filter is not None:
            self.filter = filter

        local_options = self.options.copy()  # all local state should be stored in a dict, for
                                      # ease of handing off to the various subroutines of
                                      # calcPSF. Don't just modify the global self.options
                                      # structure since that would pollute it with temporary
                                      # state as well as persistent state.
        local_options['monochromatic'] = monochromatic



        #----- choose # of wavelengths intelligently. Do this first before generating the source spectrum weighting.
        if nlambda is None or nlambda==0:
            # Automatically determine number of appropriate wavelengths.
            # Make selection based on filter configuration file
            try:
                nlambda = self._filter_nlambda_default[self.filter]
                _log.debug("Automatically selecting # of wavelengths: %d" % nlambda)
            except:
                nlambda=10
                _log.warn("Filter %s not found in lookup table for default number of wavelengths to use.. setting default nlambda=%d" % (self.filter, nlambda))
        local_options['nlambda'] = nlambda



        #----- calculate field of view depending on supplied parameters
        if fov_arcsec is None and fov_pixels is None:  #pick decent defaults.
            if self.name =='MIRI': fov_arcsec=12.
            else: fov_arcsec=5.
            fov_spec = 'arcsec = %f' % fov_arcsec
        elif fov_pixels is not None:

            if np.isscalar(fov_pixels):
                fov_spec = 'pixels = %d' % fov_pixels
            else:
                fov_spec = 'pixels = (%d, %d)' % (fov_pixels[0], fov_pixels[1])
        elif fov_arcsec is not None:
            if np.isscalar(fov_arcsec):
                fov_spec = 'arcsec = %f' % fov_arcsec
            else:
                fov_spec = 'arcsec = (%.3f, %.3f)' % (fov_arcsec[0], fov_arcsec[1])

        _log.debug('FOV set to '+fov_spec)

        #---- Implement the semi-convoluted logic for the oversampling options. See docstring above
        if oversample is not None and detector_oversample is not None and fft_oversample is not None:
            # all options set, contradictorily -> complain!
            raise ValueError("You cannot specify simultaneously the oversample= option with the detector_oversample and fft_oversample options. Pick one or the other!")
        elif oversample is None and detector_oversample is None and fft_oversample is None:
            # nothing set -> set oversample = 4
            oversample = conf.default_oversampling
        if detector_oversample is None: detector_oversample = oversample
        if fft_oversample is None: fft_oversample = oversample
        local_options['detector_oversample']=detector_oversample
        local_options['fft_oversample']=fft_oversample

        #----- compute weights for each wavelength based on source spectrum
>       wavelens, weights = self._getWeights(source=source, nlambda=nlambda, monochromatic=monochromatic)

webbpsf/webbpsf_core.py:398:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <webbpsf.wfirst.WFIRSTImager object at 0x1101dd610>, source = None, nlambda = 10, monochromatic = None, verbose = False

    def _getWeights(self, source=None, nlambda=5, monochromatic=None, verbose=False):
        """ Return the set of discrete wavelengths, and weights for each wavelength,
            that should be used for a PSF calculation.

            Uses pysynphot (if installed), otherwise assumes simple-minded flat spectrum

            """
        if monochromatic is not None:
            poppy_core._log.info(" monochromatic calculation requested.")
            return (np.asarray([monochromatic]),  np.asarray([1]) )

        elif _HAS_PYSYNPHOT and (isinstance(source, pysynphot.spectrum.SourceSpectrum)  or source is None):
            """ Given a pysynphot.SourceSpectrum object, perform synthetic photometry for
                nlambda bins spanning the wavelength range of interest.

                Because this calculation is kind of slow, cache results for reuse in the frequent
                case where one is computing many PSFs for the same spectral source.
                """
            poppy_core._log.debug("Calculating spectral weights using pysynphot, nlambda=%d, source=%s" % (nlambda, str(source)))
            if source is None:
                try:
                    source = pysynphot.Icat('ck04models',5700,0.0,2.0)
                except:
                    poppy_core._log.error("Could not load Castelli & Kurucz stellar model from disk; falling back to 5700 K blackbody")
                    source = pysynphot.BlackBody(5700)
            poppy_core._log.debug("Computing spectral weights for source = "+str(source))

            try:
                key = self._getSpecCacheKey(source, nlambda)
                if key in self._spectra_cache.keys():
                    poppy_core._log.debug("Previously computed spectral weights found in cache, just reusing those")
                    return self._spectra_cache[keys]
            except:
                pass  # in case sourcespectrum lacks a name element so the above lookup fails - just do the below calc.

            poppy_core._log.info("Computing wavelength weights using synthetic photometry for %s..." % self.filter)
            band = self._getSynphotBandpass(self.filter)
            # choose reasonable min and max wavelengths
            w_above10 = np.where(band.throughput > 0.10*band.throughput.max())

            minwave = band.wave[w_above10].min()
            maxwave = band.wave[w_above10].max()
            poppy_core._log.debug("Min, max wavelengths = %f, %f" % (minwave/1e4, maxwave/1e4))

            wave_bin_edges =  np.linspace(minwave,maxwave,nlambda+1)
            wavesteps = (wave_bin_edges[:-1] +  wave_bin_edges[1:])/2
            deltawave = wave_bin_edges[1]-wave_bin_edges[0]
            effstims = []

            for wave in wavesteps:
                poppy_core._log.debug("Integrating across band centered at %.2f microns with width %.2f" % (wave/1e4,deltawave/1e4))
                box = pysynphot.Box(wave, deltawave) * band
                if box.throughput.max() == 0:  # watch out for pathological cases with no overlap (happens with MIRI FND at high nlambda)
                    result = 0.0
                else:
                    binset =  np.linspace(wave-deltawave, wave+deltawave, 30)  # what wavelens to use when integrating across the sub-band?
                    result = pysynphot.Observation(source, box, binset=binset).effstim('counts')
                effstims.append(result)

            effstims = np.array(effstims)
            effstims /= effstims.sum()
            wave_m =  band.waveunits.Convert(wavesteps,'m') # convert to meters

            newsource = (wave_m, effstims)
            if verbose: _log.info( " Wavelengths and weights computed from pysynphot: "+str( newsource))
            self._spectra_cache[ self._getSpecCacheKey(source,nlambda)] = newsource
            return newsource
        elif isinstance(source, dict) and ('wavelengths' in source) and ('weights' in source):
            # Allow providing directly a set of specific weights and wavelengths, as in poppy.calcPSF source option #2
            return (source['wavelengths'], source['weights'])
        elif isinstance(source, tuple) and len(source) == 2:
            # Allow user to provide directly a tuple, as in poppy.calcPSF source option #3
            return source

        else:  #Fallback simple code for if we don't have pysynphot.
            poppy_core._log.warning("Pysynphot unavailable (or invalid source supplied)!   Assuming flat # of counts versus wavelength.")
            # compute a source spectrum weighted by the desired filter curves.
            # The existing FITS files all have wavelength in ANGSTROMS since that is the pysynphot convention...
            filterfits = fits.open(self._filters[self.filter].filename)
            filterdata = filterfits[1].data
            try:
                f1 = filterdata.WAVELENGTH
                d2 = filterdata.THROUGHPUT
            except:
                raise ValueError("The supplied file, %s, does not appear to be a FITS table with WAVELENGTH and THROUGHPUT columns." % self._filters[self.filter].filename )
            if 'WAVEUNIT' in  filterfits[1].header.keys():
                waveunit  = filterfits[1].header['WAVEUNIT']
            else:
                poppy_core._log.warn("CAUTION: no WAVEUNIT keyword found in filter file {0}. Assuming = Angstroms by default".format(filterfits.filename()))
                waveunit = 'Angstrom'
>           if waveunit != 'Angstrom': raise ValueError("The supplied file, %s, does not have WAVEUNIT = Angstrom as expected." % self._filters[self.filter].filename )
E           ValueError: The supplied file, /Users/mperrin/software/webbpsf-data/WFIRSTImager/filters/Z087_throughput.fits, does not have WAVEUNIT = Angstrom as expected.

/Users/mperrin/Dropbox (Personal)/Documents/software/poppy/poppy/instrument.py:722: ValueError
----------------------------------------------------------------------------------- Captured stderr -----------------------------------------------------------------------------------
poppy     : INFO     Optic from /Users/mperrin/software/webbpsf-data/AFTA_symmetrical.fits: Loaded amplitude transmission from /Users/mperrin/software/webbpsf-data/AFTA_symmetrical.fits
webbpsf   : INFO     Setting up PSF calculation for WFIRSTImager
webbpsf   : WARNING  Filter Z087 not found in lookup table for default number of wavelengths to use.. setting default nlambda=10
poppy     : WARNING  Pysynphot unavailable (or invalid source supplied)!   Assuming flat # of counts versus wavelength.
================================================================== 1 failed, 36 passed, 1 xfailed in 361.24 seconds ==================================================================

Failing test: test_nircam_SAMC

Issue by josePhoenix
Tuesday Dec 09, 2014 at 19:07 GMT
Originally opened as mperrin/webbpsf#30


This test is failing because the precision is less than desired on some machines. The difference between the same PSF calculated with the SAM coronograph method and with the no_sam option is supposed to be less than 1e-7.

Can we make the cutoff less stringent?

(Also, it looks like the code path for the SAM method in the test doesn't check that SAM was actually used. It apparently was, if there's a discrepancy, but maybe there should be a way to signal that in the PSF returned. If there is already, it should be checked.)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.