Ejemplo n.º 1
0
def test_get_ebv_from_map():
    """Try get_ebv_from_map."""

    mapdir = join(dirname(__file__), "data", "dust_subsection")

    # coordinate that is in the dust subsection map
    coords = (204., -30.)
    coords2 = SkyCoord(204.0, -30.0, frame='icrs', unit='deg')

    # value from http://irsa.ipac.caltech.edu/applications/DUST/
    # with input "204.0 -30.0 J2000"
    true_ebv = 0.0477

    # Use interpolate=False to match IRSA value
    ebv = sncosmo.get_ebv_from_map(coords, mapdir=mapdir, interpolate=False)
    assert_allclose(ebv, true_ebv, rtol=0.01)
    ebv2 = sncosmo.get_ebv_from_map(coords2, mapdir=mapdir, interpolate=False)
    assert_allclose(ebv2, true_ebv, rtol=0.01)
    def getTargetMag(self, dataSlice, filter):
    # fainten the extragalactic magnitude due to Galactic dust
        dec=numpy.maximum(dataSlice['fieldDec'][0],-numpy.pi/2)
        co = coord.ICRS(ra=dataSlice['fieldRA'][0], dec=dec, unit=(u.rad, u.rad))
        ebv=sncosmo.get_ebv_from_map(co, mapdir='../data',cache=True)
        #np=ephem.Equatorial(dataSlice['fieldRA'][0],dataSlice['fieldDec'][0])
        #g=ephem.Galactic(np)
        #ebv=map.generateEbv(g.lon,g.lat)
        self.ccm.set(ebv=ebv)
        av=-2.5*numpy.log10(self.ccm.propagate(numpy.array([self.filterinfo[filter]['wave']*10]),numpy.array([1])))
        
#        print co, ccm.parameters, av
#        return self.filterinfo[filter]['targetMag']+av
        return self.filterinfo[filter]['targetMag']+av
Ejemplo n.º 3
0
    def getTargetMag(self, dataSlice, filter):
        # fainten the extragalactic magnitude due to Galactic dust
        dec = numpy.maximum(dataSlice['fieldDec'][0], -numpy.pi / 2)
        co = coord.ICRS(ra=dataSlice['fieldRA'][0],
                        dec=dec,
                        unit=(u.rad, u.rad))
        ebv = sncosmo.get_ebv_from_map(co, mapdir='../data', cache=True)
        #np=ephem.Equatorial(dataSlice['fieldRA'][0],dataSlice['fieldDec'][0])
        #g=ephem.Galactic(np)
        #ebv=map.generateEbv(g.lon,g.lat)
        self.ccm.set(ebv=ebv)
        av = -2.5 * numpy.log10(
            self.ccm.propagate(
                numpy.array([self.filterinfo[filter]['wave'] * 10]),
                numpy.array([1])))

        #        print co, ccm.parameters, av
        #        return self.filterinfo[filter]['targetMag']+av
        return self.filterinfo[filter]['targetMag'] + av
Ejemplo n.º 4
0
    def setUp(self):
        """
        Setup the objects used in this test suite class. snObject objs are
        required to have a SN sed namely ra, dec, and SALT model parameters
        x0, x1,c and the redshift of the supernova z

        Store objects:

        # NO MW Extinction objects from catsim and SNCosmo
        self.SNnoMW : SN with said parameters, unexincted in MW
        self.SNCosmo_nomw :

        # objects with MW extinction
        self.SNmw : SN with said parameters, exincted in MW
        self.SNCosmo_mw :
        """

        ra = 204.
        dec = -30.
        mjdobs = 571203.
        # Setup SN object of different kinds we want to check

        # In order to compare SN light curves between SNCosmo and Catsim
        # we need to set them up separately

            # Check case with no MW extinction
        SNnoMW = SNObject()
        SNnoMW.set(x0=1.847e-6, x1=0.1, c=0., z=0.2)
        SNnoMW.set_MWebv(0.)
        self.SNnoMW = SNnoMW
        dust = sncosmo.OD94Dust()
        SNCosmo_nomw = sncosmo.Model(source='salt2-extended',
                                     effects=[dust, dust],
                                     effect_names=['host', 'mw'],
                                     effect_frames=['rest', 'obs'])

        SNCosmo_nomw.set(x0=1.847e-6, x1=0.1, c=0., z=0.2)
        SNCosmo_nomw.set(mwebv=0.)
        self.SNCosmo_nomw = SNCosmo_nomw

            ### SNCosmo Model object with MW extinction. Store in self.SNCosmo_mw
        # Object of SNObject class with MW extinction
        SN = SNObject(ra, dec)
        SN.set(x0=1.847e-6, x1=0.1, c=0., z=0.2)
        SNnoMW.set_MWebv(0.)
        self.SNmw = SN

        SNCosmo = sncosmo.Model(source='salt2-extended',
                                effects=[dust, dust],
                                effect_names=['host', 'mw'],
                                effect_frames=['rest', 'obs'])

        SNCosmo.set(x0=1.847e-6, x1=0.1, c=0., z=0.2)
        skycoords = SkyCoord(ra, dec, unit='deg')
        t_mwebv = sncosmo.get_ebv_from_map(skycoords,
                                           mapdir=map_dir,
                                           interpolate=False)
        # Now Set the value of mwebv
        SNCosmo.set(mwebv=t_mwebv)
        self.SNCosmo_mw = SNCosmo

        CCMdust = sncosmo.CCM89Dust()
        SNCosmo_float = sncosmo.Model(source='salt2-extended',
                                      effects=[CCMdust, CCMdust],
                                      effect_names=['host', 'mw'],
                                      effect_frames=['rest', 'obs'])

        SNCosmo_float.set(x0=1.847e-6, x1=0.1, c=0., z=0.2)
        SNCosmo_float.set(mwebv=t_mwebv)
        self.SNCosmo_float = SNCosmo_float
        
            # Load LSST sofware bandpass objects for magnitude calculation
        self.bandPassList = ['u', 'g', 'r', 'i', 'z', 'y']
        pbase = PhotometryBase()
        pbase.loadBandpassesFromFiles(self.bandPassList)
        pbase.setupPhiArray_dict()
        self.pbase = pbase
        self.lsstbands = pbase.bandpassDict
        self.times = numpy.arange(-20., 50., 1.0)

        # Load SNCosmo bandpass objects for comparison test
        thisshouldbeNone = tu.getlsstbandpassobjs(self.bandPassList,
                                                  loadcatsim=False,
                                                  plot=False)

        self.sncosmobands = ['LSST' + band for band in self.bandPassList]
