def get_profile(self, params):
        if 'flux_b' in params and 'flux_d' in params:
            flux_b = params['flux_b']
            flux_d = params['flux_d']

        elif 'flux_b' and 'flux_b/flux_total' in params:
            raise NotImplementedError('Need to implement flux_b/flux_total')

        else:
            raise ValueError('Flux was not specified.')

        if 'hlr_b' in params and 'hlr_d' in params:
            hlr_d = params['hlr_d']
            hlr_b = params['hlr_b']

        elif 'hlr_d' and 'R_r' in params:
            hlr_d = params['hlr_d']
            hlr_b = params['R_r'] * hlr_d

        else:
            raise ValueError('Size was not specified.')

        bulge = galsim.Sersic(n=params['n_b'],
                              half_light_radius=hlr_b,
                              flux=flux_b)

        disk = galsim.Sersic(n=params['n_d'],
                             half_light_radius=hlr_d,
                             flux=flux_d)

        if 'delta_e' in params or 'delta_theta' in params:
            raise NotImplementedError('Need to implement delta_e or '
                                      'delta_theta.')

        return bulge + disk
def get_gal_cg(Args):
    """ Return surface brightness profile (SBP) of cocentric bulge + disk galaxy.
    Bulge and disk have co-centric Sersic profiles.

    @param Args    Class with the following attributes:
        Args.bulge_n       Sersic index of bulge.
        Args.bulge_HLR     Half-light-radius of the bulge.
        Args.bulge_e       Shape of bulge [e1, e2].
        Args.bulge_frac    Fraction of flux in bulge at 550 nm rest-frame.
        Args.T_flux        Total flux in the galaxy.
        Args.disk_n        Sersic index of disk.
        Args.disk_HLR      Half-light-radius of the disk.
        Args.disk_e        Shape of disk [e1, e2].
        Args.b_SED         SED of bulge.
        Args.d_SED         SED of disk.
    @return galaxy with CG
    """
    bulge = galsim.Sersic(n=Args.bulge_n,
                          half_light_radius=Args.bulge_HLR,
                          flux=Args.T_flux * Args.bulge_frac)
    bulge = bulge.shear(e1=Args.bulge_e[0], e2=Args.bulge_e[1])
    disk = galsim.Sersic(n=Args.disk_n,
                         half_light_radius=Args.disk_HLR,
                         flux=Args.T_flux * (1 - Args.bulge_frac))
    disk = disk.shear(e1=Args.disk_e[0], e2=Args.disk_e[1])
    gal = bulge * Args.b_SED + disk * Args.d_SED
    return gal
    def _get_gals(self, mode, dx, dy):
        #        mode = self['Mode']
        #Cen = galsim.Gaussian(half_light_radius=self['Cen']['hlr'],flux=self['Cen']['Flux'])
        #Neigh = galsim.Exponential(half_light_radius=self['Neigh']['hlr'],flux=self['Neigh']['Flux'])

        n = rng.uniform(low=0.5, high=4)
        Cen = galsim.Sersic(n,
                            half_light_radius=self['Cen']['hlr'],
                            flux=self['Cen']['Flux'])
        n = rng.uniform(low=0.5, high=4)
        Neigh = galsim.Sersic(n,
                              half_light_radius=self['Neigh']['hlr'],
                              flux=self['Neigh']['Flux'])

        Cen = Cen.shear(g1=np.random.normal(scale=0.02),
                        g2=np.random.normal(scale=0.02))
        Neigh = Neigh.shear(g1=np.random.normal(scale=0.02),
                            g2=np.random.normal(scale=0.02))

        #cen position
        if self['Cen']['Pos'] == 'Fixed':
            dx1, dy1 = self['Cen']['dx'], self['Cen']['dy']

        elif self['Cen']['Pos'] == 'Rand_Circle':
            r = self['Cen']['r']
            theta = 2. * np.pi * np.random.random()
            dx1, dy1 = r * np.cos(theta), r * np.sin(theta)

        #neigh position
        if self['Neigh']['Pos'] == 'Fixed':
            dx2, dy2 = self['Neigh']['dx'], self['Neigh']['dy']

        elif self['Neigh']['Pos'] == 'Rand_circle':
            r = self['Neigh']['r']
            theta = 2. * np.pi * np.random.random()
            dx2, dy2 = r * np.cos(theta), r * np.sin(theta)

        dx1 += np.random.uniform(low=-0.5, high=0.5)
        dy1 += np.random.uniform(low=-0.5, high=0.5)
        dx2 += np.random.uniform(low=-0.5, high=0.5)
        dy2 += np.random.uniform(low=-0.5, high=0.5)

        #Cen = Cen.shift(dx=dx1, dy=dy1)
        #Neigh = Neigh.shift(dx=dx2, dy=dy2)

        if mode == 'scarlet' or mode == 'minimof':
            Cen = Cen.shift(dx=dx1, dy=dy1)
            Neigh = Neigh.shift(dx=dx2, dy=dy2)
            gals = [Cen, Neigh]
            objs = galsim.Add(gals)
        elif mode == 'control':
            Cen = Cen.shift(dx=dx, dy=dy)
            gals = [Cen]
            objs = galsim.Add(gals)
            dx1, dy1 = dx, dy

        shear1, shear2 = self['Shear']['Shear1'], self['Shear']['Shear2']
        #objs = objs.shear(g1=shear1, g2=shear2)

        return objs, dx1, dy1, dx2, dy2
