Esempio n. 1
0
def test_SED_sub():
    """Check that SEDs subtract like I think they should...
    """
    for z in [0, 0.2, 0.4]:
        a = galsim.SED(galsim.LookupTable([1,2,3,4,5], [1.1,2.2,3.3,4.4,5.5]),
                       wave_type='nm', flux_type='fphotons')
        b = galsim.SED(galsim.LookupTable([1.1,2.2,3.0,4.4,5.5], [1.11,2.22,3.33,4.44,5.55]),
                       wave_type='nm', flux_type='fphotons')
        if z != 0:
            a = a.atRedshift(z)
            b = b.atRedshift(z)
        c = a-b
        np.testing.assert_almost_equal(c.blue_limit, np.max([a.blue_limit, b.blue_limit]), 10,
                                       err_msg="Found wrong blue limit in SED.__sub__")
        np.testing.assert_almost_equal(c.red_limit, np.min([a.red_limit, b.red_limit]), 10,
                                       err_msg="Found wrong red limit in SED.__sub__")
        np.testing.assert_almost_equal(c(c.blue_limit), a(c.blue_limit) - b(c.blue_limit), 10,
                                       err_msg="Wrong difference in SED.__sub__")
        np.testing.assert_almost_equal(c(c.red_limit), a(c.red_limit) - b(c.red_limit), 10,
                                       err_msg="Wrong difference in SED.__sub__")
        x = 0.5 * (c.blue_limit + c.red_limit)
        np.testing.assert_almost_equal(c(x), a(x) - b(x), 10,
                                       err_msg="Wrong difference in SED.__sub__")
        np.testing.assert_almost_equal(c.redshift, a.redshift, 10,
                                       err_msg="Wrong redshift in SED difference")

    try:
        # Subracting two SEDs with different redshifts should fail.
        d = b.atRedshift(0.1)
        np.testing.assert_raises(ValueError, b.__sub__, d)
    except ImportError:
        print('The assert_raises tests require nose')
Esempio n. 2
0
def read_ps(galsim_dir=None, scale=1.):
    """Read in a Power Spectrum stored in the GalSim repository.

    Returns a galsim.PowerSpectrum object.
    """
    import os
    if galsim_dir is None:
        raise ValueError(
            "You must supply a directory for your GalSim install via the `galsim_dir` kwarg."
        )
    file = os.path.join(galsim_dir, 'examples', 'data',
                        'cosmo-fid.zmed1.00_smoothed.out')
    if scale == 1.:
        tab_ps = galsim.LookupTable(file=file, interpolant='linear')
    else:
        data = np.loadtxt(file).transpose()
        if data.shape[0] != 2:
            raise ValueError(
                "File %s provided for LookupTable does not have 2 columns" %
                file)
        x = data[0]
        f = data[1]
        f *= scale
        tab_ps = galsim.LookupTable(x=x, f=f, interpolant='linear')

    # Put this table into an E-mode power spectrum and return
    ret = galsim.PowerSpectrum(tab_ps, None, units=galsim.radians)
    return ret
Esempio n. 3
0
def test_Bandpass_wave_type():
    """Check that `wave_type='ang'` works in Bandpass.__init__
    """
    import time
    t1 = time.time()

    a0 = galsim.Bandpass(os.path.join(datapath, 'LSST_r.dat'))
    a1 = galsim.Bandpass(os.path.join(datapath, 'LSST_r.dat'), wave_type='ang')

    np.testing.assert_approx_equal(a0.red_limit, a1.red_limit*10,
                                   err_msg="Bandpass.red_limit doesn't respect wave_type")
    np.testing.assert_approx_equal(a0.blue_limit, a1.blue_limit*10,
                                   err_msg="Bandpass.blue_limit doesn't respect wave_type")
    np.testing.assert_approx_equal(a0.effective_wavelength, a1.effective_wavelength*10,
                                   err_msg="Bandpass.effective_wavelength doesn't respect"
                                           +" wave_type")

    b0 = galsim.Bandpass(galsim.LookupTable([1,2,3,4,5], [1,2,3,4,5]))
    b1 = galsim.Bandpass(galsim.LookupTable([10,20,30,40,50], [1,2,3,4,5]), wave_type='ang')
    np.testing.assert_approx_equal(b0.red_limit, b1.red_limit,
                                   err_msg="Bandpass.red_limit doesn't respect wave_type")
    np.testing.assert_approx_equal(b0.blue_limit, b1.blue_limit,
                                   err_msg="Bandpass.blue_limit doesn't respect wave_type")
    np.testing.assert_approx_equal(b0.effective_wavelength, b1.effective_wavelength,
                                   err_msg="Bandpass.effective_wavelength doesn't respect"
                                           +" wave_type")
    np.testing.assert_array_almost_equal(b0([1,2,3,4,5]), b1([1,2,3,4,5]), decimal=7,
                               err_msg="Bandpass.__call__ doesn't respect wave_type")

    t2 = time.time()
    print 'time for %s = %.2f'%(funcname(),t2-t1)
Esempio n. 4
0
def test_Bandpass_wave_type():
    """Check that `wave_type='ang'` works in Bandpass.__init__
    """
    # Also check with and without explicit directory
    a0 = galsim.Bandpass(os.path.join(datapath, 'LSST_r.dat'), wave_type='nm')
    a1 = galsim.Bandpass('LSST_r.dat', wave_type='ang')

    np.testing.assert_approx_equal(a0.red_limit, a1.red_limit*10,
                                   err_msg="Bandpass.red_limit doesn't respect wave_type")
    np.testing.assert_approx_equal(a0.blue_limit, a1.blue_limit*10,
                                   err_msg="Bandpass.blue_limit doesn't respect wave_type")
    np.testing.assert_approx_equal(a0.effective_wavelength, a1.effective_wavelength*10,
                                   err_msg="Bandpass.effective_wavelength doesn't respect"
                                           +" wave_type")

    b0 = galsim.Bandpass(galsim.LookupTable([1,2,3,4,5], [1,2,3,4,5]), wave_type='nm')
    b1 = galsim.Bandpass(galsim.LookupTable([10,20,30,40,50], [1,2,3,4,5]), wave_type='ang')
    np.testing.assert_approx_equal(b0.red_limit, b1.red_limit,
                                   err_msg="Bandpass.red_limit doesn't respect wave_type")
    np.testing.assert_approx_equal(b0.blue_limit, b1.blue_limit,
                                   err_msg="Bandpass.blue_limit doesn't respect wave_type")
    np.testing.assert_approx_equal(b0.effective_wavelength, b1.effective_wavelength,
                                   err_msg="Bandpass.effective_wavelength doesn't respect"
                                           +" wave_type")
    np.testing.assert_array_almost_equal(b0([1,2,3,4,5]), b1([1,2,3,4,5]), decimal=7,
                               err_msg="Bandpass.__call__ doesn't respect wave_type")
