Ejemplo n.º 1
0
    def from_array(cls, wave, fluxd, meta=None, **kwargs):
        """Create standard from arrays.

        Parameters
        ----------
        wave : `~astropy.units.Quantity`
            The spectral wavelengths.

        fluxd : `~astropy.units.Quantity`
            The solar flux densities, at 1 au.

        meta : dict, optional
            Meta data.

        **kwargs
            Passed to object initialization.

        """

        import synphot

        source = synphot.SourceSpectrum(synphot.Empirical1D,
                                        points=wave,
                                        lookup_table=fluxd,
                                        meta=meta)

        return cls(source, **kwargs)
Ejemplo n.º 2
0
    def from_array(cls, wave, fluxd, meta=None, **kwargs):
        """Create standard from arrays.

        Parameters
        ----------
        wave : `~astropy.units.Quantity`
            The spectral wavelengths.

        fluxd : `~astropy.units.Quantity`
            The spectral flux densities.

        meta : dict, optional
            Meta data.

        **kwargs
            Passed to object initialization.

        """

        try:
            import synphot
        except ImportError:
            raise ImportError('synphot required for {}.'.format(cls.__name__))

        source = synphot.SourceSpectrum(synphot.Empirical1D,
                                        points=wave,
                                        lookup_table=fluxd,
                                        meta=meta)

        return cls(source, **kwargs)
Ejemplo n.º 3
0
 def test_fluxd(self):
     w = u.Quantity(np.linspace(0.3, 1.0), 'um')
     f = u.Quantity(np.ones(len(w)), 'W/(m2 um)')
     source = synphot.SourceSpectrum(synphot.Empirical1D,
                                     points=w,
                                     lookup_table=f)
     s = Star(source)
     assert np.allclose(s.fluxd.to(f.unit).value, f.value)
Ejemplo n.º 4
0
 def test_source(self):
     w = u.Quantity(np.linspace(0.3, 1.0), 'um')
     f = u.Quantity(np.ones(len(w)), 'W/(m2 um)')
     source = synphot.SourceSpectrum(synphot.Empirical1D,
                                     points=w,
                                     lookup_table=f)
     s = Star(source)
     f = s.source(w)
     assert s.source == source
Ejemplo n.º 5
0
    def __init__(self, T=None):
        super().__init__(None, description='πB(T)')

        if T is None:
            raise TypeError('T is required.')

        self._T = u.Quantity(T, u.K)
        self._source = synphot.SourceSpectrum(
            synphot.BlackBody1D, temperature=self._T.value) * np.pi
Ejemplo n.º 6
0
 def test_observe_bad_wfb(self):
     w = u.Quantity(np.linspace(0.3, 1.0), 'um')
     f = u.Quantity(np.ones(len(w)), 'W/(m2 um)')
     source = synphot.SourceSpectrum(synphot.Empirical1D,
                                     points=w,
                                     lookup_table=f)
     s = Star(source)
     with pytest.raises(TypeError):
         s.observe(np.arange(5))
Ejemplo n.º 7
0
    def from_file(cls,
                  filename,
                  wave_unit=None,
                  flux_unit=None,
                  cache=True,
                  **kwargs):
        """Load the source spectrum from a file.

        NaNs are dropped.

        Parameters
        ----------
        filename : string
            The name of the file.  See
            `~synphot.SourceSpectrum.from_file` for details.

        wave_unit, flux_unit : str or `~astropy.units.Unit`, optional
            Wavelength and flux units in the file.

        cache : bool, optional
            If ``True``, cache the contents of URLs.

        **kwargs
            Passed to object initialization.

        """

        try:
            import synphot
        except ImportError:
            raise ImportError('synphot required for {}.'.format(cls.__name__))

        from astropy.utils.data import download_file, _is_url

        if filename.lower().endswith(('.fits', '.fit', '.fz')):
            read_spec = synphot.specio.read_fits_spec
        else:
            read_spec = synphot.specio.read_ascii_spec

        # URL cache because synphot.SourceSpectrum.from_file does not
        if _is_url(filename):
            fn = download_file(filename, cache=True)
        else:
            fn = filename

        spec = read_spec(fn, wave_unit=wave_unit, flux_unit=flux_unit)
        i = np.isfinite(spec[1] * spec[2])
        source = synphot.SourceSpectrum(synphot.Empirical1D,
                                        points=spec[1][i],
                                        lookup_table=spec[2][i],
                                        meta={'header': spec[0]})

        return cls(source, **kwargs)
