def compare_dft_vs_photon_object(gsobject,
                                 psf_object=None,
                                 rng=None,
                                 pixel_scale=1.,
                                 size=512,
                                 wmult=4.,
                                 abs_tol_ellip=1.e-5,
                                 abs_tol_size=1.e-5,
                                 n_trials_per_iter=32,
                                 n_photons_per_trial=1e7,
                                 moments=True,
                                 hsm=False):
    """Take an input object (with optional PSF) and render it in two ways comparing results at high
    precision.

    Using both photon shooting (via drawShoot()) and Discrete Fourier Transform (via draw()) to
    render images, we compare the numerical values of adaptive moments estimates of size and
    ellipticity to check consistency.

    This function takes actual GSObjects as its input, but because these are not yet picklable this
    means that the internals cannot be parallelized using the Python multiprocessing module.  For
    a parallelized function, that instead uses a config dictionary to specify the test objects, see
    the function compare_dft_vs_photon_config() in this module.

    We generate successive sets of `n_trials_per_iter` photon-shot images, using 
    `n_photons_per_trial` photons in each image, until the standard error on the mean absolute size
    and ellipticity drop below `abs_tol_size` and `abs_tol_ellip`.  We then output a
    ComparisonShapeData object which stores the results.

    Note that `n_photons_per_trial` should be large (>~ 1e6) to ensure that any biases detected
    between the photon shooting and DFT-drawn images are due to numerical differences rather than
    biases on adaptive moments due to noise itself, a generic feature in this work.  This can be
    verified with a convergence test.

    @param gsobject         The GSObject for which this test is to be performed (prior
                            to PSF convolution if a PSF is also supplied via `psf_object`).
                            Note that this function will automatically handle integration over
                            a Pixel of width `pixel_scale`, so a Pixel should not be included in
                            the supplied `gsobject` (unless you really mean to include it, which
                            will be very rare in normal usage).
    @param psf_object       Optional additional PSF for tests of convolved objects, also a
                            GSObject.  Note that this function will automatically handle
                            integration over a Pixel of width `pixel_scale`, so this should not
                            be included in the supplied `psf_object`.  [default: None]
    @param rng              A BaseDeviate or derived deviate class instance to provide
                            the pseudo random numbers for the photon shooting.  [default: None]
    @param pixel_scale      The pixel scale to use in the test images. [default: 1]
    @param size             The size of the images in the rendering tests - all test images
                            are currently square. [default: 512]
    @param wmult            The `wmult` parameter used in .draw() (see the GSObject .draw()
                            method docs via `help(galsim.GSObject.draw)` for more details).
                            [default: 4]
    @param abs_tol_ellip    The test will keep iterating, adding ever greater numbers of
                            trials, until estimates of the 1-sigma standard error on mean 
                            ellipticity moments from photon-shot images are smaller than this
                            param value. [default: 1.e-5]
    @param abs_tol_size     The test will keep iterating, adding ever greater numbers of
                            trials, until estimates of the 1-sigma standard error on mean 
                            size moments from photon-shot images are smaller than this param
                            value. [default: 1.e-5]
    @param n_trials_per_iter  Number of trial images used to estimate (or successively
                            re-estimate) the standard error on the delta quantities above for
                            each iteration of the tests. [default: 32]
    @param n_photons_per_trial  Number of photons shot in drawShoot() for each trial.  This should
                            be large enough that any noise bias (a.k.a. noise rectification
                            bias) on moments estimates is small. [default: 1e7]
    @param moments          Set True to compare rendered images using AdaptiveMoments
                            estimates of simple observed estimates. [default: True]
    @param hsm              Should the rendered images be compared using HSM shear estimates?
                            (i.e. including a PSF correction for shears) [not implemented]
    """
    import sys
    import logging
    import time

    # Some sanity checks on inputs
    if hsm is True:
        if psf_object is None:
            raise ValueError(
                'An input psf_object is required for HSM shear estimate testing.'
            )
        else:
            # Raise an apologetic exception about the HSM not yet being implemented!
            raise NotImplementedError('Sorry, HSM tests not yet implemented!')

    if rng is None:
        rng = galsim.BaseDeviate()

    # Then define some convenience functions for handling lists and multiple trial operations
    def _mean(array_like):
        return np.mean(np.asarray(array_like))

    def _stderr(array_like):
        return np.std(np.asarray(array_like)) / np.sqrt(len(array_like))

    def _shoot_trials_single(gsobject, ntrials, dx, imsize, rng, n_photons):
        """Convenience function to run `ntrials` and collect the results, uses only a single core.

        Uses a Python for loop but this is very unlikely to be a rate determining factor provided
        n_photons is suitably large (>1e6).
        """
        g1obslist = []
        g2obslist = []
        sigmalist = []
        im = galsim.ImageF(imsize, imsize)
        for i in xrange(ntrials):
            gsobject.drawShoot(im, dx=dx, n_photons=n_photons, rng=rng)
            res = im.FindAdaptiveMom()
            g1obslist.append(res.observed_shape.g1)
            g2obslist.append(res.observed_shape.g2)
            sigmalist.append(res.moments_sigma)
            logging.debug('Completed ' + str(i + 1) + '/' + str(ntrials) +
                          ' trials in this iteration')
            #im.write('check_shoot_trial'+str(i + 1)) CHECK IMAGE
        return g1obslist, g2obslist, sigmalist

    # OK, that's the end of the helper functions-within-helper functions, back to the main unit

    # Start the timer
    t1 = time.time()

    # If a PSF is supplied, do the convolution, otherwise just use the gal_object
    if psf_object is None:
        logging.info(
            'No psf_object supplied, running tests using input gsobject only')
        test_object = gsobject
    else:
        logging.info(
            'Generating test_object by convolving gsobject with input psf_object'
        )
        test_object = galsim.Convolve([gsobject, psf_object])

    # Draw the FFT image, only needs to be done once
    # For the FFT drawn image we need to include the galsim.Pixel, for the photon shooting we don't!
    test_object_pixelized = galsim.Convolve(
        [test_object, galsim.Pixel(pixel_scale)])
    im_draw = galsim.ImageF(size, size)
    test_object_pixelized.draw(im_draw, dx=pixel_scale, wmult=wmult)
    res_draw = im_draw.FindAdaptiveMom()
    sigma_draw = res_draw.moments_sigma
    g1obs_draw = res_draw.observed_shape.g1
    g2obs_draw = res_draw.observed_shape.g2

    # Setup storage lists for the trial shooting results
    sigma_shoot_list = []
    g1obs_shoot_list = []
    g2obs_shoot_list = []
    sigmaerr = 666.  # Slightly kludgy but will not accidentally fail the first `while` condition
    g1obserr = 666.
    g2obserr = 666.

    # Initialize iteration counter
    itercount = 0

    # Then begin while loop, farming out sets of n_trials_per_iter trials until we get the
    # statistical accuracy we require
    while (g1obserr > abs_tol_ellip) or (g2obserr > abs_tol_ellip) or (
            sigmaerr > abs_tol_size):

        # Run the trials using helper function
        g1obs_list_tmp, g2obs_list_tmp, sigma_list_tmp = _shoot_trials_single(
            test_object, n_trials_per_iter, pixel_scale, size, rng,
            n_photons_per_trial)

        # Collect results and calculate new standard error
        g1obs_shoot_list.extend(g1obs_list_tmp)
        g2obs_shoot_list.extend(g2obs_list_tmp)
        sigma_shoot_list.extend(sigma_list_tmp)
        g1obserr = _stderr(g1obs_shoot_list)
        g2obserr = _stderr(g2obs_shoot_list)
        sigmaerr = _stderr(sigma_shoot_list)
        itercount += 1
        sys.stdout.write(
            "."
        )  # This doesn't add a carriage return at the end of the line, nice!
        logging.debug('Completed ' + str(itercount) + ' iterations')
        logging.debug('(g1obserr, g2obserr, sigmaerr) = ' + str(g1obserr) +
                      ', ' + str(g2obserr) + ', ' + str(sigmaerr))

    sys.stdout.write("\n")

    # Take the runtime and collate results into a ComparisonShapeData
    runtime = time.time() - t1
    results = ComparisonShapeData(g1obs_draw,
                                  g2obs_draw,
                                  sigma_draw,
                                  _mean(g1obs_shoot_list),
                                  _mean(g2obs_shoot_list),
                                  _mean(sigma_shoot_list),
                                  g1obserr,
                                  g2obserr,
                                  sigmaerr,
                                  size,
                                  pixel_scale,
                                  wmult,
                                  itercount,
                                  n_trials_per_iter,
                                  n_photons_per_trial,
                                  runtime,
                                  gsobject=gsobject,
                                  psf_object=psf_object)

    logging.info('\n' + str(results))
    return results
