Exemple #1
0
def test_write_griddata_ascii():

    x0 = np.array([0., 1.])
    x1 = np.array([0., 1., 2.])
    y = np.zeros((2, 3))

    f = six.StringIO()
    sncosmo.write_griddata_ascii(x0, x1, y, f)

    # Read it back
    f.seek(0)
    x0_in, x1_in, y_in = sncosmo.read_griddata_ascii(f)
    f.close()
    assert_allclose(x0_in, x0)
    assert_allclose(x1_in, x1)
    assert_allclose(y_in, y)

    # with a filename:
    dirname = mkdtemp()
    fname = os.path.join(dirname, 'griddata.dat')
    sncosmo.write_griddata_ascii(x0, x1, y, fname)
    x0_in, x1_in, y_in = sncosmo.read_griddata_ascii(fname)
    assert_allclose(x0_in, x0)
    assert_allclose(x1_in, x1)
    assert_allclose(y_in, y)
    os.remove(fname)
    os.rmdir(dirname)
Exemple #2
0
def test_write_griddata_ascii():

    x0 = np.array([0., 1.])
    x1 = np.array([0., 1., 2.])
    y = np.zeros((2, 3))

    f = StringIO()
    sncosmo.write_griddata_ascii(x0, x1, y, f)

    # Read it back
    f.seek(0)
    x0_in, x1_in, y_in = sncosmo.read_griddata_ascii(f)
    f.close()
    assert_allclose(x0_in, x0)
    assert_allclose(x1_in, x1)
    assert_allclose(y_in, y)

    # with a filename:
    dirname = mkdtemp()
    fname = os.path.join(dirname, 'griddata.dat')
    sncosmo.write_griddata_ascii(x0, x1, y, fname)
    x0_in, x1_in, y_in = sncosmo.read_griddata_ascii(fname)
    assert_allclose(x0_in, x0)
    assert_allclose(x1_in, x1)
    assert_allclose(y_in, y)
    os.remove(fname)
    os.rmdir(dirname)
    def read_SED(self, ascii_file):
        """
        Reads in an ascii file detailing the time evolution of an SED. Must be
        in the following format, 3 columns: phase, wavelength, flux.

        This will also set the source model and redshift the model according to
        initialization parameters.

        Parameters:
        -----------
            ascii_file: str
                string containing the path to the ascii file containing the
                SED evolution.

        """
        # Sanity to check to make sure the provided string indeed points to a
        # file.
        if not os.path.isfile(ascii_file):
            raise IOError("Could not find SED ascii file %s" % (ascii_file))
        # Read in the SED text file with sncosmo for use with it's Model API.
        self.sed_phase, self.sed_wave, self.sed_flux = read_griddata_ascii(ascii_file)
        # Make the source model and set the transient Model to be used for
        # light curve generation and observation.
        self.make_model()
        # Given the redshifted SED set the transient duration.
        self.transient_duration = (
            self.redshifted_model.maxtime() - self.redshifted_model.mintime()
        )
Exemple #4
0
def load_sed_model(filename, p_min=5e-4, p_max=50, **kwargs):
    """
    """
    # sed = np.genfromtxt(filename)

    # phase = np.unique(sed[:,0])
    # if p_min is not None:
    #     phase = phase[(phase >= p_min)]
    # if p_max is not None:
    #     phase = phase[(phase <= p_max)]

    # wave = sed[sed[:,0] == phase[0]][:,1]
    # # Spectral flux density is in [erg s^-1 cm^-3] but need [erg s^-1 cm^-2 Angstrom^-1]
    # # Multiply by 1e-8
    # flux = np.array([sed[sed[:,0] == p,2] for p in phase]) * 1e-8

    phase, wave, flux = sncosmo.read_griddata_ascii(filename)

    k0, k1 = 0, -1
    if p_min is not None:
        if phase[0] < p_min:
            k0 = np.where(phase < p_min)[0][-1] + 1

    if p_max is not None:
        if phase[-1] > p_max:
            k1 = np.where(phase > p_max)[0][0]

    print k0, k1

    source = TimeSeriesSource(phase[k0:k1], wave, flux[k0:k1], **kwargs)

    return sncosmo.Model(source=source)