Esempio n. 5
0
def test_fnu_vs_flambda():
    import time
    t1 = time.time()

    c = 2.99792458e17  # speed of light in nm/s
    h = 6.62606957e-27  # Planck's constant in erg seconds
    k = 1.3806488e-16  # Boltzmann's constant ergs per Kelvin
    nm_in_cm = 1e7

    # read these straight from Wikipedia
    def rayleigh_jeans_fnu(T, w):
        nu = c / w
        return 2 * nu**2 * k * T / c**2 * nm_in_cm**2  # should have units of erg/s/cm^2/Hz

    def rayleigh_jeans_flambda(T, w):
        return 2 * c * k * T / w**4 * nm_in_cm**2  # should have units of erg/s/cm^2/nm

    waves = np.linspace(500, 1000, 100)
    fnu = rayleigh_jeans_fnu(5800, waves)
    flambda = rayleigh_jeans_flambda(5800, waves)

    for z in [0, 0.2, 0.4]:
        sed1 = galsim.SED(galsim.LookupTable(waves, fnu), flux_type='fnu')
        sed2 = galsim.SED(galsim.LookupTable(waves, flambda),
                          flux_type='flambda')
        if z != 0:
            sed1 = sed1.atRedshift(z)
            sed2 = sed2.atRedshift(z)
        zwaves = waves * (1.0 + z)
        np.testing.assert_array_almost_equal(
            sed1(zwaves) / sed2(zwaves),
            np.ones(len(zwaves)),
            10,
            err_msg="Check fnu & flambda consistency.")

        # Now also check that wavelengths in Angstroms work.
        waves_ang = waves * 10
        sed3 = galsim.SED(galsim.LookupTable(waves_ang, fnu),
                          flux_type='fnu',
                          wave_type='Ang')
        sed4 = galsim.SED(galsim.LookupTable(waves_ang, flambda),
                          flux_type='flambda',
                          wave_type='Ang')
        if z != 0:
            sed3 = sed3.atRedshift(z)
            sed4 = sed4.atRedshift(z)
        np.testing.assert_array_almost_equal(
            sed1(zwaves) / sed3(zwaves),
            np.ones(len(zwaves)),
            10,
            err_msg="Check nm and Ang SED wavelengths consistency.")
        np.testing.assert_array_almost_equal(
            sed2(zwaves) / sed4(zwaves),
            np.ones(len(zwaves)),
            10,
            err_msg="Check nm and Ang SED wavelengths consistency.")

    t2 = time.time()
    print 'time for %s = %.2f' % (funcname(), t2 - t1)
Esempio n. 6
0
def test_from_func():
    """Test the LookupTable.from_func factory function"""
    x_min = 2
    x_max = 200

    # Linear interpolation
    x1 = np.linspace(x_min, x_max, 2000)
    f1 = [x**3 for x in x1]
    tab1 = galsim.LookupTable(x1, f1, interpolant='linear')
    tab2 = galsim.LookupTable.from_func(lambda x: x**3,
                                        x_min,
                                        x_max,
                                        interpolant='linear')
    print('tab1 = ', tab1, tab1(10))
    print('tab2 = ', tab2, tab2(10))

    # Spline interpolation
    tab3 = galsim.LookupTable(x1, f1)
    tab4 = galsim.LookupTable.from_func(lambda x: x**3, x_min, x_max)
    print('tab3 = ', tab3, tab3(10))
    print('tab4 = ', tab4, tab4(10))

    # Log interpolation
    x5 = np.exp(np.linspace(np.log(x_min), np.log(x_max), 2000))
    f5 = [x**3 for x in x5]
    tab5 = galsim.LookupTable(x5, f5, x_log=True, f_log=True)
    tab6 = galsim.LookupTable.from_func(lambda x: x**3,
                                        x_min,
                                        x_max,
                                        x_log=True,
                                        f_log=True)
    print('tab5 = ', tab5, tab5(10))
    print('tab6 = ', tab6, tab6(10))

    test_x_vals = [2.641, 39.85, 81.23125]
    for x in test_x_vals:
        truth = x**3
        f1 = tab1(x)
        f2 = tab2(x)
        f3 = tab3(x)
        f4 = tab4(x)
        f5 = tab5(x)
        f6 = tab6(x)
        print(truth, f1, f2, f3, f4, f5, f6)
        np.testing.assert_almost_equal(f1 / truth, 1.0, decimal=2)
        np.testing.assert_almost_equal(
            f2 / truth, 1.0, 2,
            "LookupTable.from_func (linear) gave wrong answer")
        np.testing.assert_almost_equal(f3 / truth, 1.0, decimal=6)
        np.testing.assert_almost_equal(
            f4 / truth, 1.0, 6,
            "LookupTable.from_func (spline) gave wrong answer")
        np.testing.assert_almost_equal(f5 / truth, 1.0, decimal=11)
        np.testing.assert_almost_equal(
            f6 / truth, 1.0, 11,
            "LookupTable.from_func (log-log) gave wrong answer")
    do_pickle(tab2)
    do_pickle(tab4)
    do_pickle(tab6)