Exemple #4
0
    def get_snr(self, obs_list, res):

        size = res['pars'][4]
        flux = res['flux']

        model_ = galsim.Sersic(
            1, half_light_radius=1. * size, flux=flux *
            (1. - res['pars'][5])) + galsim.Sersic(
                4, half_light_radius=1. * size, flux=flux * res['pars'][5])
        for i in range(len(obs_list)):
            obs = obs_list[i]
            im = obs.psf.image.copy()
            im *= 1.0 / im.sum() / len(obs_list)
            psf_gsimage = galsim.Image(im,
                                       wcs=obs.psf.jacobian.get_galsim_wcs())
            psf_ii = galsim.InterpolatedImage(psf_gsimage,
                                              x_interpolant='lanczos15')

            model = galsim.Convolve(model_, psf_ii)
            gal_stamp = galsim.Image(np.shape(obs.image)[0],
                                     np.shape(obs.image)[1],
                                     wcs=obs.jacobian.get_galsim_wcs())

            model.drawImage(image=gal_stamp)
            if i == 0:
                image = gal_stamp.array * obs.weight
            else:
                image += gal_stamp.array * obs.weight

        return image.sum()
def fcn2min(params, data, Args, psf):
    """Function given as input to lmfit, to compute residual of fit and true
    galaxy (galaxy with no CG)
    @param params  fit parameters
    @param data    true data
    @param Args
    @param mod_psf psf
    @returns difference betwwen fit and true"""
    g1 = params['g1'].value  # shear of galaxy
    g2 = params['g2'].value  # shear of galaxy
    rb = params['rb'].value  # half light radius of buldge
    rd = params['rd'].value  # half light radius disk
    bf = params['bf'].value  # ratio Flux of buldge to total flux

    mod_bulge = galsim.Sersic(n=Args.bulge_n,
                              half_light_radius=rb,
                              flux=Args.T_flux * bf)
    mod_disk = galsim.Sersic(n=Args.disk_n,
                             half_light_radius=rd,
                             flux=Args.T_flux * (1 - bf))
    mod_gal = (mod_bulge + mod_disk) * Args.c_SED
    mod_gal = mod_gal.shear(g1=g1, g2=g2)
    obj_con = galsim.Convolve(mod_gal, psf)
    mod_im = (obj_con.drawImage(bandpass=Args.bp,
                                scale=Args.scale,
                                nx=Args.npix,
                                ny=Args.npix)).array
    model1 = mod_im.flatten()
    resid = model1 - data
    return resid
def test_sersic():
    """ Test that InclinedSersic looks identical to a Sersic when inclination is zero.
    """

    ns = (1.1, 1.1, 2.5, 2.5)
    truncs = (0, 13.5, 0, 18.0)
    scale_radius = 3.0
    hlr = 1.7
    mode = "InclinedSersic"

    for n, trunc in zip(ns, truncs):

        # Construct from scale_radius
        sersic_profile = galsim.Sersic(n=n, scale_radius=scale_radius, trunc=trunc)
        inc_profile = get_prof(mode, n=n, trunc=trunc, inclination=0 * galsim.radians,
                               scale_radius=scale_radius,
                               scale_height=hlr / 10.)
        np.testing.assert_almost_equal(inc_profile.scale_radius, sersic_profile.scale_radius)
        np.testing.assert_almost_equal(inc_profile.disk_half_light_radius,
                                       sersic_profile.half_light_radius)

        # Construct from half-light radius
        sersic_profile = galsim.Sersic(n=n, half_light_radius=hlr, trunc=trunc)
        inc_profile = get_prof(mode, n=n, trunc=trunc, inclination=0 * galsim.radians,
                               half_light_radius=hlr,
                               scale_height=hlr / 10.)
        np.testing.assert_almost_equal(inc_profile.scale_radius, sersic_profile.scale_radius)
        np.testing.assert_almost_equal(inc_profile.disk_half_light_radius,
                                       sersic_profile.half_light_radius)

        sersic_image = galsim.Image(image_nx, image_ny, scale=1.0)
        sersic_profile.drawImage(sersic_image)
        inc_image = galsim.Image(image_nx, image_ny, scale=1.0)
        inc_profile.drawImage(inc_image)

        if save_profiles:
            sersic_image.write("test_sersic.fits", image_dir, clobber=True)
            inc_image.write("test_inclined_sersic.fits", image_dir, clobber=True)

        # Check that they're the same. Note that since the inclined Sersic profile isn't
        # Real-space analytic and has hard edges in the truncated case,
        # we have to be a bit lax on rtol and atol
        if trunc != 0:
            rtol = 5e-3
            atol = 5e-5
        else:
            rtol = 1e-3
            atol = 1e-5

        np.testing.assert_allclose(inc_image.array, sersic_image.array, rtol=rtol, atol=atol)

        # The face-on version should get the max_sb value exactly right
        np.testing.assert_almost_equal(inc_profile.max_sb, sersic_profile.max_sb)

        check_basic(inc_profile, "Face-on " + mode)