Exemple #5
0
def test_salt2source_timeseries_vs_snfit():
    """Test timeseries output from SALT2Source vs pregenerated timeseries
    from snfit (SALT2 software)."""

    source = sncosmo.get_source("salt2", version="2.4")  # fixed version
    model = sncosmo.Model(source)

    dirname = os.path.join(os.path.dirname(__file__), "data")

    for fname in ['salt2_timeseries_1.dat',
                  'salt2_timeseries_2.dat',
                  'salt2_timeseries_3.dat',
                  'salt2_timeseries_4.dat']:
        f = open(os.path.join(dirname, fname), 'r')
        meta = read_header(f)
        time, wave, fluxref = sncosmo.read_griddata_ascii(f)
        f.close()

        # The output from snfit's Salt2Model.SpectrumFlux() has a
        # different definition than sncosmo's model.flux() by a factor
        # of a^2. snfit's definition is the rest-frame flux but at a
        # blue-shifted wavelength.  (There is no correction for photon
        # energy or time dilation. These corrections are made in the
        # integration step.)
        a = 1. / (1. + meta['Redshift'])
        fluxref *= a**2

        model.set(z=meta['Redshift'], t0=meta['DayMax'], x0=meta['X0'],
                  x1=meta['X1'], c=meta['Color'])
        flux = model.flux(time, wave)

        # super good agreement!
        assert_allclose(flux, fluxref, rtol=1e-13)
    def __init__(self,
                 modeldir=None,
                 m0file='sugar_template_0.dat',
                 m1file='sugar_template_1.dat',
                 m2file='sugar_template_2.dat',
                 m3file='sugar_template_3.dat',
                 m4file='sugar_template_4.dat',
                 name=None,
                 version=None):
        self.name = name
        self.version = version
        self._model = {}
        self._parameters = np.array([1., 1., 1., 1., 40.])

        names_or_objs = {
            'M0': m0file,
            'M1': m1file,
            'M2': m2file,
            'M3': m3file,
            'M4': m4file
        }

        # model components are interpolated to 2nd order
        for key in ['M0', 'M1', 'M2', 'M3', 'M4']:
            phase, wave, values = sncosmo.read_griddata_ascii(
                p2 + names_or_objs[key])
            values *= self._SCALE_FACTOR
            # self._model[key] = Spline2d(phase, wave, values, kx=2, ky=2)
            self._model[key] = BicubicInterpolator(phase, wave, values)

            # The "native" phases and wavelengths of the model are those
            # of the first model component.
            if key == 'M0':
                self._phase = phase
                self._wave = wave
    def read_SED(self, ascii_file):
        """
        Reads in an ascii file detailing the time evolution of an SED. Must be
        in the following format, 3 columns: phase, wavelength, flux.

        This will also set the source model and redshift the model according to
        initialization parameters.

        Parameters:
        -----------
            ascii_file: str
                string containing the path to the ascii file containing the
                SED evolution.

        """
        # Sanity to check to make sure the provided string indeed points to a
        # file.
        if not os.path.isfile(ascii_file):
            raise IOError("Could not find SED ascii file %s" % (ascii_file))
        # Read in the SED text file with sncosmo for use with it's Model API.
        self.sed_phase, self.sed_wave, self.sed_flux = read_griddata_ascii(
            ascii_file)
        # Make the source model and set the transient Model to be used for
        # light curve generation and observation.
        self.make_model()
        # Given the redshifted SED set the transient duration.
        self.transient_duration = (self.redshifted_model.maxtime() -
                                   self.redshifted_model.mintime())
    def model_IIP_nugent(self):
        """
        """
        sncosmo.get_source('nugent-sn2p', version='1.2')
        p, w, f = sncosmo.read_griddata_ascii(
            os.path.join(sncosmo.builtins.get_cache_dir(),
                         'sncosmo/models/nugent/sn2p_flux.v1.2.dat')
        )
        mask = (p < 130)

        return sncosmo.Model(source=sncosmo.TimeSeriesSource(p[mask], w, f[mask]),
                             effects=[sncosmo.CCM89Dust()],
                             effect_names=['host'],
                             effect_frames=['rest'])