Example #2
0
def estimate(n, p, g1, g2, el, s, show_last_gal, plot_progression, update_freq,
             typ, pxl):

    shear = []
    shear.append(g1)  # lensing shear to apply
    shear.append(g2)
    stamp_xsize = p
    stamp_ysize = p
    random_seed = 4218409
    pixel_scale = 1.0
    sky_level = 1.e6
    gal_sigma = s
    gal_flux = 1.0
    ###########

    print "\nPixel width and height is", p
    print "Applied shear is", shear
    print "Galaxy sigma in pixels", s
    print "Ellipticity is", el
    print "Number of galaxies is", n, '\n'
    if pxl:
        print "Will convolve with pixel"
    else:
        print "Will not convolve with pixel"
    if typ == 'g':
        print "Galaxy type is gaussian"
    elif typ == 'e':
        print "Galaxy type is exponential"
    else:
        print "Galaxy type unrecognized. Sersic not implemented yet."

    #gi=(sqrt(1+el)-sqrt(1-el))/(sqrt(1+el)+sqrt(1-el)) #shear due to intrinsic ellipticity

    px = []
    py = []
    py2 = []
    py3 = []
    py4 = []

    img = galsim.ImageD(stamp_xsize, stamp_ysize, scale=pixel_scale)

    first_in_pair = True

    storeXY(stamp_xsize, stamp_ysize)
    #storeXY(3,3)
    #print XX
    #print YY
    #print XY

    #start = timeit.default_timer()
    for i in range(0, n):

        ud = galsim.UniformDeviate(random_seed + i)
        if first_in_pair:
            theta = ud() * 2. * pi * galsim.radians
            first_in_pair = False
        else:
            theta += 90 * galsim.degrees
            first_in_pair = True

        if typ == 'g':
            profile = galsim.Gaussian(sigma=gal_sigma, flux=gal_flux)
        elif typ == 'e':
            profile = galsim.Exponential(scale_radius=gal_sigma / 2.,
                                         flux=gal_flux)
        else:
            print "Unrecognized galaxy type"
            sys.exit(2)

        gal = profile.createSheared(e=el, beta=theta)
        #gal=profile

        g = sqrt(shear[0]**2. + shear[1]**2.)
        gal.applyLensing(g1=shear[0], g2=shear[1], mu=1. / (1. - 2. * (g**2.)))

        if pxl:
            pix = galsim.Pixel(pixel_scale)
            final = galsim.Convolve([gal, pix])
        else:
            final = gal

        #psf = galsim.Gaussian(sigma=1.0)
        final.draw(img)

        #myimg=drawEllipse(shear[0],shear[1],stamp_xsize,stamp_ysize,s)

        infarr = img.array
        q = getQuad(infarr, pxl, *np.shape(infarr))
        E = polE(q)

        if ((i % update_freq) is 0) and (i > 0):
            print "Done " + str(i) + " galaxies..."

        py.append(0.5 * E[0])
        py2.append(0.5 * E[1])
        if plot_progression:
            px.append(i + 1)
            py3.append(np.array(py).mean())
            py4.append(np.array(py2).mean())

    #stop = timeit.default_timer()
    #print "\nAverage time spent on one galaxy: ", (stop-start)/(i+1)

    if plot_progression:
        plt.clf()
        ax = plt.subplot(1, 1, 1)

        ax.set_xlabel("Number of galaxies")
        ax.set_ylabel("Inferred shear")
        ax.plot(px, py3, 'ro')
        ax.plot(px, py4, 'bx')
        ax.axhline(y=shear[0])
        ax.axhline(y=shear[1])

    print "\nApplied shear is " + str(shear)

    for i, pp in enumerate([py, py2]):
        ## we are doing this clever rotation
        ## so we need to reduce by 2
        pp = [(pp[2 * c] + pp[2 * c + 1]) / 2.0 for c in range(len(pp) / 2)]
        p = np.array(pp)
        inf = p.mean()
        sh = shear[i]
        err = p.std() / sqrt(len(p))
        print "Inferred shear" + str(
            i + 1) + " is", inf, "+/-", err, "off by ", (
                inf - sh) * 100 / sh, " %", (inf - sh) / err, " sigma"

    if show_last_gal:
        plt.subplot(2, 2, 1)
        arr = img.array / img.array.sum()
        plt.imshow(arr, interpolation='nearest')
        plt.colorbar()
        #plt.subplot (2,2,2)
        #plt.imshow(myimg, interpolation='nearest')
        #plt.colorbar()
        #plt.subplot (2,2,3)
        #plt.imshow((arr-myimg)/(myimg+arr+1e-5), interpolation='nearest')
        #plt.imshow((arr-myimg)/(myimg+1e-5), interpolation='nearest')
        #plt.imshow(img.array-img2.array, interpolation='nearest')
        #plt.colorbar()

    if show_last_gal or plot_progression:
        plt.show()