Exemple #7
0
def test_rotate():
    """Test the 45 degree rotation of a sheared Sersic profile against a known result.
    """
    import time
    t1 = time.time()
    mySBP = galsim.SBSersic(n=2.5, flux=1, half_light_radius=1)
    myShear = galsim.Shear(e1=0.2, e2=0.0)
    mySBP.applyShear(myShear._shear)
    mySBP.applyRotation(45.0 * galsim.degrees)
    savedImg = galsim.fits.read(os.path.join(imgdir, "sersic_ellip_rotated.fits"))
    myImg = galsim.ImageF(savedImg.bounds, scale=0.2)
    mySBP.draw(myImg.view())
    printval(myImg, savedImg)
    np.testing.assert_array_almost_equal(
            myImg.array, savedImg.array, 5,
            err_msg="45-degree rotated elliptical Gaussian disagrees with expected result")

    # Repeat with the GSObject version of this:
    gal = galsim.Sersic(n=2.5, flux=1, half_light_radius=1)
    gal.applyShear(myShear)
    gal.applyRotation(45.0 * galsim.degrees)
    gal.draw(myImg,dx=0.2, normalization="surface brightness", use_true_center=False)
    np.testing.assert_array_almost_equal(
            myImg.array, savedImg.array, 5,
            err_msg="Using GSObject applyRotation disagrees with expected result")

    # Check with default_params
    gal = galsim.Sersic(n=2.5, flux=1, half_light_radius=1, gsparams=default_params)
    gal.applyShear(myShear)
    gal.applyRotation(45.0 * galsim.degrees)
    gal.draw(myImg,dx=0.2, normalization="surface brightness", use_true_center=False)
    np.testing.assert_array_almost_equal(
            myImg.array, savedImg.array, 5,
            err_msg="Using GSObject applyRotation with default_params disagrees with expected "
            "result")
    gal = galsim.Sersic(n=2.5, flux=1, half_light_radius=1, gsparams=galsim.GSParams())
    gal.applyShear(myShear)
    gal.applyRotation(45.0 * galsim.degrees)
    gal.draw(myImg,dx=0.2, normalization="surface brightness", use_true_center=False)
    np.testing.assert_array_almost_equal(
            myImg.array, savedImg.array, 5,
            err_msg="Using GSObject applyRotation with GSParams() disagrees with expected result")
 
    # Test photon shooting.
    # Convolve with a small gaussian to smooth out the central peak.
    gal2 = galsim.Convolve(gal, galsim.Gaussian(sigma=0.3))
    do_shoot(gal2,myImg,"rotated sheared Sersic")

    # Test kvalues
    do_kvalue(gal,"rotated sheared Sersic")

    t2 = time.time()
    print 'time for %s = %.2f'%(funcname(),t2-t1)
Exemple #8
0
def test_sersic_05():
    """Test the equivalence of Sersic with n=0.5 and Gaussian
    """
    # hlr/sigma = sqrt(2 ln(2)) = 1.177410022515475
    hlr_sigma = 1.177410022515475
    test_flux = 1.8

    # cf test_gaussian()
    savedImg = galsim.fits.read(os.path.join(imgdir, "gauss_1.fits"))
    savedImg.setCenter(0, 0)
    dx = 0.2
    myImg = galsim.ImageF(savedImg.bounds, scale=dx)
    sersic = galsim.Sersic(n=0.5, flux=1, half_light_radius=1 * hlr_sigma)
    myImg = sersic.drawImage(myImg, method="sb", use_true_center=False)
    print('saved image center = ', savedImg(0, 0))
    print('image center = ', myImg(0, 0))
    np.testing.assert_array_almost_equal(
        myImg.array,
        savedImg.array,
        5,
        err_msg=
        "Using Sersic with n=0.5 disagrees with expected result for Gaussian")

    check_basic(sersic, "n=0.5 Sersic")

    do_kvalue(sersic, myImg, "n=0.5 Sersic")

    # cf test_gaussian_properties()
    test_sigma = 1.8
    sersic = galsim.Sersic(n=0.5,
                           flux=test_flux,
                           half_light_radius=test_sigma * hlr_sigma)
    cen = galsim.PositionD(0, 0)
    np.testing.assert_equal(sersic.centroid, cen)
    np.testing.assert_almost_equal(sersic.kValue(cen), (1 + 0j) * test_flux)
    np.testing.assert_almost_equal(sersic.flux, test_flux)
    import math
    np.testing.assert_almost_equal(sersic.xValue(cen),
                                   1. / (2. * math.pi) * test_flux /
                                   test_sigma**2,
                                   decimal=5)
    np.testing.assert_almost_equal(sersic.xValue(cen), sersic.max_sb)

    # Also test some random values other than the center:
    gauss = galsim.Gaussian(flux=test_flux, sigma=test_sigma)
    for (x, y) in [(0.1, 0.2), (-0.5, 0.4), (0, 0.9), (1.2, 0.1), (2, 2)]:
        pos = galsim.PositionD(x, y)
        np.testing.assert_almost_equal(sersic.xValue(pos),
                                       gauss.xValue(pos),
                                       decimal=5)
        np.testing.assert_almost_equal(sersic.kValue(pos),
                                       gauss.kValue(pos),
                                       decimal=5)
Exemple #9
0
def test_sersic_flux_scaling():
    """Test flux scaling for Sersic.
    """
    import time
    t1 = time.time()
    # loop through sersic n
    for test_n in test_sersic_n:
        # loop through sersic truncation
        for test_trunc in test_sersic_trunc:
            # init with hlr and flux only (should be ok given last tests)
            obj = galsim.Sersic(test_n, half_light_radius=test_hlr, flux=test_flux, trunc=test_trunc)
            obj *= 2.
            np.testing.assert_almost_equal(
                obj.getFlux(), test_flux * 2., decimal=param_decimal,
                err_msg="Flux param inconsistent after __imul__.")
            obj = galsim.Sersic(test_n, half_light_radius=test_hlr, flux=test_flux, trunc=test_trunc)
            obj /= 2.
            np.testing.assert_almost_equal(
                obj.getFlux(), test_flux / 2., decimal=param_decimal,
                err_msg="Flux param inconsistent after __idiv__.")
            obj = galsim.Sersic(test_n, half_light_radius=test_hlr, flux=test_flux, trunc=test_trunc)
            obj2 = obj * 2.
            # First test that original obj is unharmed... (also tests that .copy() is working)
            np.testing.assert_almost_equal(
                obj.getFlux(), test_flux, decimal=param_decimal,
                err_msg="Flux param inconsistent after __rmul__ (original).")
            # Then test new obj2 flux
            np.testing.assert_almost_equal(
                obj2.getFlux(), test_flux * 2., decimal=param_decimal,
                err_msg="Flux param inconsistent after __rmul__ (result).")
            obj = galsim.Sersic(test_n, half_light_radius=test_hlr, flux=test_flux, trunc=test_trunc)
            obj2 = 2. * obj
            # First test that original obj is unharmed... (also tests that .copy() is working)
            np.testing.assert_almost_equal(
                obj.getFlux(), test_flux, decimal=param_decimal,
                err_msg="Flux param inconsistent after __mul__ (original).")
            # Then test new obj2 flux
            np.testing.assert_almost_equal(
                obj2.getFlux(), test_flux * 2., decimal=param_decimal,
                err_msg="Flux param inconsistent after __mul__ (result).")
            obj = galsim.Sersic(test_n, half_light_radius=test_hlr, flux=test_flux, trunc=test_trunc)
            obj2 = obj / 2.
            # First test that original obj is unharmed... (also tests that .copy() is working)
            np.testing.assert_almost_equal(
                 obj.getFlux(), test_flux, decimal=param_decimal,
                 err_msg="Flux param inconsistent after __div__ (original).")
            # Then test new obj2 flux
            np.testing.assert_almost_equal(
                obj2.getFlux(), test_flux / 2., decimal=param_decimal,
                err_msg="Flux param inconsistent after __div__ (result).")
    t2 = time.time()
    print 'time for %s = %.2f'%(funcname(),t2-t1)