Exemple #9
0
def addCCSpec(snType,
              sed=None,
              waveRange=None,
              phase=None,
              wave=None,
              flux=None,
              specList=None,
              specName=None):
    if not sed:
        if not phase and not wave and not flux:
            print('Need SED file or phase,wave,flux arrays (found none).')
            sys.exit()
    else:
        phase, wave, flux = sncosmo.read_griddata_ascii(sed)
Exemple #10
0
def _getWave(sedfile,bandDict,colors):
    phase,wave,flux=sncosmo.read_griddata_ascii(sedfile)
    for color in colors:
        wave1=sncosmo.get_bandpass(bandDict[color[0]]).wave
        wave2=sncosmo.get_bandpass(bandDict[color[-1]]).wave
        if wave1[0]>=wave[0] and wave1[-1]<=wave[-1]:
            if wave2[0]>=wave[0] and wave2[-1]<=wave[-1]:
                if wave2[0]>=_IRleftBound:
                    wave=wave[wave<wave2[0]]
            else:
                wave=wave[wave<wave2[0]]
        else:
            wave=wave[wave>wave1[-1]]
    return(wave)
Exemple #11
0
def test_write_griddata_ascii():

    x0 = np.array([0., 1.])
    x1 = np.array([0., 1., 2.])
    y = np.zeros((2, 3))

    f = six.StringIO()
    sncosmo.write_griddata_ascii(x0, x1, y, f)

    # Read it back
    f.seek(0)
    x0_in, x1_in, y_in = sncosmo.read_griddata_ascii(f)
    assert_allclose(x0_in, x0)
    assert_allclose(x1_in, x1)
    assert_allclose(y_in, y)
Exemple #12
0
def test_write_griddata_ascii():

    x0 = np.array([0., 1.])
    x1 = np.array([0., 1., 2.])
    y = np.zeros((2, 3))

    f = six.StringIO()
    sncosmo.write_griddata_ascii(x0, x1, y, f)

    # Read it back
    f.seek(0)
    x0_in, x1_in, y_in = sncosmo.read_griddata_ascii(f)
    assert_allclose(x0_in, x0)
    assert_allclose(x1_in, x1)
    assert_allclose(y_in, y)
    def model_generic_MultiSource(self, files=None, **kwargs):
        """
        """
        data_sed = {'p': [], 'w': [], 'f': []}
        for sed_file in sed_files[0]:
            p_, w_, f_ = sncosmo.read_griddata_ascii(sed_file)
            data_sed['p'].append(p_)
            data_sed['w'].append(w_)
            data_sed['f'].append(f_)

        source = simsurvey.MultiSource(data_sed['p'], data_sed['w'], data_sed['f'])
        return sncosmo.Model(source=source,
                             effects=[sncosmo.CCM89Dust()],
                             effect_names=['host'],
                             effect_frames=['rest'])
Exemple #14
0
def test_read_griddata_ascii():

    # Write a temporary test file.
    f = six.StringIO()
    f.write("0. 0. 0.\n"
            "0. 1. 0.\n"
            "0. 2. 0.\n"
            "1. 0. 0.\n"
            "1. 1. 0.\n"
            "1. 2. 0.\n")
    f.seek(0)

    x0, x1, y = sncosmo.read_griddata_ascii(f)

    assert_allclose(x0, np.array([0., 1.]))
    assert_allclose(x1, np.array([0., 1., 2.]))
Exemple #15
0
def test_read_griddata_ascii():

    # Write a temporary test file.
    f = six.StringIO()
    f.write("0. 0. 0.\n"
            "0. 1. 0.\n"
            "0. 2. 0.\n"
            "1. 0. 0.\n"
            "1. 1. 0.\n"
            "1. 2. 0.\n")
    f.seek(0)

    x0, x1, y = sncosmo.read_griddata_ascii(f)

    assert_allclose(x0, np.array([0., 1.]))
    assert_allclose(x1, np.array([0., 1., 2.]))