Esempio n. 7
0
def test_SED_init():
    """Check that certain invalid SED initializations are trapped.
    """
    # These fail.
    assert_raises(ValueError, galsim.SED, spec="'eggs'", wave_type='A', flux_type='flambda')
    assert_raises(ValueError, galsim.SED, spec='blah', wave_type='nm', flux_type='flambda')
    assert_raises(ValueError, galsim.SED, spec='wave+',wave_type='nm', flux_type='flambda')
    assert_raises(ValueError, galsim.SED, spec='somewhere/a/file', wave_type='nm',
                  flux_type='flambda')
    assert_raises(ValueError, galsim.SED, spec='/somewhere/a/file', wave_type='nm',
                  flux_type='flambda')
    assert_raises(ValueError, galsim.SED, spec=lambda w:1.0, wave_type='bar', flux_type='flambda')
    assert_raises(TypeError, galsim.SED, spec=lambda w:1.0, wave_type='nm')
    assert_raises(TypeError, galsim.SED, spec=lambda w:1.0, flux_type='bar')
    assert_raises(TypeError, galsim.SED, spec=lambda w:1.0)
    assert_raises(ValueError, galsim.SED, spec='wave', wave_type=units.Hz, flux_type='2')
    assert_raises(galsim.GalSimSEDError, galsim.SED, 1.0, 'nm', 'fphotons')
    # These should succeed.
    galsim.SED(spec='wave', wave_type='nm', flux_type='flambda')
    galsim.SED(spec='wave/wave', wave_type='nm', flux_type='flambda')
    galsim.SED(spec=lambda w:1.0, wave_type='nm', flux_type='flambda')
    galsim.SED(spec='1./(wave-700)', wave_type='nm', flux_type='flambda')
    galsim.SED(spec='wave', wave_type=units.nm, flux_type='flambda')
    galsim.SED(spec='wave', wave_type=units.Hz, flux_type='flambda')
    galsim.SED(spec='wave', wave_type=units.Hz, flux_type='fphotons')
    galsim.SED(spec='wave', wave_type=units.Hz, flux_type=units.erg/(units.s*units.nm*units.m**2))
    galsim.SED(spec='wave', wave_type=units.Hz, flux_type=units.erg/(units.s*units.Hz*units.m**2))
    galsim.SED(spec='wave', wave_type=units.Hz,
               flux_type=units.astrophys.photon/(units.s * units.Hz * units.m**2))
    galsim.SED(spec='wave', wave_type=units.Hz, flux_type='1')
    galsim.SED(spec='wave', wave_type=units.Hz, flux_type=units.dimensionless_unscaled)

    # Also check for invalid calls
    foo = np.arange(10.)+1.
    sed = galsim.SED(galsim.LookupTable(foo,foo), wave_type=units.Hz, flux_type='flambda')
    assert_raises(ValueError, sed, 0.5)
    assert_raises(ValueError, sed, 12.0)
    assert_raises(ValueError, galsim.SED, '1', 'nm', units.erg/units.s)
    assert_raises(ValueError, galsim.SED, '1', 'nm', '2')

    # Check a few valid calls for when fast=False
    sed = galsim.SED(galsim.LookupTable(foo,foo), wave_type=units.GHz,
                     flux_type=units.erg/(units.s*units.Hz*units.m**2), fast=False)
    sed(1.5*units.GHz)
    sed(3e8/1.5)  # lambda = c/nu = 3e8 m/s / 1.5e9 Hz * 1.e9 nm/m
    sed(3e8/1.5*units.nm)

    # And check the redshift kwarg.
    foo = np.arange(10.)+1.
    sed = galsim.SED(galsim.LookupTable(foo,foo), wave_type='nm', flux_type='flambda', redshift=1.0,
                     fast=False)
    # outside good range of 2->20 should raise ValueError
    assert_raises(ValueError, sed, 1.5)
    assert_raises(ValueError, sed, 24.0)

    sed(3.5)
    sed(3.5*units.nm)
Esempio n. 8
0
def test_SED_calculateMagnitude():
    """ Check that magnitudes work as expected.
    """
    # Test that we can create a zeropoint with an SED, and that magnitudes for that SED are
    # then 0.0
    for z in [0, 0.2, 0.4]:
        sed = galsim.SED(spec='wave', wave_type='nm', flux_type='flambda')
        if z != 0:
            sed = sed.atRedshift(z)
        bandpass = galsim.Bandpass(galsim.LookupTable([1,2,3,4,5], [1,2,3,4,5]),
                                   'nm').withZeropoint(sed)
        np.testing.assert_almost_equal(sed.calculateMagnitude(bandpass), 0.0)
        # Try multiplying SED by 100 to verify that magnitude decreases by 5
        sed *= 100
        np.testing.assert_almost_equal(sed.calculateMagnitude(bandpass), -5.0)
        # Try setting zeropoint to a constant.
        bandpass = galsim.Bandpass(galsim.LookupTable([1,2,3,4,5], [1,2,3,4,5]),
                                   'nm').withZeropoint(6.0)
        np.testing.assert_almost_equal(sed.calculateMagnitude(bandpass),
                                       (sed*100).calculateMagnitude(bandpass)+5.0)
        # Try setting AB zeropoint
        bandpass = (galsim.Bandpass(galsim.LookupTable([1,2,3,4,5], [1,2,3,4,5]), 'nm')
                    .withZeropoint('AB', effective_diameter=640.0, exptime=15.0))
        np.testing.assert_almost_equal(sed.calculateMagnitude(bandpass),
                                       (sed*100).calculateMagnitude(bandpass)+5.0)

        # See if we can set a magnitude.
        sed = sed.withMagnitude(24.0, bandpass)
        np.testing.assert_almost_equal(sed.calculateMagnitude(bandpass), 24.0)

        # Test intended meaning of zeropoint.  I.e., that an object with magnitude equal to the
        # zeropoint will have a flux of 1.0.
        bandpass = galsim.Bandpass(galsim.LookupTable([1,2,3,4,5], [1,2,3,4,5]),
                                   'nm').withZeropoint(24.0)
        sed = sed.withMagnitude(bandpass.zeropoint, bandpass)
        np.testing.assert_almost_equal(sed.calculateFlux(bandpass), 1.0, 10)

    # See if Vega magnitudes work.
    # The following AB/Vega conversions are sourced from
    # http://www.astronomy.ohio-state.edu/~martini/usefuldata.html
    # Almost certainly, the LSST filters and the filters used on this website are not perfect
    # matches, but should give some idea of the expected conversion between Vega magnitudes and AB
    # magnitudes.  The results are consistent to 0.1 magnitudes, which is encouraging, but the true
    # accuracy of the get/set magnitude algorithms is probably much better than this.
    ugrizy_vega_ab_conversions = [0.91, -0.08, 0.16, 0.37, 0.54, 0.634]
    filter_names = 'ugrizy'
    sed = sed.atRedshift(0.0)
    for conversion, filter_name in zip(ugrizy_vega_ab_conversions, filter_names):
        filter_filename = os.path.join(bppath, 'LSST_{0}.dat'.format(filter_name))
        AB_bandpass = (galsim.Bandpass(filter_filename, 'nm')
                       .withZeropoint('AB', effective_diameter=640, exptime=15))
        vega_bandpass = (galsim.Bandpass(filter_filename, 'nm')
                         .withZeropoint('vega', effective_diameter=640, exptime=15))
        AB_mag = sed.calculateMagnitude(AB_bandpass)
        vega_mag = sed.calculateMagnitude(vega_bandpass)
        assert (abs((AB_mag - vega_mag) - conversion) < 0.1)
Esempio n. 9
0
def make_Euclid_filter(res=1.0):
    """ Make a Euclid-like filter (eye-balling Semboloni++13).

    @param res  Resolution in nanometers.
    @return     galsim.Bandpass object.
    """
    x = [550.0, 750.0, 850.0, 900.0]
    y = [0.3, 0.3, 0.275, 0.2]
    tab = galsim.LookupTable(x, y, interpolant='linear')
    w = np.arange(550.0, 900.01, res)
    return galsim.Bandpass(galsim.LookupTable(w, tab(w), interpolant='linear'))