Example #3
0
def test_operations_simple():
    """Simple test of operations on InterpolatedImage: shear, magnification, rotation, shifting."""
    import time
    t1 = time.time()

    # Make some nontrivial image that can be described in terms of sums and convolutions of
    # GSObjects.  We want this to be somewhat hard to describe, but should be at least
    # critically-sampled, so put in an Airy PSF.
    gal_flux = 1000.
    pix_scale = 0.03  # arcsec
    bulge_frac = 0.3
    bulge_hlr = 0.3  # arcsec
    bulge_e = 0.15
    bulge_pos_angle = 30. * galsim.degrees
    disk_hlr = 0.6  # arcsec
    disk_e = 0.5
    disk_pos_angle = 60. * galsim.degrees
    lam = 800  # nm    NB: don't use lambda - that's a reserved word.
    tel_diam = 2.4  # meters
    lam_over_diam = lam * 1.e-9 / tel_diam  # radians
    lam_over_diam *= 206265  # arcsec
    im_size = 512

    bulge = galsim.Sersic(4, half_light_radius=bulge_hlr)
    bulge.applyShear(e=bulge_e, beta=bulge_pos_angle)
    disk = galsim.Exponential(half_light_radius=disk_hlr)
    disk.applyShear(e=disk_e, beta=disk_pos_angle)
    gal = bulge_frac * bulge + (1. - bulge_frac) * disk
    gal.setFlux(gal_flux)
    psf = galsim.Airy(lam_over_diam)
    pix = galsim.Pixel(pix_scale)
    obj = galsim.Convolve(gal, psf, pix)
    im = obj.draw(dx=pix_scale)

    # Turn it into an InterpolatedImage with default param settings
    int_im = galsim.InterpolatedImage(im)

    # Shear it, and compare with expectations from GSObjects directly
    test_g1 = -0.07
    test_g2 = 0.1
    test_decimal = 2  # in % difference, i.e. 2 means 1% agreement
    comp_region = 30  # compare the central region of this linear size
    test_int_im = int_im.createSheared(g1=test_g1, g2=test_g2)
    ref_obj = obj.createSheared(g1=test_g1, g2=test_g2)
    # make large images
    im = galsim.ImageD(im_size, im_size)
    ref_im = galsim.ImageD(im_size, im_size)
    test_int_im.draw(image=im, dx=pix_scale)
    ref_obj.draw(image=ref_im, dx=pix_scale)
    # define subregion for comparison
    new_bounds = galsim.BoundsI(1, comp_region, 1, comp_region)
    new_bounds.shift((im_size - comp_region) / 2, (im_size - comp_region) / 2)
    im_sub = im.subImage(new_bounds)
    ref_im_sub = ref_im.subImage(new_bounds)
    diff_im = im_sub - ref_im_sub
    rel = diff_im / im_sub
    zeros_arr = np.zeros((comp_region, comp_region))
    # require relative difference to be smaller than some amount
    np.testing.assert_array_almost_equal(
        rel.array,
        zeros_arr,
        test_decimal,
        err_msg='Sheared InterpolatedImage disagrees with reference')

    # Magnify it, and compare with expectations from GSObjects directly
    test_mag = 1.08
    test_decimal = 2  # in % difference, i.e. 2 means 1% agreement
    comp_region = 30  # compare the central region of this linear size
    test_int_im = int_im.createMagnified(test_mag)
    ref_obj = obj.createMagnified(test_mag)
    # make large images
    im = galsim.ImageD(im_size, im_size)
    ref_im = galsim.ImageD(im_size, im_size)
    test_int_im.draw(image=im, dx=pix_scale)
    ref_obj.draw(image=ref_im, dx=pix_scale)
    # define subregion for comparison
    new_bounds = galsim.BoundsI(1, comp_region, 1, comp_region)
    new_bounds.shift((im_size - comp_region) / 2, (im_size - comp_region) / 2)
    im_sub = im.subImage(new_bounds)
    ref_im_sub = ref_im.subImage(new_bounds)
    diff_im = im_sub - ref_im_sub
    rel = diff_im / im_sub
    zeros_arr = np.zeros((comp_region, comp_region))
    # require relative difference to be smaller than some amount
    np.testing.assert_array_almost_equal(
        rel.array,
        zeros_arr,
        test_decimal,
        err_msg='Magnified InterpolatedImage disagrees with reference')

    # Lens it (shear and magnify), and compare with expectations from GSObjects directly
    test_g1 = -0.03
    test_g2 = -0.04
    test_mag = 0.74
    test_decimal = 2  # in % difference, i.e. 2 means 1% agreement
    comp_region = 30  # compare the central region of this linear size
    test_int_im = int_im.createLensed(test_g1, test_g2, test_mag)
    ref_obj = obj.createLensed(test_g1, test_g2, test_mag)
    # make large images
    im = galsim.ImageD(im_size, im_size)
    ref_im = galsim.ImageD(im_size, im_size)
    test_int_im.draw(image=im, dx=pix_scale)
    ref_obj.draw(image=ref_im, dx=pix_scale)
    # define subregion for comparison
    new_bounds = galsim.BoundsI(1, comp_region, 1, comp_region)
    new_bounds.shift((im_size - comp_region) / 2, (im_size - comp_region) / 2)
    im_sub = im.subImage(new_bounds)
    ref_im_sub = ref_im.subImage(new_bounds)
    diff_im = im_sub - ref_im_sub
    rel = diff_im / im_sub
    zeros_arr = np.zeros((comp_region, comp_region))
    # require relative difference to be smaller than some amount
    np.testing.assert_array_almost_equal(
        rel.array,
        zeros_arr,
        test_decimal,
        err_msg='Lensed InterpolatedImage disagrees with reference')

    # Rotate it, and compare with expectations from GSObjects directly
    test_rot_angle = 32. * galsim.degrees
    test_decimal = 2  # in % difference, i.e. 2 means 1% agreement
    comp_region = 30  # compare the central region of this linear size
    test_int_im = int_im.createRotated(test_rot_angle)
    ref_obj = obj.createRotated(test_rot_angle)
    # make large images
    im = galsim.ImageD(im_size, im_size)
    ref_im = galsim.ImageD(im_size, im_size)
    test_int_im.draw(image=im, dx=pix_scale)
    ref_obj.draw(image=ref_im, dx=pix_scale)
    # define subregion for comparison
    new_bounds = galsim.BoundsI(1, comp_region, 1, comp_region)
    new_bounds.shift((im_size - comp_region) / 2, (im_size - comp_region) / 2)
    im_sub = im.subImage(new_bounds)
    ref_im_sub = ref_im.subImage(new_bounds)
    diff_im = im_sub - ref_im_sub
    rel = diff_im / im_sub
    zeros_arr = np.zeros((comp_region, comp_region))
    # require relative difference to be smaller than some amount
    np.testing.assert_array_almost_equal(
        rel.array,
        zeros_arr,
        test_decimal,
        err_msg='Rotated InterpolatedImage disagrees with reference')

    # Shift it, and compare with expectations from GSObjects directly
    x_shift = -0.31
    y_shift = 0.87
    test_decimal = 2  # in % difference, i.e. 2 means 1% agreement
    comp_region = 30  # compare the central region of this linear size
    test_int_im = int_im.createShifted(x_shift, y_shift)
    ref_obj = obj.createShifted(x_shift, y_shift)
    # make large images
    im = galsim.ImageD(im_size, im_size)
    ref_im = galsim.ImageD(im_size, im_size)
    test_int_im.draw(image=im, dx=pix_scale)
    ref_obj.draw(image=ref_im, dx=pix_scale)
    # define subregion for comparison
    new_bounds = galsim.BoundsI(1, comp_region, 1, comp_region)
    new_bounds.shift((im_size - comp_region) / 2, (im_size - comp_region) / 2)
    im_sub = im.subImage(new_bounds)
    ref_im_sub = ref_im.subImage(new_bounds)
    diff_im = im_sub - ref_im_sub
    rel = diff_im / im_sub
    zeros_arr = np.zeros((comp_region, comp_region))
    # require relative difference to be smaller than some amount
    np.testing.assert_array_almost_equal(
        rel.array,
        zeros_arr,
        test_decimal,
        err_msg='Shifted InterpolatedImage disagrees with reference')

    t2 = time.time()
    print 'time for %s = %.2f' % (funcname(), t2 - t1)