def doubleSersic(xcen1,
                 ycen1,
                 flux1,
                 reff1,
                 nser1,
                 q1,
                 pa1,
                 xcen2,
                 ycen2,
                 flux2,
                 reff2,
                 nser2,
                 q2,
                 pa2,
                 nx,
                 ny,
                 psf=None,
                 scale=1.0,
                 exptime=1.0,
                 trunc=0,
                 max_fft=None):
    """Generate image for double Sersic component."""
    ser = galsim.Add([
        galsim.Sersic(
            n=nser1,
            half_light_radius=reff1,
            flux=(flux1 * exptime),
            trunc=trunc).shear(q=q1, beta=(0.0 * galsim.degrees)).rotate(
                (90.0 - pa1) * galsim.degrees).shift((xcen1 - (nx / 2.0)),
                                                     (ycen1 - (ny / 2.0))),
        galsim.Sersic(
            n=nser2,
            half_light_radius=reff2,
            flux=(flux2 * exptime),
            trunc=trunc).shear(q=q2, beta=(0.0 * galsim.degrees)).rotate(
                (90.0 - pa2) * galsim.degrees).shift((xcen2 - (nx / 2.0)),
                                                     (ycen2 - (ny / 2.0)))
    ])

    if psf is not None:
        if max_fft is not None:
            gsparams = galsim.GSParams(maximum_fft_size=max_fft)
            return (galsim.Convolve([ser, psf], gsparams=gsparams).drawImage(
                nx=nx, ny=ny, method='no_pixel', scale=scale)).array
        else:
            return (galsim.Convolve([ser, psf]).drawImage(nx=nx,
                                                          ny=ny,
                                                          method='no_pixel',
                                                          scale=scale)).array
    else:
        return (ser.drawImage(nx=nx, ny=ny, method='no_pixel',
                              scale=scale)).array
Exemple #11
0
def test_sersic_1():
    """Test the equivalence of Sersic with n=1 and Exponential
    """
    # cf test_exponential()
    test_flux = 17.9
    re = 1.0
    r0 = re / 1.67839
    # The real value of re/r0 = 1.6783469900166605
    hlr_r0 = 1.6783469900166605
    savedImg = galsim.fits.read(os.path.join(imgdir, "exp_1.fits"))
    dx = 0.2
    myImg = galsim.ImageF(savedImg.bounds, scale=dx)
    sersic = galsim.Sersic(n=1, flux=1., half_light_radius=r0 * hlr_r0)
    sersic.drawImage(myImg, method="sb", use_true_center=False)
    np.testing.assert_array_almost_equal(
        myImg.array,
        savedImg.array,
        5,
        err_msg=
        "Using Sersic n=1 disagrees with expected result for Exponential")

    check_basic(sersic, "n=1 Sersic")

    do_kvalue(sersic, myImg, "n=1 Sersic")

    # cf test_exponential_properties()
    test_scale = 1.8
    sersic = galsim.Sersic(n=1,
                           flux=test_flux,
                           half_light_radius=test_scale * hlr_r0)
    cen = galsim.PositionD(0, 0)
    np.testing.assert_equal(sersic.centroid, cen)
    np.testing.assert_almost_equal(sersic.kValue(cen), (1 + 0j) * test_flux)
    np.testing.assert_almost_equal(sersic.flux, test_flux)
    import math
    np.testing.assert_almost_equal(sersic.xValue(cen),
                                   1. / (2. * math.pi) * test_flux /
                                   test_scale**2,
                                   decimal=5)
    np.testing.assert_almost_equal(sersic.xValue(cen), sersic.max_sb)

    # Also test some random values other than the center:
    expon = galsim.Exponential(flux=test_flux, scale_radius=test_scale)
    for (x, y) in [(0.1, 0.2), (-0.5, 0.4), (0, 0.9), (1.2, 0.1), (2, 2)]:
        pos = galsim.PositionD(x, y)
        np.testing.assert_almost_equal(sersic.xValue(pos),
                                       expon.xValue(pos),
                                       decimal=5)
        np.testing.assert_almost_equal(sersic.kValue(pos),
                                       expon.kValue(pos),
                                       decimal=5)