Ejemplo n.º 8
0
    def yaml_file_can_be_loaded_into_optical_train(self):
        # .. todo: get this working on Travis
        filename = os.path.join(TEST_PATH, "MICADO_SCAO_WIDE_2.yaml")

        cmds = UserCommands(yamls=[filename])
        assert isinstance(cmds, UserCommands)
        assert isinstance(cmds.yaml_dicts, list)

        psf_file = cmds.yaml_dicts[1]["effects"][0]["kwargs"]["filename"]
        if find_file(psf_file) is None:
            new_file = "test_FVPSF.fits"
            cmds.yaml_dicts[1]["effects"][0]["kwargs"]["filename"] = new_file

        opt = OpticalTrain(cmds=cmds)
        assert isinstance(opt, OpticalTrain)
        assert isinstance(opt.optics_manager, OpticsManager)
        assert isinstance(
            opt.optics_manager.get_all(efs.FieldVaryingPSF)[0],
            efs.FieldVaryingPSF)
        assert isinstance(opt.image_plane, ImagePlane)
        assert opt.image_plane.hdu.header["NAXIS1"] >= 4096
        assert isinstance(opt.fov_manager, FOVManager)
        assert len(opt.fov_manager.fovs) == 64

        if PLOTS:
            for fov in opt.fov_manager.fovs:
                sky_cnrs, det_cnrs = fov.corners
                plt.plot(sky_cnrs[0], sky_cnrs[1])
            plt.show()

        r = np.arange(-25, 25)
        x, y = np.meshgrid(r, r)
        x = x.flatten() * u.arcsec
        y = y.flatten() * u.arcsec
        ref = [0] * len(x)
        weight = [1] * len(x)
        spec = sp.SourceSpectrum(sp.Empirical1D,
                                 points=[0.5, 3.0] * u.um,
                                 lookup_table=[1e3, 1e3] *
                                 u.Unit("ph s-1 m-2 um-1"))
        src = Source(x=x, y=y, ref=ref, weight=weight, spectra=[spec])
        opt.observe(src)

        if PLOTS:
            plt.imshow(opt.image_plane.image.T, origin="lower", norm=LogNorm())
            plt.colorbar()
            plt.show()
Ejemplo n.º 9
0
    def from_file(cls, filename, wave_unit=None, flux_unit=None,
                  cache=True, **kwargs):
        """Load the source spectrum from a file.

        Parameters
        ----------
        filename : string
          The name of the file.  See
          `~synphot.SourceSpectrum.from_file` for details.

        wave_unit, flux_unit : str or `~astropy.units.core.Unit`, optional
          Wavelength and flux units.

        cache : bool, optional
          If `True`, cache the contents of URLs.

        **kwargs
          Passed to `Sun` initialization.

        """

        from astropy.utils.data import download_file
        from astropy.utils.data import _is_url
        import synphot
        from synphot.specio import read_fits_spec, read_ascii_spec

        # URL cache because synphot.SourceSpectrum.from_file does not
        if _is_url(filename):
            if filename.lower().endswith(('.fits', '.fit')):
                read_spec = read_fits_spec
            else:
                read_spec = read_ascii_spec

            fn = download_file(filename, cache=True)
            spec = read_spec(fn, wave_unit=wave_unit, flux_unit=flux_unit)
            source = synphot.SourceSpectrum(
                synphot.Empirical1D, points=spec[1], lookup_table=spec[2],
                meta={'header': spec[0]})
        else:
            source = synphot.SourceSpectrum.from_file(
                filename, wave_unit=wave_unit, flux_unit=flux_unit)

        return cls(source, **kwargs)