Esempio n. 10
0
def test_SED_add():
    """Check that SEDs add like I think they should...
    """
    import time
    t1 = time.time()

    for z in [0, 0.2, 0.4]:
        a = galsim.SED(galsim.LookupTable([1, 2, 3, 4, 5],
                                          [1.1, 2.2, 3.3, 4.4, 5.5]),
                       flux_type='fphotons')
        b = galsim.SED(galsim.LookupTable([1.1, 2.2, 3.0, 4.4, 5.5],
                                          [1.11, 2.22, 3.33, 4.44, 5.55]),
                       flux_type='fphotons')
        if z != 0:
            a = a.atRedshift(z)
            b = b.atRedshift(z)
        c = a + b
        np.testing.assert_almost_equal(
            c.blue_limit,
            np.max([a.blue_limit, b.blue_limit]),
            10,
            err_msg="Found wrong blue limit in SED.__add__")
        np.testing.assert_almost_equal(
            c.red_limit,
            np.min([a.red_limit, b.red_limit]),
            10,
            err_msg="Found wrong red limit in SED.__add__")
        np.testing.assert_almost_equal(c(c.blue_limit),
                                       a(c.blue_limit) + b(c.blue_limit),
                                       10,
                                       err_msg="Wrong sum in SED.__add__")
        np.testing.assert_almost_equal(c(c.red_limit),
                                       a(c.red_limit) + b(c.red_limit),
                                       10,
                                       err_msg="Wrong sum in SED.__add__")
        x = 0.5 * (c.blue_limit + c.red_limit)
        np.testing.assert_almost_equal(c(x),
                                       a(x) + b(x),
                                       10,
                                       err_msg="Wrong sum in SED.__add__")
        np.testing.assert_almost_equal(c.redshift,
                                       a.redshift,
                                       10,
                                       err_msg="Wrong redshift in SED sum")
    try:
        # Adding together two SEDs with different redshifts should fail.
        d = b.atRedshift(0.1)
        np.testing.assert_raises(ValueError, b.__add__, d)
    except ImportError:
        print 'The assert_raises tests require nose'

    t2 = time.time()
    print 'time for %s = %.2f' % (funcname(), t2 - t1)
Esempio n. 11
0
def test_Bandpass_mul():
    """Check that Bandpasses multiply like I think they should...
    """
    a = galsim.Bandpass(galsim.LookupTable([1,2,3,4,5], [1,2,3,4,5]), 'nm')
    b = galsim.Bandpass(galsim.LookupTable([1.1,2.2,3.0,4.4,5.5], [1.11,2.22,3.33,4.44,5.55]), 'nm')

    # Bandpass * Bandpass
    c = a*b
    np.testing.assert_almost_equal(c.blue_limit, 1.1, 10,
                                   err_msg="Found wrong blue limit in Bandpass.__mul__")
    np.testing.assert_almost_equal(c.red_limit, 5.0, 10,
                                   err_msg="Found wrong red limit in Bandpass.__mul__")
    np.testing.assert_almost_equal(c(3.0), 3.0 * 3.33, 10,
                                   err_msg="Found wrong value in Bandpass.__mul__")
    np.testing.assert_almost_equal(c(1.1), a(1.1)*1.11, 10,
                                   err_msg="Found wrong value in Bandpass.__mul__")
    np.testing.assert_almost_equal(c(5.0), b(5.0)*5, 10,
                                   err_msg="Found wrong value in Bandpass.__mul__")
    np.testing.assert_array_almost_equal(c.wave_list, [1.1, 2, 2.2, 3, 4, 4.4, 5],
                                         err_msg="wrong wave_list in Bandpass.__mul__")

    # Bandpass * fn
    d = lambda w: w**2
    e = c*d
    np.testing.assert_almost_equal(e(3.0), 3.0 * 3.33 * 3.0**2, 10,
                                   err_msg="Found wrong value in Bandpass.__mul__")
    np.testing.assert_array_almost_equal(e.wave_list, [1.1, 2, 2.2, 3, 4, 4.4, 5],
                                         err_msg="wrong wave_list in Bandpass.__mul__")

    # fn * Bandpass
    e = d*c
    np.testing.assert_almost_equal(e(3.0), 3.0 * 3.33 * 3.0**2, 10,
                                   err_msg="Found wrong value in Bandpass.__mul__")
    np.testing.assert_array_almost_equal(e.wave_list, [1.1, 2, 2.2, 3, 4, 4.4, 5],
                                         err_msg="wrong wave_list in Bandpass.__mul__")

    # Bandpass * scalar
    f = b * 1.21
    np.testing.assert_almost_equal(f(3.0), 3.33 * 1.21, 10,
                                   err_msg="Found wrong value in Bandpass.__mul__")
    np.testing.assert_array_almost_equal(f.wave_list, [1.1, 2.2, 3, 4.4, 5.5],
                                         err_msg="wrong wave_list in Bandpass.__mul__")
    do_pickle(f)

    # scalar * Bandpass
    f = 1.21 * a
    np.testing.assert_almost_equal(f(3.0), 3.0 * 1.21, 10,
                                   err_msg="Found wrong value in Bandpass.__mul__")
    np.testing.assert_array_almost_equal(f.wave_list, [1, 2, 3, 4, 5],
                                         err_msg="wrong wave_list in Bandpass.__mul__")
    do_pickle(f)
Esempio n. 12
0
def test_Bandpass_div():
    """Check that Bandpasses multiply like I think they should...
    """
    a_lt = galsim.Bandpass(galsim.LookupTable([1,2,3,4,5], [1,2,3,4,5]), 'nm')
    a_fn = galsim.Bandpass('wave', 'nm', blue_limit=1, red_limit=5)
    b = galsim.Bandpass(galsim.LookupTable([1.1,2.2,3.0,4.4,5.5], [1.11,2.22,3.33,4.44,5.55]), 'nm')

    for a in [a_lt, a_fn]:
        # Bandpass / Bandpass
        c = a/b
        np.testing.assert_almost_equal(c.blue_limit, 1.1, 10,
                                       err_msg="Found wrong blue limit in Bandpass.__div__")
        np.testing.assert_almost_equal(c.red_limit, 5.0, 10,
                                       err_msg="Found wrong red limit in Bandpass.__div__")
        np.testing.assert_almost_equal(c(3.0), 3.0 / 3.33, 10,
                                       err_msg="Found wrong value in Bandpass.__div__")
        np.testing.assert_almost_equal(c(1.1), a(1.1)/1.11, 10,
                                       err_msg="Found wrong value in Bandpass.__div__")
        np.testing.assert_almost_equal(c(5.0), 5/b(5.0), 10,
                                       err_msg="Found wrong value in Bandpass.__div__")
        if a is a_lt:
            combined_wave_list = [1.1, 2, 2.2, 3, 4., 4.4, 5]
        else:
            combined_wave_list = [1.1, 2.2, 3, 4.4, 5]
        np.testing.assert_array_almost_equal(c.wave_list, combined_wave_list,
                                             err_msg="wrong wave_list in Bandpass.__div__")

        # Bandpass / fn
        d = lambda w: w**2
        e = c/d
        np.testing.assert_almost_equal(e(3.0), c(3.0) / 3.0**2, 10,
                                       err_msg="Found wrong value in Bandpass.__div__")
        np.testing.assert_array_almost_equal(e.wave_list, combined_wave_list,
                                             err_msg="wrong wave_list in Bandpass.__div__")

        # Bandpass / scalar
        f = a / 1.21
        np.testing.assert_almost_equal(f(3.0), a(3.0)/1.21, 10,
                                       err_msg="Found wrong value in Bandpass.__div__")
        if a is a_lt:
            np.testing.assert_array_almost_equal(f.wave_list, [1, 2, 3, 4, 5],
                                                 err_msg="wrong wave_list in Bandpass.__div__")
            do_pickle(f)
        else:
            np.testing.assert_array_almost_equal(f.wave_list, [],
                                                 err_msg="wrong wave_list in Bandpass.__div__")

    sed = galsim.SED('1', wave_type='nm', flux_type='1')
    assert_raises(TypeError, a_lt.__div__, sed)
    assert_raises(TypeError, a_fn.__div__, sed)