Exemple #12
0
def test_ne():
    """Test base.py GSObjects for not-equals."""
    # Define some universal gsps
    gsp = galsim.GSParams(maxk_threshold=1.1e-3, folding_threshold=5.1e-3)

    # Sersic.  Params include n, half_light_radius, scale_radius, flux, trunc, flux_untruncated
    # and gsparams.
    # The following should all test unequal:
    gals = [galsim.Sersic(n=1.1, half_light_radius=1.0),
            galsim.Sersic(n=1.2, half_light_radius=1.0),
            galsim.Sersic(n=1.1, half_light_radius=1.1),
            galsim.Sersic(n=1.1, scale_radius=1.0),
            galsim.Sersic(n=1.1, half_light_radius=1.0, flux=1.1),
            galsim.Sersic(n=1.1, half_light_radius=1.0, trunc=1.8),
            galsim.Sersic(n=1.1, half_light_radius=1.0, trunc=1.8, flux_untruncated=True),
            galsim.Sersic(n=1.1, half_light_radius=1.0, gsparams=gsp)]
    all_obj_diff(gals)

    # DeVaucouleurs.  Params include half_light_radius, scale_radius, flux, trunc, flux_untruncated,
    # and gsparams.
    # The following should all test unequal:
    gals = [galsim.DeVaucouleurs(half_light_radius=1.0),
            galsim.DeVaucouleurs(half_light_radius=1.1),
            galsim.DeVaucouleurs(scale_radius=1.0),
            galsim.DeVaucouleurs(half_light_radius=1.0, flux=1.1),
            galsim.DeVaucouleurs(half_light_radius=1.0, trunc=2.0),
            galsim.DeVaucouleurs(half_light_radius=1.0, trunc=2.0, flux_untruncated=True),
            galsim.DeVaucouleurs(half_light_radius=1.0, gsparams=gsp)]
    all_obj_diff(gals)
Exemple #13
0
def test_near_05():
    """Test from issue #1041, where some values of n near but not exactly equal to 0.5 would
    fail to converge in bracketUpper()
    """
    ser1 = galsim.Sersic(n=0.5, half_light_radius=1)
    ser2 = galsim.Sersic(n=0.499999999999, half_light_radius=1)
    ser3 = galsim.Sersic(n=0.500000000001, half_light_radius=1)

    im1 = ser1.drawImage()
    im2 = ser2.drawImage()
    im3 = ser3.drawImage()

    np.testing.assert_allclose(im2.array, im1.array, atol=1.e-12)
    np.testing.assert_allclose(im3.array, im1.array, atol=1.e-12)
Exemple #14
0
def test_rotate():
    """Test the 45 degree rotation of a sheared Sersic profile against a known result.
    """
    myShear = galsim.Shear(e1=0.2, e2=0.0)
    savedImg = galsim.fits.read(os.path.join(imgdir, "sersic_ellip_rotated.fits"))
    dx = 0.2
    myImg = galsim.ImageF(savedImg.bounds, scale=dx)
    myImg.setCenter(0,0)

    gal = galsim.Sersic(n=2.5, flux=1, half_light_radius=1)
    gal = gal.shear(myShear).rotate(45.0 * galsim.degrees)
    gal.drawImage(myImg,scale=dx, method="sb", use_true_center=False)
    np.testing.assert_array_almost_equal(
            myImg.array, savedImg.array, 5,
            err_msg="Using GSObject rotate disagrees with expected result")
    np.testing.assert_almost_equal(
            myImg.array.max(), gal.max_sb, 5,
            err_msg="rotated profile max_sb did not match maximum pixel value")

    # Check with default_params
    gal = galsim.Sersic(n=2.5, flux=1, half_light_radius=1, gsparams=default_params)
    gal = gal.shear(myShear).rotate(45.0 * galsim.degrees)
    gal.drawImage(myImg,scale=dx, method="sb", use_true_center=False)
    np.testing.assert_array_almost_equal(
            myImg.array, savedImg.array, 5,
            err_msg="Using GSObject rotate with default_params disagrees with expected "
            "result")
    gal = galsim.Sersic(n=2.5, flux=1, half_light_radius=1, gsparams=galsim.GSParams())
    gal = gal._shear(myShear).rotate(45.0 * galsim.degrees)
    gal.drawImage(myImg,scale=dx, method="sb", use_true_center=False)
    np.testing.assert_array_almost_equal(
            myImg.array, savedImg.array, 5,
            err_msg="Using GSObject rotate with GSParams() disagrees with expected result")

    # Convolve with a small gaussian to smooth out the central peak.
    gal2 = galsim.Convolve(gal, galsim.Gaussian(sigma=0.3))
    check_basic(gal2, "rotated sheared Sersic")

    # Test photon shooting.
    do_shoot(gal2,myImg,"rotated sheared Sersic")

    # Test kvalues
    do_kvalue(gal,myImg,"rotated sheared Sersic")

    # Check picklability
    do_pickle(gal, lambda x: x.drawImage())
    do_pickle(gal)

    assert_raises(TypeError, gal.rotate)
    assert_raises(TypeError, gal.rotate, 34)
Exemple #15
0
def get_model(type="disc", size=1.0, g1=0, g2=0, flux=None):
    if type is "disc":
        gal = galsim.Sersic(n=1, half_light_radius=size)
    if type is "bulge":
        gal = galsim.Sersic(n=4, half_light_radius=size)
    if type is "gaussian":
        gal = galsim.Gaussian(fwhm=size)

    shear = galsim.Shear(g1=g1, g2=g2)
    gal = gal.shear(shear)

    if flux is not None:
        gal = gal.withFlux(flux)

    return gal