Example #4
0
def test_flip():
    """Test several ways to flip a profile
    """
    # The Shapelet profile has the advantage of being fast and not circularly symmetric, so
    # it is a good test of the actual code for doing the flips (in SBTransform).
    # But since the bug Rachel reported in #645 was actually in SBInterpolatedImage
    # (one calculation implicitly assumed dx > 0), it seems worthwhile to run through all the
    # classes to make sure we hit everything with negative steps for dx and dy.
    prof_list = [
        galsim.Shapelet(sigma=0.17, order=2,
                        bvec=[1.7, 0.01,0.03, 0.29, 0.33, -0.18]),
    ]
    if __name__ == "__main__":
        image_dir = './real_comparison_images'
        catalog_file = 'test_catalog.fits'
        rgc = galsim.RealGalaxyCatalog(catalog_file, dir=image_dir)
        # Some of these are slow, so only do the Shapelet test as part of the normal unit tests.
        prof_list += [
            galsim.Airy(lam_over_diam=0.17, flux=1.7),
            galsim.Airy(lam_over_diam=0.17, obscuration=0.2, flux=1.7),
            # Box gets rendered with real-space convolution.  The default accuracy isn't quite
            # enough to get the flip to match at 6 decimal places.
            galsim.Box(0.17, 0.23, flux=1.7,
                       gsparams=galsim.GSParams(realspace_relerr=1.e-6)),
            # Without being convolved by anything with a reasonable k cutoff, this needs
            # a very large fft.
            galsim.DeVaucouleurs(half_light_radius=0.17, flux=1.7),
            # I don't really understand why this needs a lower maxk_threshold to work, but
            # without it, the k-space tests fail.
            galsim.Exponential(scale_radius=0.17, flux=1.7,
                               gsparams=galsim.GSParams(maxk_threshold=1.e-4)),
            galsim.Gaussian(sigma=0.17, flux=1.7),
            galsim.Kolmogorov(fwhm=0.17, flux=1.7),
            galsim.Moffat(beta=2.5, fwhm=0.17, flux=1.7),
            galsim.Moffat(beta=2.5, fwhm=0.17, flux=1.7, trunc=0.82),
            galsim.OpticalPSF(lam_over_diam=0.17, obscuration=0.2, nstruts=6,
                              coma1=0.2, coma2=0.5, defocus=-0.1, flux=1.7),
            # Like with Box, we need to increase the real-space convolution accuracy.
            # This time lowering both relerr and abserr.
            galsim.Pixel(0.23, flux=1.7,
                         gsparams=galsim.GSParams(realspace_relerr=1.e-6,
                                                  realspace_abserr=1.e-8)),
            # Note: RealGalaxy should not be rendered directly because of the deconvolution.
            # Here we convolve it by a Gaussian that is slightly larger than the original PSF.
            galsim.Convolve([ galsim.RealGalaxy(rgc, index=0, flux=1.7),  # "Real" RealGalaxy
                              galsim.Gaussian(sigma=0.08) ]),
            galsim.Convolve([ galsim.RealGalaxy(rgc, index=1, flux=1.7),  # "Fake" RealGalaxy
                              galsim.Gaussian(sigma=0.08) ]),             # (cf. test_real.py)
            galsim.Spergel(nu=-0.19, half_light_radius=0.17, flux=1.7),
            galsim.Spergel(nu=0., half_light_radius=0.17, flux=1.7),
            galsim.Spergel(nu=0.8, half_light_radius=0.17, flux=1.7),
            galsim.Sersic(n=2.3, half_light_radius=0.17, flux=1.7),
            galsim.Sersic(n=2.3, half_light_radius=0.17, flux=1.7, trunc=0.82),
            # The shifts here caught a bug in how SBTransform handled the recentering.
            # Two of the shifts (0.125 and 0.375) lead back to 0.0 happening on an integer
            # index, which now works correctly.
            galsim.Sum([ galsim.Gaussian(sigma=0.17, flux=1.7).shift(-0.2,0.125),
                         galsim.Exponential(scale_radius=0.23, flux=3.1).shift(0.375,0.23)]),
            galsim.TopHat(0.23, flux=1.7),
            # Box and Pixel use real-space convolution.  Convolve with a Gaussian to get fft.
            galsim.Convolve([ galsim.Box(0.17, 0.23, flux=1.7).shift(-0.2,0.1),
                              galsim.Gaussian(sigma=0.09) ]),
            galsim.Convolve([ galsim.TopHat(0.17, flux=1.7).shift(-0.275,0.125),
                              galsim.Gaussian(sigma=0.09) ]),
            # Test something really crazy with several layers worth of transformations
            galsim.Convolve([
                galsim.Sum([
                    galsim.Gaussian(sigma=0.17, flux=1.7).shear(g1=0.1,g2=0.2).shift(2,3),
                    galsim.Kolmogorov(fwhm=0.33, flux=3.9).transform(0.31,0.19,-0.23,0.33) * 88.,
                    galsim.Box(0.11, 0.44, flux=4).rotate(33 * galsim.degrees) / 1.9
                ]).shift(-0.3,1),
                galsim.AutoConvolve(galsim.TopHat(0.5).shear(g1=0.3,g2=0)).rotate(3*galsim.degrees),
                (galsim.AutoCorrelate(galsim.Box(0.2, 0.3)) * 11).shift(3,2).shift(2,-3) * 0.31
            ]).shift(0,0).transform(0,-1,-1,0).shift(-1,1)
        ]

    s = galsim.Shear(g1=0.11, g2=-0.21)
    s1 = galsim.Shear(g1=0.11, g2=0.21)  # Appropriate for the flips around x and y axes
    s2 = galsim.Shear(g1=-0.11, g2=-0.21)  # Appropriate for the flip around x=y

    # Also use shears with just a g1 to get dx != dy, but dxy, dyx = 0.
    q = galsim.Shear(g1=0.11, g2=0.)
    q1 = galsim.Shear(g1=0.11, g2=0.)  # Appropriate for the flips around x and y axes
    q2 = galsim.Shear(g1=-0.11, g2=0.)  # Appropriate for the flip around x=y

    decimal=6  # Oddly, these aren't as precise as I would have expected.
               # Even when we only go to this many digits of accuracy, the Exponential needed
               # a lower than default value for maxk_threshold.
    im = galsim.ImageD(16,16, scale=0.05)

    for prof in prof_list:
        print('prof = ',prof)

        # Not all profiles are expected to have a max_sb value close to the maximum pixel value,
        # so mark the ones where we don't want to require this to be true.
        close_maxsb = True
        name = str(prof)
        if ('DeVauc' in name or 'Sersic' in name or 'Spergel' in name or
            'Optical' in name or 'shift' in name):
            close_maxsb = False

        # Make sure we hit all 4 fill functions.
        # image_x uses fillXValue with izero, jzero
        # image_x1 uses fillXValue with izero, jzero, and unequal dx,dy
        # image_x2 uses fillXValue with dxy, dyx
        # image_k uses fillKValue with izero, jzero
        # image_k1 uses fillKValue with izero, jzero, and unequal dx,dy
        # image_k2 uses fillKValue with dxy, dyx
        image_x = prof.drawImage(image=im.copy(), method='no_pixel')
        image_x1 = prof.shear(q).drawImage(image=im.copy(), method='no_pixel')
        image_x2 = prof.shear(s).drawImage(image=im.copy(), method='no_pixel')
        image_k = prof.drawImage(image=im.copy())
        image_k1 = prof.shear(q).drawImage(image=im.copy())
        image_k2 = prof.shear(s).drawImage(image=im.copy())

        if close_maxsb:
            np.testing.assert_allclose(
                    image_x.array.max(), prof.max_sb*im.scale**2, rtol=0.2,
                    err_msg="max_sb did not match maximum pixel value")
            np.testing.assert_allclose(
                    image_x1.array.max(), prof.shear(q).max_sb*im.scale**2, rtol=0.2,
                    err_msg="max_sb did not match maximum pixel value")
            np.testing.assert_allclose(
                    image_x2.array.max(), prof.shear(s).max_sb*im.scale**2, rtol=0.2,
                    err_msg="max_sb did not match maximum pixel value")

        # Flip around y axis (i.e. x -> -x)
        flip1 = prof.transform(-1, 0, 0, 1)
        image2_x = flip1.drawImage(image=im.copy(), method='no_pixel')
        np.testing.assert_array_almost_equal(
            image_x.array, image2_x.array[:,::-1], decimal=decimal,
            err_msg="Flipping image around y-axis failed x test")
        image2_x1 = flip1.shear(q1).drawImage(image=im.copy(), method='no_pixel')
        np.testing.assert_array_almost_equal(
            image_x1.array, image2_x1.array[:,::-1], decimal=decimal,
            err_msg="Flipping image around y-axis failed x1 test")
        image2_x2 = flip1.shear(s1).drawImage(image=im.copy(), method='no_pixel')
        np.testing.assert_array_almost_equal(
            image_x2.array, image2_x2.array[:,::-1], decimal=decimal,
            err_msg="Flipping image around y-axis failed x2 test")
        image2_k = flip1.drawImage(image=im.copy())
        np.testing.assert_array_almost_equal(
            image_k.array, image2_k.array[:,::-1], decimal=decimal,
            err_msg="Flipping image around y-axis failed k test")
        image2_k1 = flip1.shear(q1).drawImage(image=im.copy())
        np.testing.assert_array_almost_equal(
            image_k1.array, image2_k1.array[:,::-1], decimal=decimal,
            err_msg="Flipping image around y-axis failed k1 test")
        image2_k2 = flip1.shear(s1).drawImage(image=im.copy())
        np.testing.assert_array_almost_equal(
            image_k2.array, image2_k2.array[:,::-1], decimal=decimal,
            err_msg="Flipping image around y-axis failed k2 test")

        if close_maxsb:
            np.testing.assert_allclose(
                    image2_x.array.max(), flip1.max_sb*im.scale**2, rtol=0.2,
                    err_msg="max_sb did not match maximum pixel value")
            np.testing.assert_allclose(
                    image2_x1.array.max(), flip1.shear(q).max_sb*im.scale**2, rtol=0.2,
                    err_msg="max_sb did not match maximum pixel value")
            np.testing.assert_allclose(
                    image2_x2.array.max(), flip1.shear(s).max_sb*im.scale**2, rtol=0.2,
                    err_msg="max_sb did not match maximum pixel value")

        # Flip around x axis (i.e. y -> -y)
        flip2 = prof.transform(1, 0, 0, -1)
        image2_x = flip2.drawImage(image=im.copy(), method='no_pixel')
        np.testing.assert_array_almost_equal(
            image_x.array, image2_x.array[::-1,:], decimal=decimal,
            err_msg="Flipping image around x-axis failed x test")
        image2_x1 = flip2.shear(q1).drawImage(image=im.copy(), method='no_pixel')
        np.testing.assert_array_almost_equal(
            image_x1.array, image2_x1.array[::-1,:], decimal=decimal,
            err_msg="Flipping image around x-axis failed x1 test")
        image2_x2 = flip2.shear(s1).drawImage(image=im.copy(), method='no_pixel')
        np.testing.assert_array_almost_equal(
            image_x2.array, image2_x2.array[::-1,:], decimal=decimal,
            err_msg="Flipping image around x-axis failed x2 test")
        image2_k = flip2.drawImage(image=im.copy())
        np.testing.assert_array_almost_equal(
            image_k.array, image2_k.array[::-1,:], decimal=decimal,
            err_msg="Flipping image around x-axis failed k test")
        image2_k1 = flip2.shear(q1).drawImage(image=im.copy())
        np.testing.assert_array_almost_equal(
            image_k1.array, image2_k1.array[::-1,:], decimal=decimal,
            err_msg="Flipping image around x-axis failed k1 test")
        image2_k2 = flip2.shear(s1).drawImage(image=im.copy())
        np.testing.assert_array_almost_equal(
            image_k2.array, image2_k2.array[::-1,:], decimal=decimal,
            err_msg="Flipping image around x-axis failed k2 test")

        if close_maxsb:
            np.testing.assert_allclose(
                    image2_x.array.max(), flip2.max_sb*im.scale**2, rtol=0.2,
                    err_msg="max_sb did not match maximum pixel value")
            np.testing.assert_allclose(
                    image2_x1.array.max(), flip2.shear(q).max_sb*im.scale**2, rtol=0.2,
                    err_msg="max_sb did not match maximum pixel value")
            np.testing.assert_allclose(
                    image2_x2.array.max(), flip2.shear(s).max_sb*im.scale**2, rtol=0.2,
                    err_msg="max_sb did not match maximum pixel value")

        # Flip around x=y (i.e. y -> x, x -> y)
        flip3 = prof.transform(0, 1, 1, 0)
        image2_x = flip3.drawImage(image=im.copy(), method='no_pixel')
        np.testing.assert_array_almost_equal(
            image_x.array, np.transpose(image2_x.array), decimal=decimal,
            err_msg="Flipping image around x=y failed x test")
        image2_x1 = flip3.shear(q2).drawImage(image=im.copy(), method='no_pixel')
        np.testing.assert_array_almost_equal(
            image_x1.array, np.transpose(image2_x1.array), decimal=decimal,
            err_msg="Flipping image around x=y failed x1 test")
        image2_x2 = flip3.shear(s2).drawImage(image=im.copy(), method='no_pixel')
        np.testing.assert_array_almost_equal(
            image_x2.array, np.transpose(image2_x2.array), decimal=decimal,
            err_msg="Flipping image around x=y failed x2 test")
        image2_k = flip3.drawImage(image=im.copy())
        np.testing.assert_array_almost_equal(
            image_k.array, np.transpose(image2_k.array), decimal=decimal,
            err_msg="Flipping image around x=y failed k test")
        image2_k1 = flip3.shear(q2).drawImage(image=im.copy())
        np.testing.assert_array_almost_equal(
            image_k1.array, np.transpose(image2_k1.array), decimal=decimal,
            err_msg="Flipping image around x=y failed k1 test")
        image2_k2 = flip3.shear(s2).drawImage(image=im.copy())
        np.testing.assert_array_almost_equal(
            image_k2.array, np.transpose(image2_k2.array), decimal=decimal,
            err_msg="Flipping image around x=y failed k2 test")

        if close_maxsb:
            np.testing.assert_allclose(
                    image2_x.array.max(), flip3.max_sb*im.scale**2, rtol=0.2,
                    err_msg="max_sb did not match maximum pixel value")
            np.testing.assert_allclose(
                    image2_x1.array.max(), flip3.shear(q).max_sb*im.scale**2, rtol=0.2,
                    err_msg="max_sb did not match maximum pixel value")
            np.testing.assert_allclose(
                    image2_x2.array.max(), flip3.shear(s).max_sb*im.scale**2, rtol=0.2,
                    err_msg="max_sb did not match maximum pixel value")

        do_pickle(prof, lambda x: x.drawImage(image=im.copy(), method='no_pixel'))
        do_pickle(flip1, lambda x: x.drawImage(image=im.copy(), method='no_pixel'))
        do_pickle(flip2, lambda x: x.drawImage(image=im.copy(), method='no_pixel'))
        do_pickle(flip3, lambda x: x.drawImage(image=im.copy(), method='no_pixel'))
        do_pickle(prof)
        do_pickle(flip1)
        do_pickle(flip2)
        do_pickle(flip3)