Esempio n. 13
0
def test_Bandpass_div():
    """Check that Bandpasses multiply like I think they should...
    """
    import time
    t1 = time.time()

    a = galsim.Bandpass(galsim.LookupTable([1,2,3,4,5], [1,2,3,4,5]))
    b = galsim.Bandpass(galsim.LookupTable([1.1,2.2,3.0,4.4,5.5], [1.11,2.22,3.33,4.44,5.55]))
    # Bandpass / Bandpass
    c = a/b
    np.testing.assert_almost_equal(c.blue_limit, 1.1, 10,
                                   err_msg="Found wrong blue limit in Bandpass.__mul__")
    np.testing.assert_almost_equal(c.red_limit, 5.0, 10,
                                   err_msg="Found wrong red limit in Bandpass.__mul__")
    np.testing.assert_almost_equal(c(3.0), 3.0 / 3.33, 10,
                                   err_msg="Found wrong value in Bandpass.__mul__")
    np.testing.assert_almost_equal(c(1.1), a(1.1)/1.11, 10,
                                   err_msg="Found wrong value in Bandpass.__mul__")
    np.testing.assert_almost_equal(c(5.0), 5/b(5.0), 10,
                                   err_msg="Found wrong value in Bandpass.__mul__")
    np.testing.assert_array_almost_equal(c.wave_list, [1.1, 2, 2.2, 3, 4, 4.4, 5],
                                         err_msg="wrong wave_list in Bandpass.__mul__")
    # Bandpass / fn
    d = lambda w: w**2
    e = c/d
    np.testing.assert_almost_equal(e(3.0), 3.0 / 3.33 / 3.0**2, 10,
                                   err_msg="Found wrong value in Bandpass.__mul__")
    np.testing.assert_array_almost_equal(e.wave_list, [1.1, 2, 2.2, 3, 4, 4.4, 5],
                                         err_msg="wrong wave_list in Bandpass.__mul__")
    # fn / Bandpass
    e = d/c
    np.testing.assert_almost_equal(e(3.0), 3.0**2 / (3.0 / 3.33), 10,
                                   err_msg="Found wrong value in Bandpass.__mul__")
    np.testing.assert_array_almost_equal(e.wave_list, [1.1, 2, 2.2, 3, 4, 4.4, 5],
                                         err_msg="wrong wave_list in Bandpass.__mul__")
    # Bandpass / scalar
    f = e / 1.21
    np.testing.assert_almost_equal(f(3.0), (3.0**2 / (3.0 / 3.33)) / 1.21, 10,
                                   err_msg="Found wrong value in Bandpass.__mul__")
    np.testing.assert_array_almost_equal(f.wave_list, [1.1, 2, 2.2, 3, 4, 4.4, 5],
                                         err_msg="wrong wave_list in Bandpass.__mul__")
    # scalar / Bandpass
    f = 1.21 / e
    np.testing.assert_almost_equal(f(3.0), 1.21 / (3.0**2 / (3.0 / 3.33)), 10,
                                   err_msg="Found wrong value in Bandpass.__mul__")
    np.testing.assert_array_almost_equal(f.wave_list, [1.1, 2, 2.2, 3, 4, 4.4, 5],
                                         err_msg="wrong wave_list in Bandpass.__mul__")

    t2 = time.time()
    print 'time for %s = %.2f'%(funcname(),t2-t1)
Esempio n. 14
0
def test_ne():
    """ Check that inequality works as expected."""
    tput = lambda x: x / 1000
    lt = galsim.LookupTable([400, 550], [0.4, 0.55], interpolant='linear')
    sed = galsim.SED('3', 'nm', 'flambda')

    # These should all compare unequal.
    bps = [
        galsim.Bandpass(throughput=tput,
                        wave_type='nm',
                        blue_limit=400,
                        red_limit=550),
        galsim.Bandpass(throughput=tput,
                        wave_type='nm',
                        blue_limit=400,
                        red_limit=551),
        galsim.Bandpass(throughput=tput,
                        wave_type='nm',
                        blue_limit=401,
                        red_limit=550),
        galsim.Bandpass(throughput=lt, wave_type='nm'),
        galsim.Bandpass(throughput=lt, wave_type='A'),
        galsim.Bandpass(throughput=lt, wave_type='nm', zeropoint=10.0),
        galsim.Bandpass(throughput=lt, wave_type='nm').withZeropoint('AB'),
        galsim.Bandpass(throughput=lt, wave_type='nm').withZeropoint('ST'),
        galsim.Bandpass(throughput=lt, wave_type='nm').withZeropoint('Vega'),
        galsim.Bandpass(throughput=lt, wave_type='nm').withZeropoint(100.0),
        galsim.Bandpass(throughput=lt, wave_type='nm').withZeropoint(sed)
    ]
    all_obj_diff(bps)
Esempio n. 15
0
    def thin(self, rel_err=1.e-4, preserve_range=False):
        """ If the SED was initialized with a LookupTable or from a file (which internally creates a
        LookupTable), then remove tabulated values while keeping the integral over the set of
        tabulated values still accurate to `rel_err`.

        @param rel_err            The relative error allowed in the integral over the SED
                                  [default: 1.e-4]
        @param preserve_range     Should the original range (`blue_limit` and `red_limit`) of the
                                  SED be preserved? (True) Or should the ends be trimmed to
                                  include only the region where the integral is significant? (False)
                                  [default: False]

        @returns the thinned SED.
        """
        if len(self.wave_list) > 0:
            wave_factor = 1.0 + self.redshift
            x = self.wave_list / wave_factor
            f = self._rest_photons(x)
            newx, newf = utilities.thin_tabulated_values(x, f, rel_err=rel_err,
                                                         preserve_range=preserve_range)
            spec = galsim.LookupTable(newx, newf, interpolant='linear')
            blue_limit = np.min(newx) * wave_factor
            red_limit = np.max(newx) * wave_factor
            wave_list = np.array(newx) * wave_factor
            return SED(spec, flux_type='fphotons', redshift=self.redshift,
                       _wave_list=wave_list, _blue_limit=blue_limit, _red_limit=red_limit)
        else:
            return self