Exemple #16
0
def test_sersic_shoot():
    """Test Sersic with photon shooting.  Particularly the flux of the final image.
    """
    rng = galsim.BaseDeviate(1234)
    obj = galsim.Sersic(n=1.5, half_light_radius=3.5, flux=1.e4)
    im = galsim.Image(100, 100, scale=1)
    im.setCenter(0, 0)
    added_flux, photons = obj.drawPhot(im,
                                       poisson_flux=False,
                                       rng=rng.duplicate())
    print('obj.flux = ', obj.flux)
    print('added_flux = ', added_flux)
    print('photon fluxes = ', photons.flux.min(), '..', photons.flux.max())
    print('image flux = ', im.array.sum())
    assert np.isclose(added_flux, obj.flux)
    assert np.isclose(im.array.sum(), obj.flux)
    photons2 = obj.makePhot(poisson_flux=False, rng=rng)
    assert photons2 == photons, "Sersic makePhot not equivalent to drawPhot"

    obj = galsim.DeVaucouleurs(half_light_radius=3.5, flux=1.e4)
    # Need a larger image for devauc wings
    im = galsim.Image(1000, 1000, scale=1)
    im.setCenter(0, 0)
    added_flux, photons = obj.drawPhot(im,
                                       poisson_flux=False,
                                       rng=rng.duplicate())
    print('obj.flux = ', obj.flux)
    print('added_flux = ', added_flux)
    print('photon fluxes = ', photons.flux.min(), '..', photons.flux.max())
    print('image flux = ', im.array.sum())
    assert np.isclose(added_flux, obj.flux)
    assert np.isclose(im.array.sum(), obj.flux)
    photons2 = obj.makePhot(poisson_flux=False, rng=rng)
    assert photons2 == photons, "Sersic makePhot not equivalent to drawPhot"

    # Can do up to around n=6 with this image if hlr is smaller.
    obj = galsim.Sersic(half_light_radius=0.9, n=6.2, flux=1.e4)
    added_flux, photons = obj.drawPhot(im,
                                       poisson_flux=False,
                                       rng=rng.duplicate())
    print('obj.flux = ', obj.flux)
    print('added_flux = ', added_flux)
    print('photon fluxes = ', photons.flux.min(), '..', photons.flux.max())
    print('image flux = ', im.array.sum())
    assert np.isclose(added_flux, obj.flux)
    assert np.isclose(im.array.sum(), obj.flux)
    photons2 = obj.makePhot(poisson_flux=False, rng=rng)
    assert photons2 == photons, "Sersic makePhot not equivalent to drawPhot"
Exemple #17
0
def test_comparison_object(np):

    logging.basicConfig(level=logging.WARNING, stream=sys.stdout)
    logger = logging.getLogger("test_comparison_object")

    logger.info("Running basic tests of comparison scripts using objects")

    # Build a trial galaxy
    gal = galsim.Sersic(galn, half_light_radius=galhlr)
    gal.applyShear(g1=g1gal, g2=g2gal)
    # And an example PSF
    psf = galsim.Moffat(beta=psfbeta, fwhm=psffwhm)
    psf.applyShear(g1=g1psf, g2=g2psf)

    # Try a single core run
    print "Starting tests using config file with N_PHOTONS = " + str(np)
    res1 = galsim.utilities.compare_dft_vs_photon_object(
        gal,
        psf_object=psf,
        rng=galsim.BaseDeviate(rseed),
        size=imsize,
        pixel_scale=dx,
        abs_tol_ellip=tol_ellip,
        abs_tol_size=tol_size,
        n_photons_per_trial=np)
    print res1
    return
def draw_sersic_model(mag=-10,
                      r=1,
                      pixel_scale=1,
                      q=0.2,
                      beta=0.0,
                      n=1,
                      xc=0,
                      yc=0,
                      x_size=64,
                      y_size=64):
    k = 64
    big_fft_params = galsim.GSParams(maximum_fft_size=int(512 * k))

    flux_gal = 10**(-0.4 * mag)  # Lensed documentation: L_tot = 10**(-0.4m)
    size_gal = r  # In arcseconds
    q_gal = q
    beta_gal = beta
    n = n
    #random_seed=1534225
    #rng = galsim.BaseDeviate(random_seed)
    xc = xc
    yc = yc

    gal = galsim.Sersic(n=n,
                        half_light_radius=size_gal,
                        flux=flux_gal,
                        gsparams=big_fft_params).shear(q=q_gal,
                                                       beta=beta_gal *
                                                       galsim.degrees)
    base_size_x = x_size
    base_size_y = y_size
    im = gal.drawImage(image=galsim.ImageF(base_size_x, base_size_y),
                       scale=pixel_scale,
                       offset=(xc, yc))
    return im.array
Exemple #19
0
def test_lens():
    """Test the lensing (shear, magnification) of a Sersic profile carried out 2 ways.
    """
    re = 1.0
    n = 3.
    g1 = 0.12
    g2 = -0.4
    mu = 1.2
    pix_scale = 0.1
    imsize = 100
    ser = galsim.Sersic(n, half_light_radius = re)

    ser1 = ser.shear(g1=g1, g2=g2).magnify(mu)
    im1 = galsim.ImageF(imsize, imsize, scale=pix_scale)
    im1 = ser1.drawImage(im1, method='no_pixel')

    ser2 = ser.lens(g1, g2, mu)
    im2 = galsim.ImageF(imsize, imsize, scale=pix_scale)
    im2 = ser2.drawImage(im2, method='no_pixel')
    np.testing.assert_array_almost_equal(im2.array, im1.array, 5,
        err_msg="Lensing of Sersic profile done in two different ways gives different answer")

    # _lens is equivalent in this case.
    ser3 = ser._lens(g1, g2, mu)
    im3 = galsim.ImageF(imsize, imsize, scale=pix_scale)
    im3 = ser3.drawImage(im3, method='no_pixel')
    np.testing.assert_array_almost_equal(im3.array, im1.array, 5,
        err_msg="Lensing of Sersic profile with _lens gives different answer")