Example #5
0
def test_convolve():
    """Test the convolution of a Moffat and a Box SBProfile against a known result.
    """
    import time
    t1 = time.time()

    dx = 0.2
    # Using an exact Maple calculation for the comparison.  Only accurate to 4 decimal places.
    savedImg = galsim.fits.read(os.path.join(imgdir, "moffat_pixel.fits"))
    myImg = galsim.ImageF(savedImg.bounds, scale=dx)
    myImg.setCenter(0, 0)

    # Code was formerly:
    # psf = galsim.Moffat(beta=1.5, truncationFWHM=4, flux=1, half_light_radius=1)
    #
    # ...but this is no longer quite so simple since we changed the handling of trunc to be in
    # physical units.  However, the same profile can be constructed using
    # fwhm=1.0927449310213702,
    # as calculated by interval bisection in devutils/external/calculate_moffat_radii.py
    fwhm_backwards_compatible = 1.0927449310213702
    psf = galsim.Moffat(beta=1.5,
                        fwhm=fwhm_backwards_compatible,
                        trunc=4 * fwhm_backwards_compatible,
                        flux=1)
    pixel = galsim.Pixel(scale=dx, flux=1.)
    # Note: Since both of these have hard edges, GalSim wants to do this with real_space=True.
    # Here we are intentionally tesing the Fourier convolution, so we want to suppress the
    # warning that GalSim emits.
    import warnings
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        # We'll do the real space convolution below
        conv = galsim.Convolve([psf, pixel], real_space=False)
        conv.draw(myImg,
                  scale=dx,
                  normalization="surface brightness",
                  use_true_center=False)
        np.testing.assert_array_almost_equal(
            myImg.array,
            savedImg.array,
            4,
            err_msg="Moffat convolved with Pixel disagrees with expected result"
        )

        # Other ways to do the convolution:
        conv = galsim.Convolve(psf, pixel, real_space=False)
        conv.draw(myImg,
                  scale=dx,
                  normalization="surface brightness",
                  use_true_center=False)
        np.testing.assert_array_almost_equal(
            myImg.array,
            savedImg.array,
            4,
            err_msg=
            "Using GSObject Convolve(psf,pixel) disagrees with expected result"
        )

        # Check with default_params
        conv = galsim.Convolve([psf, pixel],
                               real_space=False,
                               gsparams=default_params)
        conv.draw(myImg,
                  scale=dx,
                  normalization="surface brightness",
                  use_true_center=False)
        np.testing.assert_array_almost_equal(
            myImg.array,
            savedImg.array,
            4,
            err_msg=
            "Using GSObject Convolve([psf,pixel]) with default_params disagrees with"
            "expected result")
        conv = galsim.Convolve([psf, pixel],
                               real_space=False,
                               gsparams=galsim.GSParams())
        conv.draw(myImg,
                  scale=dx,
                  normalization="surface brightness",
                  use_true_center=False)
        np.testing.assert_array_almost_equal(
            myImg.array,
            savedImg.array,
            4,
            err_msg=
            "Using GSObject Convolve([psf,pixel]) with GSParams() disagrees with"
            "expected result")

    # Test photon shooting.
    do_shoot(conv, myImg, "Moffat * Pixel")

    t2 = time.time()
    print 'time for %s = %.2f' % (funcname(), t2 - t1)