Esempio n. 16
0
    def __mul__(self, other):
        if isinstance(other, galsim.GSObject):
            return galsim.Chromatic(other, self)

        # SEDs can be multiplied by scalars or functions (callables)
        wave_factor = 1.0 + self.redshift
        wave_type = 'nm'
        flux_type = 'fphotons'
        if hasattr(other, '__call__'):
            spec = lambda w: self._rest_photons(w) * other(w * wave_factor)
        elif isinstance(self._spec, galsim.LookupTable):
            # If other is not a function, then there is no loss of accuracy by applying the 
            # factor directly to the LookupTable, if that's what we are using.
            # Make sure to keep the same properties about the table, flux_type, wave_type.
            if self.wave_factor == 10.0:
                wave_type = 'Angstroms'
            flux_type = self.flux_type
            x = self._spec.getArgs()
            f = [ val * other for val in self._spec.getVals() ]
            spec = galsim.LookupTable(x, f, x_log=self._spec.x_log, f_log=self._spec.f_log,
                                      interpolant=self._spec.interpolant)
        else:
            spec = lambda w: self._rest_photons(w) * other

        return SED(spec, flux_type=flux_type, wave_type=wave_type, redshift=self.redshift,
                   _wave_list=self.wave_list,
                   _blue_limit=self.blue_limit, _red_limit=self.red_limit)
Esempio n. 17
0
def test_init():
    """Some simple tests of LookupTable initialization."""
    interp = 'linear'
    try:
        # Check for bad input: 1 column file, or specifying file and x, or just x, or bad
        # interpolant.
        np.testing.assert_raises(ValueError,
                                 galsim.LookupTable,
                                 file=os.path.join(
                                     TESTDIR, 'table_test1_%s.txt' % interp),
                                 x=interp)
        np.testing.assert_raises(ValueError,
                                 galsim.LookupTable,
                                 file=os.path.join(
                                     TESTDIR, 'table_test1_%s.txt' % interp))
        np.testing.assert_raises(ValueError,
                                 galsim.LookupTable,
                                 x=os.path.join(TESTDIR,
                                                'table_test1_%s.txt' % interp))
        np.testing.assert_raises(
            ValueError,
            galsim.LookupTable,
            file='../examples/data/cosmo-fid.zmed1.00_smoothed.out',
            interpolant='foo')
    except ImportError:
        print('The assert_raises tests require nose')
    # Also make sure nothing bad happens when we try to read in a stored power spectrum and assume
    # we can use the default interpolant (spline).
    tab_ps = galsim.LookupTable(
        file='../examples/data/cosmo-fid.zmed1.00_smoothed.out')

    # Check picklability
    do_pickle(tab_ps)
Esempio n. 18
0
def test_SED_div():
    """Check that SEDs divide like I think they should...
    """
    a0 = galsim.SED(galsim.LookupTable([1,2,3,4,5], [1.1,2.2,3.3,4.4,5.5]),
                    wave_type='nm', flux_type='fphotons')
    for z in [0, 0.2, 0.4]:
        a = a0.atRedshift(z)

        # SED divided by function
        b = lambda w: w**2
        c = a/b
        x = 3.0
        np.testing.assert_almost_equal(c(x), a(x)/b(x), 10,
                                       err_msg="Found wrong value in SED.__div__")

        # SED divided by scalar
        d = a/4.2
        np.testing.assert_almost_equal(d(x), a(x)/4.2, 10,
                                       err_msg="Found wrong value in SED.__div__")
        do_pickle(d)

        # assignment division
        d /= 2
        np.testing.assert_almost_equal(d(x), a(x)/4.2/2, 10,
                                       err_msg="Found wrong value in SED.__div__")
        do_pickle(d)

        # SED divided by dimensionless SED
        e = galsim.SED('wave', 'nm', '1')
        d /= e
        np.testing.assert_almost_equal(d(x), a(x)/4.2/2/e(x), 10,
                                       err_msg="Found wrong value in SED.__div__")
Esempio n. 19
0
def test_SED_mul():
    """Check that SEDs multiply like I think they should...
    """
    for z in [0, 0.2, 0.4]:
        a = galsim.SED(galsim.LookupTable([1,2,3,4,5], [1.1,2.2,3.3,4.4,5.5]),
                       wave_type='nm', flux_type='fphotons')
        if z != 0:
            a = a.atRedshift(z)

        # SED multiplied by function
        b = lambda w: w**2
        c = a*b
        x = 3.0
        np.testing.assert_almost_equal(c(x), a(x) * b(x), 10,
                                       err_msg="Found wrong value in SED.__mul__")

        # function multiplied by SED
        c = b*a
        np.testing.assert_almost_equal(c(x), a(x) * b(x), 10,
                                       err_msg="Found wrong value in SED.__rmul__")

        # SED multiplied by scalar
        d = a*4.2
        np.testing.assert_almost_equal(d(x), a(x) * 4.2, 10,
                                       err_msg="Found wrong value in SED.__mul__")
        do_pickle(d)

        # assignment multiplication
        d *= 2
        np.testing.assert_almost_equal(d(x), a(x) * 4.2 * 2, 10,
                                       err_msg="Found wrong value in SED.__mul__")
        do_pickle(d)
Esempio n. 20
0
def test_dep_bandpass():
    """Test the deprecated methods in galsim/deprecated/bandpass.py.
    """
    b = galsim.Bandpass(
        galsim.LookupTable([1.1, 2.2, 3.0, 4.4, 5.5],
                           [1.11, 2.22, 3.33, 4.44, 5.55]), 'nm')
    d = lambda w: w**2

    # fn / Bandpass
    #e = d/b
    e = check_dep(b.__rdiv__, d)
    np.testing.assert_almost_equal(
        e(3.0),
        3.0**2 / 3.33,
        10,
        err_msg="Found wrong value in Bandpass.__rdiv__")
    np.testing.assert_array_almost_equal(
        e.wave_list, [1.1, 2.2, 3.0, 4.4, 5.5],
        err_msg="wrong wave_list in Bandpass.__rdiv__")

    # scalar / Bandpass
    #f = 1.21 / b
    f = check_dep(b.__rdiv__, 1.21)
    np.testing.assert_almost_equal(
        f(3.0),
        1.21 / 3.33,
        10,
        err_msg="Found wrong value in Bandpass.__rdiv__")
    np.testing.assert_array_almost_equal(
        f.wave_list, [1.1, 2.2, 3.0, 4.4, 5.5],
        err_msg="wrong wave_list in Bandpass.__rdiv__")