Exemple #16
0
def createSNSED(filename,rescale=False):
    """
    Creates an sncosmo.Source object from a timeseries source (flux in photons/s/cm^2 as in sncosmo,assumes the file
    is in ergs though)

    :param filename: Name of file containing the timerseries source
    :type filename: str
    :param rescale: If you want to rescale the flux so that it is in photons at the end instead of ergs (divides by ergs/AA
    :type rescale: Boolean, optional
    :returns: ncosmo.Source object
    """
    phase,wave,flux=sncosmo.read_griddata_ascii(filename)
    if rescale:
        for i in range( len(phase) ) :
            flux[i]=flux[i]/sncosmo.constants.HC_ERG_AA
    return(sncosmo.TimeSeriesSource(phase,wave,flux,zero_before=True,name=os.path.basename(filename)))
    #return(snSource(phase,wave,flux,name=os.path.basename(filename)))
Exemple #17
0
def test_bicubic_interpolator_vs_snfit():
    datadir = os.path.join(os.path.dirname(__file__), "data")

    # created by running generate script in `misc` directory
    fname_input = os.path.join(datadir, "interpolation_test_input.dat")
    fname_evalx = os.path.join(datadir, "interpolation_test_evalx.dat")
    fname_evaly = os.path.join(datadir, "interpolation_test_evaly.dat")

    # result file was created by running snfit software Grid2DFunction
    fname_result = os.path.join(datadir, "interpolation_test_result.dat")

    # load arrays
    x, y, z = sncosmo.read_griddata_ascii(fname_input)
    xp = np.loadtxt(fname_evalx)
    yp = np.loadtxt(fname_evaly)
    result = np.loadtxt(fname_result)

    f = BicubicInterpolator(x, y, z)
    assert_allclose(f(xp, yp), result, rtol=1e-5)
Exemple #18
0
def test_bicubic_interpolator_vs_snfit():
    datadir = os.path.join(os.path.dirname(__file__), "data")

    # created by running generate script in `misc` directory
    fname_input = os.path.join(datadir, "interpolation_test_input.dat")
    fname_evalx = os.path.join(datadir, "interpolation_test_evalx.dat")
    fname_evaly = os.path.join(datadir, "interpolation_test_evaly.dat")

    # result file was created by running snfit software Grid2DFunction
    fname_result = os.path.join(datadir, "interpolation_test_result.dat")

    # load arrays
    x, y, z = sncosmo.read_griddata_ascii(fname_input)
    xp = np.loadtxt(fname_evalx)
    yp = np.loadtxt(fname_evaly)
    result = np.loadtxt(fname_result)

    f = BicubicInterpolator(x, y, z)
    assert_allclose(f(xp, yp), result, rtol=1e-5)
Exemple #19
0
def test_salt2source_timeseries_vs_snfit():
    """Test timeseries output from SALT2Source vs pregenerated timeseries
    from snfit (SALT2 software)."""

    source = sncosmo.get_source("salt2", version="2.4")  # fixed version
    model = sncosmo.Model(source)

    dirname = os.path.join(os.path.dirname(__file__), "data")

    for fname in [
            'salt2_timeseries_1.dat', 'salt2_timeseries_2.dat',
            'salt2_timeseries_3.dat', 'salt2_timeseries_4.dat'
    ]:
        f = open(os.path.join(dirname, fname), 'r')
        meta = read_header(f)
        time, wave, fluxref = sncosmo.read_griddata_ascii(f)
        f.close()

        # The output from snfit's Salt2Model.SpectrumFlux() has a
        # different definition than sncosmo's model.flux() by a factor
        # of a^2. snfit's definition is the rest-frame flux but at a
        # blue-shifted wavelength.  (There is no correction for photon
        # energy or time dilation. These corrections are made in the
        # integration step.)
        a = 1. / (1. + meta['Redshift'])
        fluxref *= a**2

        model.set(z=meta['Redshift'],
                  t0=meta['DayMax'],
                  x0=meta['X0'],
                  x1=meta['X1'],
                  c=meta['Color'])
        flux = model.flux(time, wave)

        # super good agreement!
        assert_allclose(flux, fluxref, rtol=1e-13)