Example #6
0
    tot_time_meas += (t2 - t1)
    mean_e1 += res.corrected_e1
    mean_e2 += res.corrected_e2
time_per_call = tot_time_meas / ntest
mean_e1 /= ntest
mean_e2 /= ntest
# check results
print "\nFor image size ", imsize, " per side, with noise, time to estimate shear was ", time_per_call, " per call"
print "Final results for e1, e2: ", mean_e1, mean_e2

# let's try something more complicated, like Sersic n=3 (same HLR as the Gaussian)
# and Kolmogorov with same FWHM of 2.5 pix, convolved with pixel
# do our conclusions still hold?
psf = galsim.Kolmogorov(fwhm=psf_fwhm)
gal = galsim.Sersic(3, half_light_radius=gal_hlr, flux=gal_flux)
pix = galsim.Pixel(pixel_scale)
gal.applyShear(e1=gal_e1, e2=gal_e2)
obj = galsim.Convolve(gal, psf, pix)
epsf = galsim.Convolve(psf, pix)
im_obj = galsim.ImageF(imsize, imsize)
im_epsf = galsim.ImageF(imsize, imsize)
im_obj = obj.draw(image=im_obj, dx=pixel_scale)
im_epsf = epsf.draw(image=im_epsf, dx=pixel_scale)

# get adaptive moments some number of times so we can average over the calls to get an average speed
time_mom = 0.0
time_shear = 0.0
for i in range(ntest):
    t1 = time.time()
    res1 = im_obj.FindAdaptiveMom(strict=False)
    t2 = time.time()
Example #7
0
def test_realspace_distorted_convolve():
    """
    The same as above, but both the Moffat and the Box are sheared, rotated and shifted
    to stress test the code that deals with this for real-space convolutions that wouldn't
    be tested otherwise.
    """
    import time
    t1 = time.time()

    dx = 0.2
    saved_img = galsim.fits.read(
        os.path.join(imgdir, "moffat_pixel_distorted.fits"))
    img = galsim.ImageF(saved_img.bounds, scale=dx)
    img.setCenter(0, 0)

    fwhm_backwards_compatible = 1.0927449310213702
    psf = galsim.Moffat(beta=1.5,
                        half_light_radius=1,
                        trunc=4 * fwhm_backwards_compatible,
                        flux=1)
    #psf = galsim.Moffat(beta=1.5, fwhm=fwhm_backwards_compatible,
    #trunc=4*fwhm_backwards_compatible, flux=1)
    psf.applyShear(g1=0.11, g2=0.17)
    psf.applyRotation(13 * galsim.degrees)
    pixel = galsim.Pixel(scale=dx, flux=1.)
    pixel.applyShear(g1=0.2, g2=0.0)
    pixel.applyRotation(80 * galsim.degrees)
    pixel.applyShift(0.13, 0.27)
    # NB: real-space is chosen automatically
    conv = galsim.Convolve([psf, pixel])
    conv.draw(img,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        img.array,
        saved_img.array,
        5,
        err_msg=
        "Using Convolve([psf,pixel]) (distorted) disagrees with expected result"
    )

    # Check with default_params
    conv = galsim.Convolve([psf, pixel], gsparams=default_params)
    conv.draw(img,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        img.array,
        saved_img.array,
        5,
        err_msg=
        "Using Convolve([psf,pixel]) (distorted) with default_params disagrees with "
        "expected result")
    conv = galsim.Convolve([psf, pixel], gsparams=galsim.GSParams())
    conv.draw(img,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        img.array,
        saved_img.array,
        5,
        err_msg=
        "Using Convolve([psf,pixel]) (distorted) with GSParams() disagrees with "
        "expected result")

    # Other ways to do the convolution:
    conv = galsim.Convolve(psf, pixel)
    conv.draw(img,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        img.array,
        saved_img.array,
        5,
        err_msg=
        "Using Convolve(psf,pixel) (distorted) disagrees with expected result")

    # The real-space convolution algorithm is not (trivially) independent of the order of
    # the two things being convolved.  So check the opposite order.
    conv = galsim.Convolve([pixel, psf])
    conv.draw(img,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        img.array,
        saved_img.array,
        5,
        err_msg=
        "Using Convolve([pixel,psf]) (distorted) disagrees with expected result"
    )

    t2 = time.time()
    print 'time for %s = %.2f' % (funcname(), t2 - t1)
Example #8
0
def test_realspace_shearconvolve():
    """Test the real-space convolution of a sheared Gaussian and a Box SBProfile against a 
       known result.
    """
    import time
    t1 = time.time()

    e1 = 0.04
    e2 = 0.0
    myShear = galsim.Shear(e1=e1, e2=e2)
    dx = 0.2
    saved_img = galsim.fits.read(
        os.path.join(imgdir, "gauss_smallshear_convolve_box.fits"))
    img = galsim.ImageF(saved_img.bounds, scale=dx)
    img.setCenter(0, 0)

    psf = galsim.Gaussian(flux=1, sigma=1)
    psf.applyShear(e1=e1, e2=e2)
    pixel = galsim.Pixel(scale=dx, flux=1.)
    conv = galsim.Convolve([psf, pixel], real_space=True)
    conv.draw(img,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        img.array,
        saved_img.array,
        5,
        err_msg=
        "Using GSObject Convolve([psf,pixel]) disagrees with expected result")

    # Check with default_params
    conv = galsim.Convolve([psf, pixel],
                           real_space=True,
                           gsparams=default_params)
    conv.draw(img,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        img.array,
        saved_img.array,
        5,
        err_msg=
        "Using GSObject Convolve([psf,pixel]) with default_params disagrees with "
        "expected result")
    conv = galsim.Convolve([psf, pixel],
                           real_space=True,
                           gsparams=galsim.GSParams())
    conv.draw(img,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        img.array,
        saved_img.array,
        5,
        err_msg=
        "Using GSObject Convolve([psf,pixel]) with GSParams() disagrees with "
        "expected result")

    # Other ways to do the convolution:
    conv = galsim.Convolve(psf, pixel, real_space=True)
    conv.draw(img,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        img.array,
        saved_img.array,
        5,
        err_msg=
        "Using GSObject Convolve(psf,pixel) disagrees with expected result")

    # The real-space convolution algorithm is not (trivially) independent of the order of
    # the two things being convolved.  So check the opposite order.
    conv = galsim.Convolve([pixel, psf], real_space=True)
    conv.draw(img,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        img.array,
        saved_img.array,
        5,
        err_msg=
        "Using GSObject Convolve([pixel,psf]) disagrees with expected result")

    t2 = time.time()
    print 'time for %s = %.2f' % (funcname(), t2 - t1)
