예제 #1
0
파일: helpers.py 프로젝트: bhayden53/SALT2X
def register_JLA_magsys():
    #AB_B12
    spec = np.genfromtxt('%s/MagSys/ab-spec.dat' % (os.environ['SNFIT_DATA']))
    wave = spec[:, 0]
    flux = spec[:, 1]
    specsnc = sncosmo.Spectrum(wave,
                               flux,
                               unit=(u.erg / u.s / u.cm**2 / u.AA),
                               wave_unit=u.AA)
    magsys = sncosmo.magsystems.SpectralMagSystem(specsnc)
    sncosmo.registry.register(magsys,
                              'AB_B12',
                              data_class=sncosmo.MagSystem,
                              force=True)
    test = sncosmo.get_magsystem('ab_b12')
    # embed()
    print test

    #vega2
    spec = np.genfromtxt('%s/MagSys/bd_17d4708_stisnic_003.ascii' %
                         (os.environ['SNFIT_DATA']))
    wave = spec[:, 0]
    flux = spec[:, 1]
    specsnc = sncosmo.Spectrum(wave,
                               flux,
                               unit=(u.erg / u.s / u.cm**2 / u.AA),
                               wave_unit=u.AA)
    magsys = sncosmo.magsystems.SpectralMagSystem(specsnc)
    sncosmo.registry.register(magsys,
                              'VEGA2',
                              data_class=sncosmo.MagSystem,
                              force=True)

    #vegahst
    spec = np.genfromtxt('%s/MagSys/alpha_lyr_stis_005.ascii' %
                         (os.environ['SNFIT_DATA']))
    wave = spec[:, 0]
    flux = spec[:, 1]
    specsnc = sncosmo.Spectrum(wave,
                               flux,
                               unit=(u.erg / u.s / u.cm**2 / u.AA),
                               wave_unit=u.AA)
    magsys = sncosmo.magsystems.SpectralMagSystem(specsnc)
    sncosmo.registry.register(magsys,
                              'VEGAHST',
                              data_class=sncosmo.MagSystem,
                              force=True)
예제 #2
0
def test_bin_edges_log():
    """Ensure that we can recover consistent bin edges for a spectrum from bin
    centers.

    Internally, the bin edges are stored rather than the bin centers.
    """
    wave = np.logspace(np.log10(3000), np.log10(8000), 100)
    flux = np.ones_like(wave)
    spec = sncosmo.Spectrum(wave, flux)

    assert_allclose(wave, spec.wave, rtol=1.e-5)
예제 #3
0
    def setup_class(self):
        # Simulate a spectrum
        model = sncosmo.Model(source='hsiao-subsampled')
        params = {'t0': 10., 'amplitude': 1.e-7, 'z': 0.2}
        start_params = {'t0': 0., 'amplitude': 1., 'z': 0.}
        model.set(**params)

        # generate a fake spectrum with no errors. note: we simulate a high
        # resolution spectrum and then bin it up. we also include large
        # covariance between spectral elements to verify that we are handling
        # covariance properly.
        spec_time = params['t0'] + 5.
        sim_wave = np.arange(3000, 9000)
        sim_flux = model.flux(spec_time, sim_wave)
        sim_fluxcov = 0.01 * np.max(sim_flux)**2 * np.ones(
            (len(sim_flux), len(sim_flux)))
        sim_fluxcov += np.diag(0.1 * sim_flux**2)
        spectrum = sncosmo.Spectrum(sim_wave,
                                    sim_flux,
                                    fluxcov=sim_fluxcov,
                                    time=spec_time)

        # generate a binned up low-resolution spectrum.
        bin_wave = np.linspace(3500, 8500, 200)
        bin_spectrum = spectrum.rebin(bin_wave)

        # generate fake photometry with no errors
        points_per_band = 12
        bands = points_per_band * [
            'bessellux', 'bessellb', 'bessellr', 'besselli'
        ]
        times = params['t0'] + np.linspace(-10., 60., len(bands))
        zp = len(bands) * [25.]
        zpsys = len(bands) * ['ab']
        flux = model.bandflux(bands, times, zp=zp, zpsys=zpsys)
        fluxerr = len(bands) * [0.1 * np.max(flux)]
        photometry = Table({
            'time': times,
            'band': bands,
            'flux': flux,
            'fluxerr': fluxerr,
            'zp': zp,
            'zpsys': zpsys
        })

        self.model = model
        self.photometry = photometry
        self.spectrum = spectrum
        self.bin_spectrum = bin_spectrum
        self.params = params
        self.start_params = start_params
예제 #4
0
 def synth_lc(self):
     """
     Lightcurve synthesized from the spectrum
     """
     lc = defaultdict(list)
     for spec in self.spectra_noflags:
         lc['phase'].append(spec.salt2_phase)
         wave, flux, var = spec.merged_spec()
         snc_spec = sncosmo.Spectrum(wave, flux)
         for name, band in SNF_BANDS.items():
             try:
                 bandflux = snc_spec.bandflux(band)
                 lc[name].append(MAGSYS.band_flux_to_mag(bandflux, band))
             except ValueError:
                 lc[name].append(np.nan)
     return lc