Esempio n. 21
0
def test_SED_div():
    """Check that SEDs divide like I think they should...
    """
    import time
    t1 = time.time()

    for z in [0, 0.2, 0.4]:
        a = galsim.SED(galsim.LookupTable([1,2,3,4,5], [1.1,2.2,3.3,4.4,5.5]),
                       wave_type='nm', flux_type='fphotons')
        if z != 0:
            a = a.atRedshift(z)

        # SED divided by function
        b = lambda w: w**2
        c = a/b
        x = 3.0
        np.testing.assert_almost_equal(c(x), a(x)/b(x), 10,
                                       err_msg="Found wrong value in SED.__div__")

        # SED divided by scalar
        d = a/4.2
        np.testing.assert_almost_equal(d(x), a(x)/4.2, 10,
                                       err_msg="Found wrong value in SED.__div__")
        do_pickle(d)

        # assignment division
        d /= 2
        np.testing.assert_almost_equal(d(x), a(x)/4.2/2, 10,
                                       err_msg="Found wrong value in SED.__div__")
        do_pickle(d)

    t2 = time.time()
    print 'time for %s = %.2f'%(funcname(),t2-t1)
Esempio n. 22
0
def get_stellar_seds(pickles_path,
                     spec_types,
                     target_flux_density=1.0,
                     wavelength=500,
                     show=False):
    """Create templates for stellar sources
    """
    pickles_idx = ApTable.read(os.path.join(pickles_path, "pickles_uk.fits"))
    pickles_spt = [spt.rstrip() for spt in pickles_idx["SPTYPE"]]

    seds_stellar = []
    for spt in spec_types:
        filename = os.path.join(
            pickles_path,
            pickles_idx[pickles_spt.index(spt)]["FILENAME"].rstrip() + ".fits")
        data = fits.open(filename)[1].data
        tbl = galsim.LookupTable(data["wavelength"], data["flux"])
        sed = galsim.SED(tbl, wave_type="a", flux_type="flambda")
        seds_stellar.append(
            sed.withFluxDensity(target_flux_density=target_flux_density,
                                wavelength=wavelength))
    if show:
        for s, spt in enumerate(spec_types):
            tmp = seds_stellar[s]
            plt.plot(tmp._spec.x, tmp._spec.f / np.sum(tmp._spec.f), label=spt)
            plt.title("Stellar Spectra")
            plt.xlabel("Wavelength")
            plt.ylabel("Normalized Flux")
        plt.legend()
        plt.show()

    return seds_stellar
Esempio n. 23
0
def test_dep_sed():
    """Test the deprecated methods in galsim/deprecated/sed.py.
    """
    z = 0.4
    a = galsim.SED(galsim.LookupTable([1, 2, 3, 4, 5],
                                      [1.1, 2.2, 3.3, 4.4, 5.5]),
                   wave_type='nm',
                   flux_type='fphotons',
                   redshift=0.4)
    b = lambda w: w**2

    # function divided by SED
    #c = b/a
    c = check_dep(a.__rdiv__, b)
    x = 3.0
    np.testing.assert_almost_equal(c(x),
                                   b(x) / a(x),
                                   10,
                                   err_msg="Found wrong value in SED.__rdiv__")

    # number divided by SED
    #d = x/a
    d = check_dep(a.__rdiv__, x)
    np.testing.assert_almost_equal(d(x),
                                   x / a(x),
                                   10,
                                   err_msg="Found wrong value in SED.__rdiv__")
Esempio n. 24
0
    def __div__(self, other):
        # Watch out for 4 types of `other`:
        # 1.  SED: prohibit.
        # 2.  Bandpass: return a Bandpass, but carefully propagate blue/red limit and wave_list.
        # 3.  Callable: return a Bandpass
        # 4.  Scalar: return a Bandpass

        if isinstance(other, galsim.SED):
            raise TypeError("Cannot divide Bandpass by SED.")

        # Bandpass / Bandpass -> Bandpass
        if isinstance(other, Bandpass):
            wave_list, blue_limit, red_limit = galsim.utilities.combine_wave_list([self, other])
            tp = lambda w: self(w) / other(w)
            return Bandpass(tp, 'nm', blue_limit=blue_limit, red_limit=red_limit, zeropoint=None,
                            _wave_list=wave_list)

        # Quotient of Bandpass with generic callable or scalar is a rescaled Bandpass.
        wave_type = 'nm'
        if hasattr(other, '__call__'):
            tp = lambda w: self.func(w) / other(w)
        elif isinstance(self._tp, galsim.LookupTable):
            # If other is not a function, then there is no loss of accuracy by applying the
            # factor directly to the LookupTable, if that's what we are using.
            # Make sure to keep the same properties about the table, wave_type.
            if self.wave_factor == 10.0:
                wave_type = 'Angstroms'
            x = self._tp.getArgs()
            f = [ val / other for val in self._tp.getVals() ]
            tp = galsim.LookupTable(x, f, x_log=self._tp.x_log, f_log=self._tp.f_log,
                                    interpolant=self._tp.interpolant)
        else:
            tp = lambda w: self.func(w) / other

        return Bandpass(tp, wave_type, self.blue_limit, self.red_limit, _wave_list=self.wave_list)
Esempio n. 25
0
    def __div__(self, other):
        # Enable division by scalars or dimensionless callables (including dimensionless SEDs.)
        if isinstance(other, galsim.SED) and other.spectral:
            raise TypeError("Cannot divide by spectral SED.")
        if hasattr(other, '__call__'):
            spec = lambda w: self(w * (1.0 + self.redshift)) / other(w * (
                1.0 + self.redshift))
        elif isinstance(self._spec, galsim.LookupTable):
            # If other is not a function, then there is no loss of accuracy by applying the
            # factor directly to the LookupTable, if that's what we are using.
            # Make sure to keep the same properties about the table, flux_type, wave_type.
            x = self._spec.getArgs()
            f = [val / other for val in self._spec.getVals()]
            spec = galsim.LookupTable(x,
                                      f,
                                      x_log=self._spec.x_log,
                                      f_log=self._spec.f_log,
                                      interpolant=self._spec.interpolant)
        else:
            spec = lambda w: self(w * (1.0 + self.redshift)) / other

        return SED(spec,
                   flux_type=self.flux_type,
                   wave_type=self.wave_type,
                   redshift=self.redshift,
                   fast=self.fast,
                   _wave_list=self.wave_list,
                   _blue_limit=self.blue_limit,
                   _red_limit=self.red_limit)