def singleSersic(xcen,
                 ycen,
                 flux,
                 reff,
                 nser,
                 q,
                 pa,
                 nx,
                 ny,
                 psf=None,
                 scale=1.0,
                 exptime=1.0,
                 trunc=0,
                 max_fft=None):
    """Generate image for single Sersic component."""
    ser = galsim.Sersic(n=nser,
                        half_light_radius=reff,
                        flux=(flux * exptime),
                        trunc=trunc).shear(
                            q=q, beta=(0.0 * galsim.degrees)).rotate(
                                (90.0 - pa) * galsim.degrees).shift(
                                    (xcen - (nx / 2.0)), (ycen - (ny / 2.0)))

    if psf is not None:
        if max_fft is not None:
            gsparams = galsim.GSParams(maximum_fft_size=max_fft)
        else:
            gsparams = galsim.GSParams()
        return (galsim.Convolve([ser, psf], gsparams=gsparams).drawImage(
            nx=nx, ny=ny, method='no_pixel', scale=scale)).array
    else:
        return (ser.drawImage(nx=nx, ny=ny, method='no_pixel',
                              scale=scale)).array
    def drawSersic(self, gsObject):
        """
        Draw the image of a Sersic profile.

        @param [in] gsObject is an instantiation of the GalSimCelestialObject class
        carrying information about the object whose image is to be drawn
        """

        # create a Sersic profile
        centeredObj = galsim.Sersic(n=float(gsObject.sindex),
                                    half_light_radius=float(
                                        gsObject.halfLightRadiusArcsec))

        # Turn the Sersic profile into an ellipse
        centeredObj = centeredObj.shear(
            q=gsObject.minorAxisRadians / gsObject.majorAxisRadians,
            beta=(0.5 * np.pi + gsObject.positionAngleRadians) *
            galsim.radians)

        # Apply weak lensing distortion.
        centeredObj = centeredObj.lens(gsObject.g1, gsObject.g2, gsObject.mu)

        # Apply the PSF.
        if self.PSF is not None:
            centeredObj = self.PSF.applyPSF(xPupil=gsObject.xPupilArcsec,
                                            yPupil=gsObject.yPupilArcsec,
                                            obj=centeredObj)

        return centeredObj
Exemple #22
0
def makeGalaxy(cc,
               gal_indices,
               chromatic=False,
               gsparams=None,
               trunc_factor=0.):
    """Return Sersic profile specified by Cosmos Catalog (cc) and gal_indeces"""
    galaxies = []
    sersicfit = cc.param_cat['sersicfit']
    for gal_id in gal_indices:
        gal_n = sersicfit[gal_id, 2]
        gal_q = sersicfit[gal_id, 3]
        gal_phi = sersicfit[gal_id, 7]
        gal_hlr = sersicfit[gal_id, 1] * np.sqrt(gal_q) * 0.03  # in arcsec
        b_n = 1.992 * gal_n - 0.3271
        gal_flux = 2 * np.pi * gal_n * scipy.special.gamma(2*gal_n)*\
                   np.exp(b_n) * gal_q * (sersicfit[gal_id, 1]**2)*\
                   (sersicfit[gal_id, 0])/(b_n**(2. * gal_n))
        # print gal_n, gal_hlr, gal_flux, gal_q, gal_phi
        gal = galsim.Sersic(n=gal_n,
                            half_light_radius=gal_hlr,
                            flux=gal_flux,
                            trunc=trunc_factor * gal_hlr,
                            gsparams=gsparams).shear(q=gal_q,
                                                     beta=gal_phi *
                                                     galsim.radians)
        galaxies.append(gal)
    return galaxies
Exemple #23
0
 def createSource(self, galaxyIndex, shifted=False, lensed=False):
     """
     Returns a GalSim model of the source for the specified galaxy index with
     optional centroid shifts and weak lensing distortion.
     """
     params = self.getTruthCatalog()[galaxyIndex]
     # Create the bulge component.
     bulge = galsim.Sersic(flux=params['bulge_flux'],
                           half_light_radius=params['bulge_hlr'],
                           n=params['bulge_n'],
                           gsparams=Observation.getGSParams())
     bulge.applyShear(q=params['bulge_q'],
                      beta=params['bulge_beta_radians'] * galsim.radians)
     # Is there a disk component?
     if params['disk_flux'] > 0:
         disk = galsim.Exponential(flux=params['disk_flux'],
                                   half_light_radius=params['disk_hlr'],
                                   gsparams=Observation.getGSParams())
         disk.applyShear(q=params['disk_q'],
                         beta=params['disk_beta_radians'] * galsim.radians)
         source = galsim.Add(bulge, disk)
     else:
         source = bulge
     # Apply optional lensing.
     if lensed:
         source = source.lens(g1=params['g1'],
                              g2=params['g2'],
                              mu=params['mu'])
     # Apply optional centroid shift.
     if shifted:
         source = source.shift(dx=params['xshift'] * self.pixelScale,
                               dy=params['yshift'] * self.pixelScale)
     return source
def test_lens():
    """Test the lensing (shear, magnification) of a Sersic profile carried out 2 ways.
    """
    import time
    t1 = time.time()
    re = 1.0
    n = 3.
    g1 = 0.12
    g2 = -0.4
    mu = 1.2
    pix_scale = 0.1
    imsize = 100
    ser = galsim.Sersic(n, half_light_radius = re)
    ser2 = ser.createLensed(g1, g2, mu)
    ser.applyShear(g1=g1, g2=g2)
    ser.applyMagnification(mu)
    im = galsim.ImageF(imsize, imsize, scale=pix_scale)
    im = ser.draw(im)
    im2 = galsim.ImageF(imsize, imsize, scale=pix_scale)
    im2 = ser2.draw(im2)
    np.testing.assert_array_almost_equal(im.array, im2.array, 5,
        err_msg="Lensing of Sersic profile done in two different ways gives different answer")

    t2 = time.time()
    print 'time for %s = %.2f'%(funcname(),t2-t1)
def makeSersic(gal_n, gal_hlr, gal_flux, gal_q, gal_phi, gsparams):
    """Return a Sersic profile with given n, circ. hlr, flux, axis ratio q, orientation angle phi in radians."""
    gal = galsim.Sersic(n=gal_n,
                        half_light_radius=gal_hlr,
                        flux=gal_flux,
                        gsparams=gsparams).shear(q=gal_q,
                                                 beta=gal_phi * galsim.radians)
    return gal