Ejemplo n.º 10
0
 def __init__(self):
     super().__init__(
         synphot.SourceSpectrum(synphot.ConstFlux1D,
                                amplitude=1 * u.W / u.m**2 / u.um))
    def get_sky_spectrum(self, return_type="table", filename=None):

        from astropy import table

        if filename is None:
            filename = "skycalc_temp.fits"

        if not self.validate_params():
            raise ValueError("Object contains invalid parameters. "
                             "Not calling ESO")

        skm = SkyModel()
        skm.callwith(self.values)
        skm.write(filename)

        with fits.open(filename) as hdu:

            tbl = table.Table(hdu[1].data)
            tbl["lam"].unit = u.um
            for colname in tbl.colnames:
                if "flux" in colname:
                    tbl[colname].unit = u.Unit("ph s-1 m-2 um-1 arcsec-2")

        date_created = dt.now().strftime('%Y-%m-%dT%H:%M:%S')
        meta_data = {
            "DESCRIPT": "Sky transmission and emission curves",
            "SOURCE": "ESO Skycalc utility",
            "AUTHOR": "ESO Skycalc utility",
            "STATUS": "Tested - Generated from ESO Skycalc utility",
            "DATE_CRE": date_created,
            "ETYPE": "TERCurve",
            "EDIM": 1
        }

        params = {k: (self.values[k], self.comments[k]) for k in self.keys}
        meta_data.update(params)

        if "tab" in return_type:
            tbl.meta.update(meta_data)

            if "ext" in return_type:
                tbl_return = tbl
            else:
                tbl_small = table.Table()
                tbl_small.add_columns([tbl["lam"], tbl["trans"], tbl["flux"]])
                tbl_return = tbl_small

            return tbl_return

        elif "arr" in return_type:

            wave = tbl["lam"].data * tbl["lam"].unit
            trans = tbl["trans"].data
            flux = tbl["flux"].data * tbl["flux"].unit

            return wave, trans, flux

        elif "syn" in return_type:
            import synphot as sp

            trans = sp.SpectralElement(sp.Empirical1D,
                                       points=tbl["lam"].data *
                                       tbl["lam"].unit,
                                       lookup_table=tbl["trans"].data)

            funit = u.Unit("ph s-1 m-2 um-1")
            flux = sp.SourceSpectrum(sp.Empirical1D,
                                     points=tbl["lam"].data * tbl["lam"].unit,
                                     lookup_table=tbl["flux"].data * funit)
            print("Warning: synphot doesn't accept surface brightnesses \n"
                  "The resulting spectrum should be multiplied by arcsec-2")

            return trans, flux

        elif "fit" in return_type:

            hdu0 = fits.PrimaryHDU()
            for key in meta_data:
                hdu0.header[key] = meta_data[key]
            hdu1 = fits.table_to_hdu(tbl)
            hdu = fits.HDUList([hdu0, hdu1])

            return hdu
Ejemplo n.º 12
0
    time = Time('2025-03-01')
    sun = get_sun(time).transform_to(GeocentricTrueEcliptic(equinox=time))
    coord = SkyCoord(sun.lon + 180 * u.deg,
                     lat * u.deg,
                     frame=GeocentricTrueEcliptic(equinox=time))

st.markdown('## Source')

spectrum = st.radio('Spectrum',
                    ('Thermal', 'Flat in frequency (AB mag = const)',
                     'Flat in wavelength (ST mag = const)'))

if spectrum == 'Thermal':
    temperature = st.number_input('Temperature (K)', 0, 20000, 10000, 1000)
    source = synphot.SourceSpectrum(synphot.BlackBodyNorm1D,
                                    temperature=temperature * u.K)
elif spectrum == 'Flat in frequency (AB mag = const)':
    source = synphot.SourceSpectrum(synphot.ConstFlux1D, amplitude=0 * u.ABmag)
elif spectrum == 'Flat in wavelength (ST mag = const)':
    source = synphot.SourceSpectrum(synphot.ConstFlux1D, amplitude=0 * u.STmag)

spectra = pd.DataFrame({
    'wavelength':
    bandpass.waveset.to_value(u.nm),
    'aeff': (bandpass(bandpass.waveset) *
             dorado.sensitivity.constants.AREA).to_value(u.cm**2),
    'source':
    source(bandpass.waveset, u.erg * u.s**-1 * u.cm**-2 * u.nm**-1)
})

palette = [to_hex(color) for color in seaborn.color_palette('colorblind', 2)]