Exemple #20
0
########################################################################
# ... and that's all that we need to define!: A couple class attributes
# (``_param_names`` and ``param_names_latex``, an ``__init__`` method,
# and a ``_flux`` method. The ``_flux`` method is guaranteed to be passed
# numpy arrays for phase and wavelength.
#
# We can now initialize an instance of this source from two spectral time
# series:

#Just as an example, we'll use some undocumented functionality in
# sncosmo to download the Nugent Ia and 2p templates. Don't rely on this
# the `DATADIR` object, or these paths in your code though, as these are
# subject to change between version of sncosmo!
from sncosmo.builtins import DATADIR
phase1, wave1, flux1 = sncosmo.read_griddata_ascii(
    DATADIR.abspath('models/nugent/sn1a_flux.v1.2.dat'))
phase2, wave2, flux2 = sncosmo.read_griddata_ascii(
    DATADIR.abspath('models/nugent/sn2p_flux.v1.2.dat'))

# In our __init__ method we defined above, the two fluxes need to be on
# the same grid, so interpolate the second onto the first:
flux2_interp = RectBivariateSpline(phase2, wave2, flux2)(phase1, wave1)

source = ComboSource(phase1, wave1, flux1, flux2_interp, name='sn1a+sn2p')

##########################################################################
# We can get a summary of the Source we created:

print(source)