Example #9
0
def test_realspace_convolve():
    """Test the real-space convolution of a Moffat and a Box SBProfile against a known result.
    """
    import time
    t1 = time.time()

    dx = 0.2
    # Note: Using an image created from Maple "exact" calculations.
    saved_img = galsim.fits.read(os.path.join(imgdir, "moffat_pixel.fits"))
    img = galsim.ImageF(saved_img.bounds, scale=dx)
    img.setCenter(0, 0)

    # Code was formerly:
    # psf = galsim.Moffat(beta=1.5, truncationFWHM=4, flux=1, half_light_radius=1)
    #
    # ...but this is no longer quite so simple since we changed the handling of trunc to be in
    # physical units.  However, the same profile can be constructed using
    # fwhm=1.0927449310213702,
    # as calculated by interval bisection in devutils/external/calculate_moffat_radii.py
    fwhm_backwards_compatible = 1.0927449310213702
    psf = galsim.Moffat(beta=1.5,
                        half_light_radius=1,
                        trunc=4 * fwhm_backwards_compatible,
                        flux=1)
    #psf = galsim.Moffat(beta=1.5, fwhm=fwhm_backwards_compatible,
    #trunc=4*fwhm_backwards_compatible, flux=1)
    pixel = galsim.Pixel(scale=dx, flux=1.)
    conv = galsim.Convolve([psf, pixel], real_space=True)
    conv.draw(img,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        img.array,
        saved_img.array,
        5,
        err_msg=
        "Using GSObject Convolve([psf,pixel]) disagrees with expected result")

    # Check with default_params
    conv = galsim.Convolve([psf, pixel],
                           real_space=True,
                           gsparams=default_params)
    conv.draw(img,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        img.array,
        saved_img.array,
        5,
        err_msg=
        "Using GSObject Convolve([psf,pixel]) with default_params disagrees with "
        "expected result")
    conv = galsim.Convolve([psf, pixel],
                           real_space=True,
                           gsparams=galsim.GSParams())
    conv.draw(img,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        img.array,
        saved_img.array,
        5,
        err_msg=
        "Using GSObject Convolve([psf,pixel]) with GSParams() disagrees with "
        "expected result")

    # Other ways to do the convolution:
    conv = galsim.Convolve(psf, pixel, real_space=True)
    conv.draw(img,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        img.array,
        saved_img.array,
        5,
        err_msg=
        "Using GSObject Convolve(psf,pixel) disagrees with expected result")

    # The real-space convolution algorithm is not (trivially) independent of the order of
    # the two things being convolved.  So check the opposite order.
    conv = galsim.Convolve([pixel, psf], real_space=True)
    conv.draw(img,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        img.array,
        saved_img.array,
        5,
        err_msg=
        "Using GSObject Convolve([pixel,psf]) disagrees with expected result")

    # Test kvalues
    do_kvalue(conv, "Truncated Moffat convolved with Box")

    t2 = time.time()
    print 'time for %s = %.2f' % (funcname(), t2 - t1)
Example #10
0
def test_shearconvolve():
    """Test the convolution of a sheared Gaussian and a Box SBProfile against a known result.
    """
    import time
    t1 = time.time()

    e1 = 0.04
    e2 = 0.0
    myShear = galsim.Shear(e1=e1, e2=e2)
    dx = 0.2
    savedImg = galsim.fits.read(
        os.path.join(imgdir, "gauss_smallshear_convolve_box.fits"))
    myImg = galsim.ImageF(savedImg.bounds, scale=dx)
    myImg.setCenter(0, 0)

    psf = galsim.Gaussian(flux=1, sigma=1)
    psf2 = psf.createSheared(e1=e1, e2=e2)
    psf.applyShear(e1=e1, e2=e2)
    pixel = galsim.Pixel(scale=dx, flux=1.)
    conv = galsim.Convolve([psf, pixel])
    conv.draw(myImg,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        myImg.array,
        savedImg.array,
        5,
        err_msg=
        "Using GSObject Convolve([psf,pixel]) disagrees with expected result")
    conv2 = galsim.Convolve([psf2, pixel])
    conv2.draw(myImg,
               scale=dx,
               normalization="surface brightness",
               use_true_center=False)
    np.testing.assert_array_almost_equal(
        myImg.array,
        savedImg.array,
        5,
        err_msg=
        "Using GSObject Convolve([psf,pixel]) disagrees with expected result")

    # Check with default_params
    conv = galsim.Convolve([psf, pixel], gsparams=default_params)
    conv.draw(myImg,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        myImg.array,
        savedImg.array,
        5,
        err_msg=
        "Using GSObject Convolve([psf,pixel]) with default_params disagrees with "
        "expected result")
    conv = galsim.Convolve([psf, pixel], gsparams=galsim.GSParams())
    conv.draw(myImg,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        myImg.array,
        savedImg.array,
        5,
        err_msg=
        "Using GSObject Convolve([psf,pixel]) with GSParams() disagrees with "
        "expected result")

    # Other ways to do the convolution:
    conv = galsim.Convolve(psf, pixel)
    conv.draw(myImg,
              scale=dx,
              normalization="surface brightness",
              use_true_center=False)
    np.testing.assert_array_almost_equal(
        myImg.array,
        savedImg.array,
        5,
        err_msg=
        "Using GSObject Convolve(psf,pixel) disagrees with expected result")

    # Test photon shooting.
    do_shoot(conv, myImg, "sheared Gaussian * Pixel")

    t2 = time.time()
    print 'time for %s = %.2f' % (funcname(), t2 - t1)
Example #11
0
#From Chihway's config file
photon=0
Pixelsize=0.2
full_image = galsim.ImageF(128, 128)
full_image.setCenter(2657,3044)
full_image.setScale(0.2)
im_center = full_image.bounds.center()
im_center = galsim.PositionD(im_center.x, im_center.y)
Atmseeing = 0.6
Airmass = 1.0
atm_psf = galsim.Kolmogorov(fwhm = Atmseeing*Airmass**0.6)
Optpsfbeta = 3
Optpsfsize = 0.35
Optpsftrunc = 3.*Optpsfsize
opt_psf=galsim.Moffat(beta=Optpsfbeta, fwhm=Optpsfsize, trunc=Optpsftrunc)
pix = galsim.Pixel(0.2)
#decide if using photon shooting or not
psf=galsim.Convolve([atm_psf, opt_psf, pix])    


if (photon == 0):
    psf=galsim.Convolve([atm_psf, opt_psf, pix])
if (photon == 1):
    psf=galsim.Convolve([atm_psf, opt_psf])

#Bright galaxy
#corresponds to line 24645 in storedproc.dat
x=512.84819306
y=652.163783834
z=0.215078294
galFlux=int(19861.5428849*25)
Example #12
0
#Define wavelengths, ellipticities, and magnitudes
new_params = galsim.hsm.HSMParams(max_amoment=6.0e7, max_mom2_iter=10000000)
big_fft_params = galsim.GSParams(maximum_fft_size=4096)
mag_gal_vec = [18, 19, 20, 21, 22, 23, 24]

e1_vec, e2_vec, r_measured_vec = [], [], []

print "mag_vec, ratio_vec", mag_vec, ratio_vec

for mag in mag_gal_vec:
    gal_flux = 6e4 * 2.521**(m_zero - mag)
    gal = galsim.Convolve(galsim.Gaussian(flux=gal_flux,
                                          sigma=gal_sigma).shear(
                                              galsim.Shear(e1=0.0, e2=0.0)),
                          galsim.Pixel(pixel_scale),
                          gsparams=big_fft_params)
    measurement_function(gal,
                         e1_inter_vec=e1_vec,
                         e2_inter_vec=e2_vec,
                         size_inter_vec=r_measured_vec,
                         noise=None,
                         string='Gausian, no noise',
                         type=type)