예제 #5
0
def test_spectralmagsystem():
    """Check that SpectralMagSystem matches ABMagSystem when the spectrum is
    the same as AB."""

    # construct a spectrum with same flux as AB: 3631 x 10^{-23} erg/s/cm^2/Hz
    # Use a fine grid to reduce linear interpolation errors when integrating
    # in Spectrum.bandflux().
    wave = np.linspace(1000., 20000., 100000)  # fine grid
    flux = 3631.e-23 * np.ones_like(wave)
    unit = u.erg / u.s / u.cm**2 / u.Hz
    s = sncosmo.Spectrum(wave, flux, unit=unit)
    magsys1 = sncosmo.SpectralMagSystem(s)

    magsys2 = sncosmo.ABMagSystem()

    assert_allclose(magsys1.zpbandflux('bessellb'),
                    magsys2.zpbandflux('bessellb'))
예제 #6
0
def test_spectralmagsystem():
    """Check that SpectralMagSystem matches ABMagSystem when the spectrum is
    the same as AB."""

    # construct a spectrum with same flux as AB: 3631 x 10^{-23} erg/s/cm^2/Hz
    wave = np.linspace(1000., 20000., 1000)
    flux = 3631.e-23 * np.ones_like(wave)
    unit = u.erg / u.s / u.cm**2 / u.Hz
    s = sncosmo.Spectrum(wave, flux, unit=unit)
    magsys1 = sncosmo.SpectralMagSystem(s)

    magsys2 = sncosmo.ABMagSystem()

    # Match is only good to 1e-3. Probably due to different methods
    # of calculating bandflux between Spectrum and ABMagSystem.
    assert_allclose(magsys1.zpbandflux('bessellb'),
                    magsys2.zpbandflux('bessellb'),
                    rtol=1e-3)
예제 #7
0
 def synth_lc_array(self):
     """
     Lightcurve as a 5 x n_epochs numpy array (for fitting)
     """
     lcs, phases = [], []
     for spec in self.spectra_noflags:
         if spec.salt2_phase < -10 or spec.salt2_phase > 46:
             continue
         phases.append(spec.salt2_phase)
         wave, flux, var = spec.merged_spec()
         snc_spec = sncosmo.Spectrum(wave, flux)
         for name, band in SNF_BANDS.items():
             try:
                 bandflux = snc_spec.bandflux(band)
                 lcs.append(MAGSYS.band_flux_to_mag(bandflux, band))
             except ValueError:
                 lcs.append(np.nan)
     lcs = np.array(lcs)
     phases = np.array(phases)
     return phases, lcs.reshape(len(phases), 5)
예제 #8
0
    def post(self, spectrum_id):
        """
        ---
        description: Create synthetic photometry from a spectrum
        tags:
          - spectra
        parameters:
          - in: path
            name: spectrum_id
            required: true
            schema:
              type: integer
          - in: query
            name: filters
            schema:
              type: list
            required: true
            description: |
                List of filters
        responses:
          200:
            content:
              application/json:
                schema: SingleSpectrum
          400:
            content:
              application/json:
                schema: Error
        """

        data = self.get_json()
        filters = data.get('filters')

        spectrum = Spectrum.get_if_accessible_by(
            spectrum_id,
            self.current_user,
            raise_if_none=False,
        )
        if spectrum is None:
            return self.error(f'No spectrum with id {spectrum_id}')

        spec_dict = recursive_to_dict(spectrum)
        wav = spec_dict['wavelengths']
        flux = spec_dict['fluxes']
        err = spec_dict['errors']
        obstime = spec_dict['observed_at']

        try:
            spec = sncosmo.Spectrum(wav, flux * spectrum.astropy_units,
                                    err * spectrum.astropy_units)
        except TypeError:
            spec = sncosmo.Spectrum(wav, flux * spectrum.astropy_units)

        data_list = []
        for filt in filters:
            try:
                mag = spec.bandmag(filt, magsys='ab')
                magerr = 0
            except ValueError as e:
                return self.error(
                    f"Unable to generate synthetic photometry for filter {filt}: {e}"
                )

            data_list.append({
                'mjd': Time(obstime, format='datetime').mjd,
                'ra': spectrum.obj.ra,
                'dec': spectrum.obj.dec,
                'mag': mag,
                'magerr': magerr,
                'filter': filt,
                'limiting_mag': 25.0,
            })

        if len(data_list) > 0:
            df = pd.DataFrame.from_dict(data_list)
            df['magsys'] = 'ab'
            data_out = {
                'obj_id': spectrum.obj.id,
                'instrument_id': spectrum.instrument.id,
                'group_ids':
                [g.id for g in self.current_user.accessible_groups],
                **df.to_dict(orient='list'),
            }
            add_external_photometry(data_out, self.associated_user_object)

            return self.success()
        return self.success()