##########################################################################
Exemple #21
0
def extendCC(colorTable,colorCurveDict,snType,outFileLoc='.',bandDict=_filters,colorExtreme='median',colors=None,zpsys='AB',
             sedlist=None,showplots=None,verbose=True,UVoverwrite=False,IRoverwrite=True,specList=None,specName=None):
    """
    Function used at top level to extend a core-collapse SED.

    :param colorTable: Colortable made by colorCalc.curveToColor
    :type colorTable: astropy.Table
    :param colorCurveDict: Dictionary of color curves, such as made by fitColorCurve
    :type colorCurveDict: dict
    :param snType: SN classification for SED(s)
    :type snType: str
    :param outFileLoc:  Place you want the new SED to be saved, default current directory
    :type outFileLoc: str,optional
    :param bandDict: sncosmo bandpass for each band used in the fitting/table generation
    :type bandDict: dict,optional
    :param colorExtreme: 'blue,'median','red' describes which curve extreme to use
    :type colorExtreme: str,optional
    :param colors: Colors you would like to use for extrapolation
    :type colors: list or None,optional
    :param zpsys: Magnitude system
    :type zpsys: str,optional
    :param sedlist: list of SEDs to extrapolate, if None then uses all SEDs in SNDATA_ROOT
    :type sedlist: list or None,optional
    :param showplots: If you would like to see plots as they're extrapolated
    :type showplots: Boolean,optional
    :param verbose: Printing on?
    :type verbose: Boolean, optional
    :param UVoverwrite: Whether you would like to overwrite existing UV data
    :type UVoverwrite: Boolean,options
    :param IRoverwrite: Whether you would like to overwrite existing IR data
    :type IRoverwrite: Boolean,optional
    :param specList: A list of spectra to use in an average
    :type specList: list, optional
    :param specName: The name of a spectrum to use.
    :type specName: str, optional
    :returns: Saves extrapolated SED to outFileLoc, and returns an sncosmo.Source SED from the extrapolated timeseries.
    """
    colorTable=_standardize(colorTable)

    if not isinstance(colorTable,Table):
        raise RuntimeError('Colors argument must be an astropy table.')

    for band in bandDict:
        if not isinstance(bandDict[band],sncosmo.Bandpass):
            bandDict=_bandCheck(bandDict,band)
    if not colors:
        print("No extrapolation colors defined, assuming: ",colorCurveDict.keys())
        colors=[x for x in colorCurveDict.keys() if 'U-' in x]+[x for x in colorCurveDict.keys() if '-J' in x]+[x for x in colorCurveDict.keys() if '-H' in x]+[x for x in colorCurveDict.keys() if '-K' in x]
    else:
        tempColors=[x for x in colors if 'U-' in x]+[x for x in colors if '-J' in x]+[x for x in colors if '-H' in x]+[x for x in colors if '-K' in x]
        if len(tempColors)>4:
            raise RuntimeError("Only can do 4 colors!")


    bands=append([col[0] for col in colors],[col[-1] for col in colors])
    for band in _filters.keys():
        if band not in bandDict.keys() and band in bands:
            bandDict[band]=sncosmo.get_bandpass(_filters[band])
    if not sedlist:
        sedlist = glob.glob(os.path.join(sndataroot,"snsed","NON1A","*.SED"))
    else:
        sedlist=[sedlist] if not isinstance(sedlist,(tuple,list)) else sedlist
        sedlist=[os.path.join(sndataroot,"snsed","NON1A",sed) for sed in sedlist]
    returnList=[]


    for sedfile in sedlist:

        phase,wave,flux=sncosmo.read_griddata_ascii(sedfile)
        #bbWave,blackbody=getBB(phase,wave,flux)
        #blackbody=sncosmo.Model(source=sncosmo.TimeSeriesSource(phase,bbWave,blackbody))

        origWave=_getWave(sedfile,bandDict,colors)



        #phase,wave,flux=sncosmo.read_griddata_ascii(sedfile)
        bbWave,blackbody=getBB(phase,wave,flux,os.path.basename(sedfile)[:-4])


        blackbody=sncosmo.Model(source=sncosmo.TimeSeriesSource(phase,bbWave,blackbody))
        newsedfile=os.path.join(outFileLoc,os.path.basename(sedfile))
        if verbose:
            print("EXTRAPOLATING %s"%os.path.basename(newsedfile))
        once=False
        boundUV=False
        boundIR=False
        bandsDone=[]

        for color in colors:
            if verbose:
                print('     Running %s extrapolation.'%color)
            if color[0] not in bandDict.keys():
                raise RuntimeError('Band "%s" defined in color "%s", but band is not defined.')
            if color[-1] not in bandDict.keys():
                raise RuntimeError('Band "%s" defined in color "%s", but band is not defined.')


            extremeColors=dict([])

            extremeColors['blue'],extremeColors['median'],extremeColors['red']=_getExtremes(colorCurveDict[color]['time'],colorCurveDict[color][color],colorTable,color)
            if sncosmo.get_bandpass(_filters[color[0]]).wave_eff>_UVrightBound:
                shiftedCurve=_shiftCurve(colorCurveDict[color]['time'],extremeColors,blackbody,color,zpsys)
            else:
                shiftedCurve=extremeColors
            tempMask=colorTable[color].mask

            colorTable[color].mask=tempMask
            if once:
                sedfile=newsedfile
            tempTable=colorTable[~colorTable[color].mask]
            UV,IR=_extrapolatesed(sedfile,newsedfile,color,tempTable,colorCurveDict[color]['time'],shiftedCurve[colorExtreme], bandDict,zpsys,bandsDone,UVoverwrite,IRoverwrite,niter=50)
            if UV:
                boundUV=True
                bandsDone.append(color[0])
            if IR:
                boundIR=True
                bandsDone.append(color[-1])
            once=True

        #_addCCSpec(snType,newsedfile,origWave,specList,specName)
        #phase,wave,flux=sncosmo.read_griddata_ascii(newsedfile)
        #temp=sncosmo.Model(sncosmo.TimeSeriesSource(phase,wave,flux))
        #for col in [('sdss::r','paritel::j'),('sdss::r','paritel::h'),('sdss::r','paritel::ks')]:
        #    print(temp.color(col[0],col[1],'vega',0),blackbody.color(col[0],col[1],'vega',0))

        if showplots:
            plotSED(newsedfile,day=showplots)
            plt.show()
            plt.close()
        if boundUV:
            _boundUVsed(newsedfile)
        if boundIR:
            _boundIRsed(newsedfile)
        if verbose:
            print("     Done with %s.\a\a\a"%os.path.basename(sedfile))
        returnList.append(createSNSED(newsedfile))

    if len(returnList)>1:
        return returnList
    return returnList[0]