prop = fm.FontProperties(size=7)
alpha = 0.6
fig = plt.figure()
ax = fig.add_subplot(111)
ax.errorbar(mag_vec,
            ratio_vec,
Example #13
0
def test_interleaveImages():
    # 1a) With galsim Gaussian
    g = galsim.Gaussian(sigma=3.7,flux=1000.)
    gal = galsim.Convolve([g,galsim.Pixel(1.0)])
    im_list = []
    offset_list = []
    n = 2
    for j in range(n):
        for i in range(n):
            im = galsim.Image(16*n,16*n)
            offset = galsim.PositionD(-(i+0.5)/n+0.5,-(j+0.5)/n+0.5)
            offset_list.append(offset)
            gal.drawImage(image=im,method='no_pixel',offset=offset,scale=0.5)
            im_list.append(im)

    scale = im.scale

    # Input to N as an int
    img = galsim.utilities.interleaveImages(im_list,n,offsets=offset_list)
    im = galsim.Image(16*n*n,16*n*n)
    g = galsim.Gaussian(sigma=3.7,flux=1000.*n*n)
    gal = galsim.Convolve([g,galsim.Pixel(1.0)])
    gal.drawImage(image=im,method='no_pixel',offset=galsim.PositionD(0.0,0.0),scale=1.*scale/n)
    np.testing.assert_array_equal(img.array,im.array,\
        err_msg="Interleaved Gaussian images do not match")

    assert im.wcs == img.wcs

    # 1b) With im_list and offsets permuted
    offset_list = []
    # An elegant way of generating the default offsets
    DX = np.arange(0.0,-1.0,-1.0/n)
    DX -= DX.mean()
    DY = DX
    for dy in DY:
        for dx in DX:
            offset = galsim.PositionD(dx,dy)
            offset_list.append(offset)

    np.random.seed(42) # for generating the same random permutation everytime
    rand_idx = np.random.permutation(len(offset_list))
    im_list_randperm = [im_list[idx] for idx in rand_idx]
    offset_list_randperm = [offset_list[idx] for idx in rand_idx]
    # Input to N as a tuple
    img_randperm = galsim.utilities.interleaveImages(im_list_randperm,(n,n),offsets=offset_list_randperm)

    np.testing.assert_array_equal(img_randperm.array,img.array,\
        err_msg="Interleaved images do not match when 'offsets' is supplied")
    assert img_randperm.scale == img.scale

    # 1c) Catching errors in offsets
    offset_list = []
    im_list = []
    n = 5
    # Generate approximate offsets
    DX = np.array([-0.67,-0.33,0.,0.33,0.67])
    DY = DX
    for dy in DY:
        for dx in DX:
           offset = galsim.PositionD(dx,dy)
           offset_list.append(offset)
           im = galsim.Image(16,16)
           gal.drawImage(image=im,offset=offset,method='no_pixel')
           im_list.append(im)

    try:
        N = (n,n)
        np.testing.assert_raises(ValueError,galsim.utilities.interleaveImages,im_list,N,offset_list)
    except ImportError:
        print("The assert_raises tests require nose")

    offset_list = []
    im_list = []
    n = 5
    DX = np.arange(0.,1.,1./n)
    DY = DX
    for dy in DY:
        for dx in DX:
            offset = galsim.PositionD(dx,dy)
            offset_list.append(offset)
            im = galsim.Image(16,16)
            gal.drawImage(image=im,offset=offset,method='no_pixel')
            im_list.append(im)

    try:
        N = (n,n)
        np.testing.assert_raises(ValueError, galsim.utilities.interleaveImages,
                                 im_list, N, offset_list)
    except ImportError:
        print("The assert_raises tests require nose")

    # 2a) Increase resolution along one direction - square to rectangular images
    n = 2
    g = galsim.Gaussian(sigma=3.7,flux=100.)
    gal1 = g.shear(g=1.*(n**2-1)/(n**2+1),beta=0.0*galsim.radians)
    im_list = []
    offset_list = []

    # Generating offsets in a natural way
    DY = np.arange(0.0,1.0,1.0/(n*n))
    DY -= DY.mean()
    for dy in DY:
        im = galsim.Image(16,16)
        offset = galsim.PositionD(0.0,dy)
        offset_list.append(offset)
        gal1.drawImage(im,offset=offset,method='no_pixel',scale=2.0)
        im_list.append(im)

    img = galsim.utilities.interleaveImages(im_list, N=[1,n**2], offsets=offset_list,
                                            add_flux=False, suppress_warnings=True)
    im = galsim.Image(16,16*n*n)
    # The interleaved image has the total flux averaged out since `add_flux = False'
    gal = galsim.Gaussian(sigma=3.7*n,flux=100.)
    gal.drawImage(image=im,method='no_pixel',scale=2.0)

    np.testing.assert_array_equal(im.array, img.array,
                                  err_msg="Sheared gaussian not interleaved correctly")
    assert img.wcs == galsim.JacobianWCS(2.0,0.0,0.0,2./(n**2))

    # 2b) Increase resolution along one direction - rectangular to square images
    n = 2
    g = galsim.Gaussian(sigma=3.7,flux=100.)
    gal2 = g.shear(g=1.*(n**2-1)/(n**2+1),beta=90.*galsim.degrees)
    im_list = []
    offset_list = []

    # Generating offsets in a natural way
    DX = np.arange(0.0,1.0,1.0/n**2)
    DX -= DX.mean()
    for dx in DX:
         offset = galsim.PositionD(dx,0.0)
         offset_list.append(offset)
         im = galsim.Image(16,16*n*n)
         gal2.drawImage(im,offset=offset,method='no_pixel',scale=3.0)
         im_list.append(im)

    img = galsim.utilities.interleaveImages(im_list, N=np.array([n**2,1]), offsets=offset_list,
                                            suppress_warnings=True)
    im = galsim.Image(16*n*n,16*n*n)
    gal = galsim.Gaussian(sigma=3.7,flux=100.*n*n)
    scale = im_list[0].scale
    gal.drawImage(image=im,scale=1.*scale/n,method='no_pixel')

    np.testing.assert_array_equal(im.array, img.array,
                                  err_msg="Sheared gaussian not interleaved correctly")
    assert img.wcs == galsim.JacobianWCS(1.*scale/n**2,0.0,0.0,scale)

    # 3) Check compatability with deInterleaveImage
    n = 3
    g = galsim.Gaussian(sigma=3.7,flux=100.)
    # break symmetry to detect possible bugs in deInterleaveImage
    gal = g.shear(g=0.2,beta=0.*galsim.degrees)
    im_list = []
    offset_list = []

    # Generating offsets in the order they would be returned by deInterleaveImage, for convenience
    for i in range(n):
        for j in range(n):
            im = galsim.Image(16*n,16*n)
            offset = galsim.PositionD(-(i+0.5)/n+0.5,-(j+0.5)/n+0.5)
            offset_list.append(offset)
            gal.drawImage(image=im,method='no_pixel',offset=offset,scale=0.5)
            im.setOrigin(3,3) # for non-trivial bounds
            im_list.append(im)

    img = galsim.utilities.interleaveImages(im_list,N=n,offsets=offset_list)
    im_list_1, offset_list_1 = galsim.utilities.deInterleaveImage(img, N=n)

    for k in range(n**2):
        assert offset_list_1[k] == offset_list[k]
        np.testing.assert_array_equal(im_list_1[k].array, im_list[k].array)
        assert im_list_1[k].wcs == im_list[k].wcs

        assert im_list[k].origin() == img.origin()
        assert im_list[k].bounds == im_list_1[k].bounds

    # Checking for non-default flux option
    img = galsim.utilities.interleaveImages(im_list,N=n,offsets=offset_list,add_flux=False)
    im_list_2, offset_list_2 = galsim.utilities.deInterleaveImage(img,N=n,conserve_flux=True)

    for k in range(n**2):
        assert offset_list_2[k] == offset_list[k]
        np.testing.assert_array_equal(im_list_2[k].array, im_list[k].array)
        assert im_list_2[k].wcs == im_list[k].wcs