Exemple #26
0
def draw_bulge_plus_disk_model(mag_b=-10,
                               r_b=1,
                               q_b=0.2,
                               beta_b=0.0,
                               n_b=1,
                               mag_d=-10,
                               r_d=1,
                               q_d=0.2,
                               beta_d=0.0,
                               n_d=1,
                               pixel_scale=1,
                               xc=0,
                               yc=0,
                               x_size=64,
                               y_size=64):
    k = 64
    big_fft_params = galsim.GSParams(maximum_fft_size=int(512 * k))

    flux_b = 10**(-0.4 * mag_b)
    bulge = galsim.Sersic(n=n_b,
                          half_light_radius=r_b,
                          flux=flux_b,
                          gsparams=big_fft_params).shear(q=q_b,
                                                         beta=beta_b *
                                                         galsim.degrees)

    flux_d = 10**(-0.4 * mag_d)
    disk = galsim.Sersic(n=n_d,
                         half_light_radius=r_d,
                         flux=flux_d,
                         gsparams=big_fft_params).shear(q=q_d,
                                                        beta=beta_d *
                                                        galsim.degrees)

    gal = disk + bulge

    xc = xc
    yc = yc

    base_size_x = x_size
    base_size_y = y_size
    im = gal.drawImage(image=galsim.ImageF(base_size_x, base_size_y),
                       scale=pixel_scale,
                       offset=(xc, yc))
    return im.array
Exemple #27
0
 def lrg(self,objinfo,siminfo):
     """Create an LRG (spheroidal) galaxy."""
     obj = galsim.Sersic(float(objinfo['SERSICN_1']),half_light_radius=
                         float(objinfo['R50_1']),
                         flux=self.objflux,gsparams=siminfo.gsparams)
     obj = obj.shear(q=float(objinfo['BA_1']),beta=
                     float(objinfo['PHI_1'])*galsim.degrees)
     stamp = self.convolve_and_draw(obj)
     return stamp
Exemple #28
0
def make_bdf(half_light_radius=None,
             flux=None,
             fracdev=None,
             trunc=0.0,
             gsparams=None):
    """
    a bulge+disk maker for equal hlr for bulge and disk

    Parameters
    ----------
    half_light_radius: float
        hlr
    flux: float
        Total flux in the profile
    fracdev: float
        fraction of light in the bulge
    """
    import galsim

    assert half_light_radius is not None, 'send half_light_ratio'
    assert flux is not None, 'send flux'
    assert fracdev is not None, 'send fracdev'

    if trunc > 0:
        flux_untruncated = True
    else:
        flux_untruncated = False
    """
    bulge = galsim.DeVaucouleurs(
        half_light_radius=half_light_radius,
        flux=fracdev,
        flux_untruncated=flux_untruncated ,
        trunc=trunc,
        gsparams=gsparams,
    )
    """
    bulge = galsim.Sersic(
        n=2,
        half_light_radius=half_light_radius,
        flux=fracdev,
        flux_untruncated=flux_untruncated,
        trunc=trunc,
        gsparams=gsparams,
    )

    disk = galsim.Exponential(
        half_light_radius=half_light_radius,
        flux=(1 - fracdev),
        gsparams=gsparams,
    )

    return galsim.Add(
        bulge,
        disk,
        gsparams=gsparams,
    ).withFlux(flux)
Exemple #29
0
    def _get_gal_exp(self):
        flux = 10**(0.4 * (30 - 20))
        half_light_radius = 1e-5

        obj = galsim.Sersic(
            half_light_radius=half_light_radius,
            n=1,
        ).withFlux(flux)

        return [obj]
Exemple #30
0
def test_sersic_flux_scaling():
    """Test flux scaling for Sersic.
    """
    # decimal point to go to for parameter value comparisons
    param_decimal = 12
    test_hlr = 1.8
    test_flux = 17.9
    test_sersic_trunc = [0., 8.5]

    if __name__ != "__main__":
        # If doing a pytest run, we don't actually need to do all 4 sersic n values.
        # Two should be enough to notice if there is a problem, and the full list will be tested
        # when running python test_base.py to try to diagnose the problem.
        test_sersic_n = [1.5, -4]
    else:
        test_sersic_n = [1.5, 2.5, 4, -4]  # -4 means use explicit DeVauc rather than n=4

    # loop through sersic n
    for test_n in test_sersic_n:
        # loop through sersic truncation
        for test_trunc in test_sersic_trunc:
            # init with hlr and flux only (should be ok given last tests)
            # n=-4 is code to use explicit DeVaucouleurs rather than Sersic(n=4).
            # It should be identical.
            if test_n == -4:
                init_obj = galsim.DeVaucouleurs(half_light_radius=test_hlr, flux=test_flux,
                                           trunc=test_trunc)
            else:
                init_obj = galsim.Sersic(test_n, half_light_radius=test_hlr, flux=test_flux,
                                    trunc=test_trunc)

            obj2 = init_obj * 2.
            np.testing.assert_almost_equal(
                init_obj.flux, test_flux, decimal=param_decimal,
                err_msg="Flux param inconsistent after __rmul__ (original).")
            np.testing.assert_almost_equal(
                obj2.flux, test_flux * 2., decimal=param_decimal,
                err_msg="Flux param inconsistent after __rmul__ (result).")

            obj2 = 2. * init_obj
            np.testing.assert_almost_equal(
                init_obj.flux, test_flux, decimal=param_decimal,
                err_msg="Flux param inconsistent after __mul__ (original).")
            np.testing.assert_almost_equal(
                obj2.flux, test_flux * 2., decimal=param_decimal,
                err_msg="Flux param inconsistent after __mul__ (result).")

            obj2 = init_obj / 2.
            np.testing.assert_almost_equal(
                 init_obj.flux, test_flux, decimal=param_decimal,
                 err_msg="Flux param inconsistent after __div__ (original).")
            np.testing.assert_almost_equal(
                obj2.flux, test_flux / 2., decimal=param_decimal,
                err_msg="Flux param inconsistent after __div__ (result).")