Exemple #22
0
def _addCCSpec(snType, sedFile, oldWave, specList=None, specName=None):
    phase, newWave, flux = sncosmo.read_griddata_ascii(sedFile)
    wave = np.append(newWave[newWave < oldWave[0]],
                     newWave[newWave > oldWave[-1]])
    if len(wave) == 0:
        return (flux)
    #flux=flux[:][newWave==wave]
    if specList:
        spec = createAveSpec(specList)
    elif specName:
        spec = os.path.join(__dir__, 'data', 'spectra', specName)
        allSpec = _readSpec(spec)
    else:
        tempInd, tempVal = _find_nearest(phase, 0)
        if snType == 'II':
            snType = 'IIP'
        allSpec, bestConst = _findBest(snType, newWave, flux[tempInd])
        #spec=os.path.join(__dir__,'data','spectra',_defaultSpec[snType])
        #allSpec=_readSpec(spec)

    x = [float(x[2:]) for x in allSpec.colnames if x != 'wave']
    y = allSpec['wave']
    allSpec.remove_column('wave')

    func = interp2d(x, y, np.array([list(r) for r in np.array(allSpec)]))
    tempFlux = np.transpose(
        func(phase[phase >= x[0]][phase[phase >= x[0]] <= x[-1]],
             newWave[newWave > 4000][newWave[newWave > 4000] < 7500]))
    finalFlux = np.transpose(
        func(phase[phase >= x[0]][phase[phase >= x[0]] <= x[-1]],
             wave[wave >= y[0]][wave[wave >= y[0]] <= y[-1]]))
    if np.max(np.max(finalFlux)) == 0:
        return
    #if os.path.basename(sedFile)=='SDSS-015339.SED':
    #	print(finalFlux)
    #	print(wave[wave>=y[0]][wave[wave>=y[0]]<=y[-1]])
    #	sys.exit()

    splines = []
    for p in phase[phase >= x[0]][phase[phase >= x[0]] <= x[-1]]:

        ind = np.where(phase == p)[0][0]
        mySpline = spl(
            newWave[newWave > 4000][newWave[newWave > 4000] < 7500],
            flux[ind][newWave < 7500][newWave[newWave < 7500] > 4000],
            k=5,
            ext=1)
        tempSpline = mySpline(
            newWave[newWave < 7500][newWave[newWave < 7500] > 4000])
        splines.append(
            np.log10(
                flux[ind][newWave < 7500][newWave[newWave < 7500] > 4000] /
                tempSpline))

    splines = np.array(splines)
    waves = wave[wave >= y[0]][wave[wave >= y[0]] <= y[-1]]
    for i in range(len(phase[phase >= x[0]][phase[phase >= x[0]] <= x[-1]])):
        #const1=math.fabs(np.max(splines[i])/np.max(tempFlux[i]))

        #const2=math.fabs(np.min(splines[i])/np.max(tempFlux[i]))
        const = minimize(_specChi,
                         np.array([bestConst]),
                         args=(splines[i], tempFlux[i])).x
        #const=np.nanmedian([math.fabs(k) for k in splines[i]/tempFlux[i]])
        finalFlux[i] *= const
        if i == 4:
            final = const
        #if tempFlux[i][0]>splines[i][0]:
        #	constMinus=tempFlux[i][0]-splines[i][0]
        #	finalFlux[i]-=constMinus
        #else:
        #	constMinus=splines[i][0]-tempFlux[i][0]
        #	tempFlux[i]+=constMinus
        #splines[i]+=finalFlux[i]
        ind = np.where(phase == phase[phase >= x[0]][
            phase[phase >= x[0]] <= x[-1]][i])[0][0]
        for j in range(len(waves)):
            ind2 = np.where(newWave == waves[j])[0][0]
            flux[ind][ind2] = max(0, flux[ind][ind2] + finalFlux[i][j])
    #fig=plt.figure()
    #ax=fig.gca()
    #ax.plot(newWave[newWave<7500][newWave[newWave<7500]>4000],tempFlux[4]*const)
    #ax.plot(newWave[newWave<7500][newWave[newWave<7500]>4000],splines[4])
    #plt.savefig('test_'+os.path.basename(sedFile[:-3])+'pdf',format='pdf',overwrite=True)
    #plt.close()
    sncosmo.write_griddata_ascii(phase, newWave, flux, sedFile)
    return