Ejemplo n.º 5
0
    # Standardize data
    data = standardize_data(data)

    # Get min and max data times
    dtmin = np.min(data['time'])
    dtmax = np.max(data['time'])

    # Cut LC based on S/N ratio
    mask = data['flux'] / data['fluxerr'] > 5.
    if (len(np.unique(data['band'][mask])) < 2):
        print "Fails SNR cut"
        ncut += 1
        continue

    # get mwebv
    mwebv = sncosmo.get_ebv_from_map((meta['ra'], meta['dec']),
                                     mapdir='/home/kyle/Data/dust')

    # Evaluate evidence for each model
    for name, m in models.iteritems():

        # Set t0 bounds (its OK that we keep overwriting this dict)
        m['model'].set(z=0.)
        t0off = m['model'].get('t0') - m['model'].mintime() # t0 offset from
                                                            # mintime

        t0min = dtmin - 30. + t0off
        t0max = dtmax - 30. + t0off
        m['bounds']['t0'] = (t0min, t0max)

        # Set mwebv of model.
        m['model'].set(mwebv=mwebv)
Ejemplo n.º 6
0
def simulate_simlib(simlibfile, snmodelsource, outfile="LC/simulatedlc.dat", restrict=10):
    """
    Simulate SN based on the simlibfile using SNCosmo SALT models


    Parameters
    ----------
    simlibfile :

    snmodelsource:

    outfile:

    Returns
    -------

    """
    from astropy.units import Unit
    from astropy.coordinates import SkyCoord

    # read the simlibfile into obstables
    meta, obstables = sncosmo.read_snana_simlib(simlibfilename)

    # set the SNCosmo model source
    dustmaproot = os.getenv("SIMS_DUSTMAPS_DIR")
    map_dir = os.path.join(dustmaproot, "DustMaps")
    dust = sncosmo.CCM89Dust()
    model = Model(
        source=snmodelsource, effects=[dust, dust], effect_frames=["rest", "obs"], effect_names=["host", "mw"]
    )

    maxSNperField = restrict
    # Different fields in SIMLIB are indexed by libids
    libids = obstables.keys()
    lcs = []
    for libid in libids:

        # Get the obstable corresponding to each field
        obstable = obstables[libid]
        manipulateObsTable(obstable)
        # Need Area from PixSize
        ra = obstable.meta["RA"]
        dec = obstable.meta["DECL"]
        area = obstable.meta["PIXSIZE"]
        maxmjd = obstable["time"].max()
        minmjd = obstable["time"].min()
        rangemjd = maxmjd - minmjd
        skycoords = SkyCoord(ra, dec, unit="deg")
        t_mwebv = sncosmo.get_ebv_from_map(skycoords, mapdir=map_dir, interpolate=False)
        model.set(mwebv=t_mwebv)
        params = []
        # col = Table.Column(obstable['SEARCH'].size*['ab'], name='zpsys')
        # obstable['FLT'].name =  'band'
        # obstable['MJD'].name =  'time'
        # obstable['ZPTAVG'].name =  'zp'
        # obstable['CCD_GAIN'].name =  'gain'
        # obstable['SKYSIG'].name =  'skynoise'
        # obstable.add_column(col)
        redshifts = list(sncosmo.zdist(0.0, 1.2, ratefunc=cosmoRate, time=rangemjd, area=area))
        print "num SN generated ", len(redshifts)
        for i, z in enumerate(redshifts):
            mabs = normal(-19.3, 0.3)
            model.set(z=z)
            model.set_source_peakabsmag(mabs, "bessellb", "ab")
            x0 = model.get("x0")
            # RB: really should not be min, max but done like in catalogs
            p = {"z": z, "t0": uniform(minmjd, maxmjd), "x0": x0, "x1": normal(0.0, 1.0), "c": normal(0.0, 0.1)}
            params.append(p)
            if maxSNperField is not None:
                if i == maxSNperField:
                    break
        print "realizing SN"
        lcslib = sncosmo.realize_lcs(obstable, model, params, trim_observations=True)
        lcs.append(lcslib)
        # alllcsintables = vstack(lcslib)
    # print alllcsintables[0]
    # print alllcsintables[MJD].size
    # write light curves to disk
    for i, field in enumerate(lcs):
        for snid, lc in enumerate(field):
            sncosmo.write_lc(lc, fname=outfile + "_" + str(i) + "_" + str(snid) + ".dat", format="ascii")
    return lcs