Esempio n. 26
0
    def thin(self, rel_err=1.e-4, preserve_range=False):
        """Thin out the internal wavelengths of a Bandpass that uses a LookupTable.

        If the bandpass was initialized with a LookupTable or from a file (which internally
        creates a LookupTable), this function removes tabulated values while keeping the integral
        over the set of tabulated values still accurate to the given relative error.

        That is, the integral of the bandpass function is preserved to a relative precision
        of `rel_err`, while eliminating as many internal wavelength values as possible.  This
        process will usually help speed up integrations using this bandpass.  You should weigh
        the speed improvements against your fidelity requirements for your particular use
        case.

        @param rel_err            The relative error allowed in the integral over the throughput
                                  function. [default: 1.e-4]
        @param preserve_range     Should the original range (`blue_limit` and `red_limit`) of the
                                  Bandpass be preserved? (True) Or should the ends be trimmed to
                                  include only the region where the integral is significant? (False)
                                  [default: False]

        @returns the thinned Bandpass.
        """
        if len(self.wave_list) > 0:
            x = self.wave_list
            f = self(x)
            newx, newf = utilities.thin_tabulated_values(
                x, f, rel_err=rel_err, preserve_range=preserve_range)
            tp = galsim.LookupTable(newx, newf, interpolant='linear')
            blue_limit = np.min(newx)
            red_limit = np.max(newx)
            wave_list = np.array(newx)
            return Bandpass(tp, blue_limit, red_limit, _wave_list=wave_list)
        else:
            return self
Esempio n. 27
0
    def _initialize_tp(self):
        # Turn the input tp into a real function self.func.
        # The function cannot be pickled, so will need to do this in setstate as well as init.

        if self._tp is not None:
            pass
        elif isinstance(self._orig_tp, basestring):
            import os
            if os.path.isfile(self._orig_tp):
                self._tp = galsim.LookupTable(file=self._orig_tp,
                                              interpolant='linear')
            else:
                # Evaluate the function somewhere to make sure it is valid before continuing on.
                if self.red_limit is not None:
                    test_wave = self.red_limit * self.wave_factor
                elif blue_limit is not None:
                    test_wave = self.blue_limit * self.wave_factor
                else:
                    # If neither `blue_limit` nor `red_limit` is defined, then the Bandpass should
                    # be able to be evaluated at any wavelength, so check.
                    test_wave = 700
                try:
                    self._tp = eval('lambda wave : ' + self._orig_tp)
                    self._tp(test_wave)
                except:
                    raise ValueError(
                        "String throughput must either be a valid filename or something that "
                        +
                        "can eval to a function of wave. Input provided: {0}".
                        format(self._orig_tp))
        else:
            self._tp = self._orig_tp

        self.func = lambda w: self._tp(w * self.wave_factor)
Esempio n. 28
0
 def waves(self):
     if self._waves is None:
         sed = galsim.SED(galsim.LookupTable(x=self.skyModel.wave,
                                             f=self.skyModel.spec[0, :]),
                          wave_type='nm',
                          flux_type='flambda')
         bandPassName = self.obs_metadata.bandpass
         bandpass = self.bandpassDict[bandPassName]
         index = np.where(bandpass.sb != 0)
         gs_bandpass \
             = galsim.Bandpass(galsim.LookupTable(x=bandpass.wavelen[index],
                                                  f=bandpass.sb[index]),
                               wave_type='nm')
         self._waves = galsim.WavelengthSampler(sed=sed,
                                                bandpass=gs_bandpass,
                                                rng=self.randomNumbers)
     return self._waves
Esempio n. 29
0
def test_roundoff():
    table1 = galsim.LookupTable([1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
                                [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    # These should work without raising an exception
    np.testing.assert_almost_equal(table1(1.0 - 1.e-7), 1.0, decimal=6)
    np.testing.assert_almost_equal(table1(10.0 + 1.e-7), 10.0, decimal=6)
    assert_raises(ValueError, table1, 1.0 - 1.e5)
    assert_raises(ValueError, table1, 10.0 + 1.e5)
Esempio n. 30
0
    def _initialize_spec(self):
        # Turn the input spec into a real function self._rest_photons
        # The function cannot be pickled, so will need to do this in getstate as well as init.

        if self._spec is not None:
            pass
        elif isinstance(self._orig_spec, basestring):
            import os
            if os.path.isfile(self._orig_spec):
                self._spec = galsim.LookupTable(file=self._orig_spec,
                                                interpolant='linear')
            else:
                # Don't catch ArithmeticErrors when testing to see if the the result of `eval()`
                # is valid since `spec = '1./(wave-700)'` will generate a ZeroDivisionError (which
                # is a subclass of ArithmeticError) despite being a valid spectrum specification,
                # while `spec = 'blah'` where `blah` is undefined generates a NameError and is not
                # a valid spectrum specification.
                # Are there any other types of errors we should trap here?
                try:
                    self._spec = eval('lambda wave : ' + self._orig_spec)
                    self._spec(700)
                except ArithmeticError:
                    pass
                except:
                    raise ValueError(
                        "String spec must either be a valid filename or something that "
                        +
                        "can eval to a function of wave. Input provided: {0}".
                        format(self._orig_spec))
        else:
            self._spec = self._orig_spec

        # Do some SED unit conversions to make internal representation proportional to photons/nm.
        # Note that w should have units of nm below.
        c = 2.99792458e17  # speed of light in nm/s
        h = 6.62606957e-27  # Planck's constant in erg seconds
        if self.flux_type == 'flambda':
            # photons/nm = (erg/nm) * (photons/erg)
            #            = spec(w) * 1/(h nu) = spec(w) * lambda / hc
            self._rest_photons = lambda w: (self._spec(w * self.wave_factor) *
                                            w * self.wave_factor / (h * c))
        elif self.flux_type == 'fnu':
            # photons/nm = (erg/Hz) * (photons/erg) * (Hz/nm)
            #            = spec(w) * 1/(h nu) * |dnu/dlambda|
            # [Use dnu/dlambda = d(c/lambda)/dlambda = -c/lambda^2 = -nu/lambda]
            #            = spec(w) * 1/(h lambda)
            self._rest_photons = lambda w: (self._spec(w * self.wave_factor) /
                                            (w * h))
        elif self.flux_type == 'fphotons':
            # Already basically correct.  Just convert the units of lambda
            if self.wave_factor == 1.:
                self._rest_photons = self._spec
            else:
                # photons/nm = (photons/A) * (A/nm)
                self._rest_photons = lambda w: self._spec(w * self.wave_factor
                                                          ) * self.wave_factor
        else:
            raise ValueError("Unknown flux_type '{0}'".format(self.flux_type))