Exemple #23
0
def _getWave(sedfile):
    phase, wave, flux = sncosmo.read_griddata_ascii(sedfile)
    return (wave)
########################################################################
# ... and that's all that we need to define!: A couple class attributes
# (``_param_names`` and ``param_names_latex``, an ``__init__`` method,
# and a ``_flux`` method. The ``_flux`` method is guaranteed to be passed
# numpy arrays for phase and wavelength.
#
# We can now initialize an instance of this source from two spectral time
# series:

#Just as an example, we'll use some undocumented functionality in
# sncosmo to download the Nugent Ia and 2p templates. Don't rely on this
# the `DATADIR` object, or these paths in your code though, as these are
# subject to change between version of sncosmo!
from sncosmo.builtins import DATADIR
phase1, wave1, flux1 = sncosmo.read_griddata_ascii(
    DATADIR.abspath('models/nugent/sn1a_flux.v1.2.dat'))
phase2, wave2, flux2 = sncosmo.read_griddata_ascii(
    DATADIR.abspath('models/nugent/sn2p_flux.v1.2.dat'))

# In our __init__ method we defined above, the two fluxes need to be on
# the same grid, so interpolate the second onto the first:
flux2_interp = RectBivariateSpline(phase2, wave2, flux2)(phase1, wave1)

source = ComboSource(phase1, wave1, flux1, flux2_interp, name='sn1a+sn2p')


##########################################################################
# We can get a summary of the Source we created:

print(source)
Exemple #25
0
def plotSED(sedfile,
            day,
            normalize=False,
            MINWAVE=1200,
            MAXWAVE=25000,
            saveFig=True,
            figFile=None,
            showPlot=False,
            **kwargs):
    """
    Simple plotting function to visualize the SED file.

    :param sedfile: SED filename to read
    :type sedfile: str
    :param day: The day you want to plot
    :type day: double
    :param normalize: Boolean to normalize the data
    :type normalize: Boolean
    :param MINWAVE: Allows user to plot in a specific window, left edge
    :type MINWAVE: float
    :param MAXWAVE: Allows user to plot in a specific window, right edge
    :type MAXWAVE: float
    :returns: None
    """

    dlist, wlist, flist = sncosmo.read_griddata_ascii(sedfile)
    ind, dayVal = _find_nearest(dlist, day)
    print(dayVal)
    fig = plt.figure()
    ax = fig.gca()

    if MINWAVE:
        idx1, val = _find_nearest(wlist, MINWAVE)
    else:
        idx1 = None
    if MAXWAVE:
        idx2, val = _find_nearest(wlist, MAXWAVE)
    else:
        idx2 = None

    if normalize:
        ax.plot(wlist[idx1:idx2],
                flist[ind][idx1:idx2] / flist[ind][idx1:idx2].max(), **kwargs)
    else:
        ax.plot(wlist[idx1:idx2],
                flist[ind][idx1:idx2],
                label=str(dayVal),
                **kwargs)

    if 'xlabel' in kwargs.keys():
        xlabel = kwargs.pop('xlabel')
    else:
        xlabel = 'Rest Wavelength ($\AA$)'
    if 'ylabel' in kwargs.keys():
        ylabel = kwargs.pop('ylabel')
    else:
        ylabel = 'Flux'
    if 'title' in kwargs.keys():
        title = kwargs.pop('title')
    else:
        title = os.path.basename(sedfile) + " Extrapolated--Phase=" + str(
            dayVal)
    ax.set_title(title)

    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

    if saveFig:
        if not figFile:
            figFile = os.path.basename(sedfile)[:-3] + 'pdf'
        plt.savefig(figFile, format='pdf', overwrite=True)
    if showPlot:
        plt.show()
    return