Example #1
0
def test_ne():
    """ Check that inequality works as expected."""
    gsp = galsim.GSParams(maxk_threshold=1.1e-3, folding_threshold=5.1e-3)
    gal1 = galsim.Gaussian(fwhm=1)
    gal2 = galsim.Gaussian(fwhm=2)

    # Sum.  Params are objs to add and potentially gsparams.
    gals = [
        galsim.Sum(gal1),
        galsim.Sum(gal1, gal2),
        galsim.Sum(gal2, gal1),  # Not! commutative.
        galsim.Sum(galsim.Sum(gal1, gal2), gal2),
        galsim.Sum(gal1, galsim.Sum(gal2, gal2)),  # Not! associative.
        galsim.Sum(gal1, gsparams=gsp)
    ]
    all_obj_diff(gals)

    # Convolution.  Params are objs to convolve and potentially gsparams.
    # The following should test unequal
    gals = [
        galsim.Convolution(gal1),
        galsim.Convolution(gal1, gal2),
        galsim.Convolution(gal2, gal1),  # Not! commutative.
        galsim.Convolution(gal1, gal2, real_space=True),
        galsim.Convolution(galsim.Convolution(gal1, gal2), gal2),
        galsim.Convolution(gal1,
                           galsim.Convolution(gal2,
                                              gal2)),  # Not! associative.
        galsim.Convolution(gal1, gsparams=gsp)
    ]
    all_obj_diff(gals)

    # Deconvolution.  Only params here are obj to deconvolve and gsparams.
    gals = [
        galsim.Deconvolution(gal1),
        galsim.Deconvolution(gal2),
        galsim.Deconvolution(gal1, gsparams=gsp)
    ]
    all_obj_diff(gals)

    # AutoConvolution.  Only params here are obj to deconvolve and gsparams.
    gals = [
        galsim.AutoConvolution(gal1),
        galsim.AutoConvolution(gal2),
        galsim.AutoConvolution(gal1, gsparams=gsp)
    ]
    all_obj_diff(gals)

    # AutoCorrelation.  Only params here are obj to deconvolve and gsparams.
    gals = [
        galsim.AutoCorrelation(gal1),
        galsim.AutoCorrelation(gal2),
        galsim.AutoCorrelation(gal1, gsparams=gsp)
    ]
    all_obj_diff(gals)
Example #2
0
    def __getitem__(self, idx):
        flux_avg = self._uniform(self.min_flux, self.max_flux)
        hlr = self._uniform(self.min_hlr, self.max_hlr)  # arcseconds
        flux = (hlr / self.pixel_scale) ** 2 * np.pi * flux_avg  # approx

        # sample ellipticity
        ell = self._uniform(0, self.max_e)
        theta = self._uniform(0, 2 * np.pi)
        g1 = ell * np.cos(theta)
        g2 = ell * np.sin(theta)

        # pylint: disable=no-value-for-parameter
        galaxy = galsim.Gaussian(half_light_radius=hlr).shear(g1=g1, g2=g2).withFlux(flux)
        gal_conv = galsim.Convolution(galaxy, self.psf)
        image = gal_conv.drawImage(
            nx=self.slen, ny=self.slen, method="auto", scale=self.pixel_scale
        )

        # convert image to pytorch and reshape
        image = torch.from_numpy(image.array).reshape(1, self.slen, self.slen)

        # add noise and background.
        image += self.background
        noise = torch.sqrt(image) * torch.randn(*image.shape)
        image += noise

        return {"images": image, "background": self.background}
Example #3
0
def dilatePSF(epsf_profile, shear):
    """
    Separate epsf and pixel response, dilate by 1+2g, reconvolve by pixel response
    epsf_profile must be a Convolution object, not interpolated_image
    """
    obj_list = epsf_profile.obj_list
    non_pixel = [obj for obj in obj_list if not isinstance(obj, galsim.Pixel)]
    pixel = [obj for obj in obj_list if isinstance(obj, galsim.Pixel)][0]  # assume one pixel object
    if len(non_pixel) > 1:
        non_pixel = galsim.Convolution(non_pixel)
    else:
        non_pixel = non_pixel[0]
    dilation = 1.0 + 2.0 * shear.g
    dil_psf = non_pixel.dilate(dilation)
    reconv_psf = galsim.Convolution(dil_psf, pixel)
    return reconv_psf
Example #4
0
    def make_fft_psf(self, psf, logger):
        """Swap out any PhaseScreenPSF component with a roughly equivalent analytic approximation.
        """
        if isinstance(psf, galsim.Transformation):
            return galsim.Transformation(self.make_fft_psf(psf.original, logger),
                                         psf.jac, psf.offset, psf.flux_ratio, psf.gsparams)
        elif isinstance(psf, galsim.Convolution):
            obj_list = [self.make_fft_psf(p, logger) for p in psf.obj_list]
            return galsim.Convolution(obj_list, gsparams=psf.gsparams)
        elif isinstance(psf, galsim.PhaseScreenPSF):
            # If psf is a PhaseScreenPSF, then make a simpler one the just convolves
            # a Kolmogorov profile with an OpticalPSF.
            r0_500 = psf.screen_list.r0_500_effective
            atm_psf = galsim.Kolmogorov(lam=psf.lam, r0_500=r0_500,
                                        gsparams=psf.gsparams)

            opt_screens = [s for s in psf.screen_list if isinstance(s, galsim.OpticalScreen)]
            logger.info('opt_screens = %r',opt_screens)
            if len(opt_screens) >= 1:
                # Should never be more than 1, but if there weirdly is, just use the first.
                opt_screen = opt_screens[0]
                optical_psf = galsim.OpticalPSF(
                        lam=psf.lam,
                        diam=opt_screen.diam,
                        aberrations=opt_screen.aberrations,
                        annular_zernike=opt_screen.annular_zernike,
                        obscuration=opt_screen.obscuration,
                        gsparams=psf.gsparams)
                return galsim.Convolve([atm_psf, optical_psf], gsparams=psf.gsparams)
            else:
                return atm_psf
        else:
            return psf
Example #5
0
def test_measurements():
    slen = 40
    pixel_scale = 0.2
    psf = galsim.Gaussian(sigma=0.2)
    gal = galsim.Gaussian(sigma=1.0)
    gal_conv = galsim.Convolution(gal, psf)
    psf_image = psf.drawImage(nx=slen, ny=slen, scale=pixel_scale).array.reshape(1, slen, slen)
    image = gal_conv.drawImage(nx=slen, ny=slen, scale=pixel_scale).array.reshape(1, 1, slen, slen)
    image, psf_image = torch.from_numpy(image), torch.from_numpy(psf_image)
    reporting.get_single_galaxy_measurements(image, psf_image, pixel_scale)
Example #6
0
def test_ne():
    import time
    t1 = time.time()

    gsp = galsim.GSParams(maxk_threshold=1.1e-3, folding_threshold=5.1e-3)
    gal1 = galsim.Gaussian(fwhm=1)
    gal2 = galsim.Gaussian(fwhm=2)

    # Sum.  Params are objs to add and potentially gsparams.
    gals = [galsim.Sum(gal1),
            galsim.Sum(gal1, gal2),
            galsim.Sum(gal2, gal1),  # Not! commutative.
            galsim.Sum(galsim.Sum(gal1, gal2), gal2),
            galsim.Sum(gal1, galsim.Sum(gal2, gal2)),  # Not! associative.
            galsim.Sum(gal1, gsparams=gsp)]
    all_obj_diff(gals)

    # Convolution.  Params are objs to convolve and potentially gsparams.
    # The following should test unequal
    gals = [galsim.Convolution(gal1),
            galsim.Convolution(gal1, gal2),
            galsim.Convolution(gal2, gal1),  # Not! commutative.
            galsim.Convolution(gal1, gal2, real_space=True),
            galsim.Convolution(galsim.Convolution(gal1, gal2), gal2),
            galsim.Convolution(gal1, galsim.Convolution(gal2, gal2)),  # Not! associative.
            galsim.Convolution(gal1, gsparams=gsp)]
    all_obj_diff(gals)

    # Deconvolution.  Only params here are obj to deconvolve and gsparams.
    gals = [galsim.Deconvolution(gal1),
            galsim.Deconvolution(gal2),
            galsim.Deconvolution(gal1, gsparams=gsp)]
    all_obj_diff(gals)

    # AutoConvolution.  Only params here are obj to deconvolve and gsparams.
    gals = [galsim.AutoConvolution(gal1),
            galsim.AutoConvolution(gal2),
            galsim.AutoConvolution(gal1, gsparams=gsp)]
    all_obj_diff(gals)

    # AutoCorrelation.  Only params here are obj to deconvolve and gsparams.
    gals = [galsim.AutoCorrelation(gal1),
            galsim.AutoCorrelation(gal2),
            galsim.AutoCorrelation(gal1, gsparams=gsp)]
    all_obj_diff(gals)

    t2 = time.time()
    print 'time for %s = %.2f'%(funcname(),t2-t1)
Example #7
0
 def simple_model(self, e, half_light_radius, theta_int, flux, g1=0., g2=0.):
     '''Simple image model, only involves key parameters to describe an image
         This function is used to find the major axis direction of image only data 
     '''
     disk = galsim.Sersic(n=1, half_light_radius=half_light_radius, flux=flux, trunc=4*half_light_radius)
     disk = disk.shear(g1=e/2., g2=0.0)
     disk = disk.rotate(theta_int*galsim.radians)
     disk = disk.shear(g1=g1, g2=g2)
     galObj = galsim.Convolution([disk, self.psf])
     _image = galsim.Image(self.image.ngrid, self.image.ngrid, scale=self.image.pixScale)
     newImage = galObj.drawImage(image=_image)
     return newImage.array
Example #8
0
    def forward_model(self, pars):

        disk = galsim.Sersic(n=1, half_light_radius=pars['r_hl_image'], flux=pars['flux'], trunc=4*pars['r_hl_image'])

        e = cal_e_int(sini=pars['sini'], q_z=pars['aspect'])
        g1_int = e/2.
        disk = disk.shear(g1=g1_int, g2=0.0)
        disk = disk.rotate(pars['theta_int']*galsim.radians)
        disk = disk.shear(g1=pars['g1'], g2=pars['g2'])

        galObj = galsim.Convolution([disk, self.psf])

        image0 = galsim.Image(pars['ngrid'], pars['ngrid'], scale=pars['subGridPixScale'])
        image = galObj.drawImage(image=image0)

        return image.array
Example #9
0
    def render_galaxy(
        self,
        galaxy_params: Tensor,
        psf: galsim.GSObject,
        slen: int,
        offset: Optional[Tensor] = None,
    ) -> Tensor:
        assert offset is None or offset.shape == (2, )
        if isinstance(galaxy_params, Tensor):
            galaxy_params = galaxy_params.cpu().detach()
        total_flux, disk_frac, beta_radians, disk_q, a_d, bulge_q, a_b = galaxy_params
        bulge_frac = 1 - disk_frac

        disk_flux = total_flux * disk_frac
        bulge_flux = total_flux * bulge_frac

        components = []
        if disk_flux > 0:
            b_d = a_d * disk_q
            disk_hlr_arcsecs = np.sqrt(a_d * b_d)
            disk = galsim.Exponential(
                flux=disk_flux, half_light_radius=disk_hlr_arcsecs).shear(
                    q=disk_q,
                    beta=beta_radians * galsim.radians,
                )
            components.append(disk)
        if bulge_flux > 0:
            b_b = bulge_q * a_b
            bulge_hlr_arcsecs = np.sqrt(a_b * b_b)
            bulge = galsim.DeVaucouleurs(
                flux=bulge_flux, half_light_radius=bulge_hlr_arcsecs).shear(
                    q=bulge_q, beta=beta_radians * galsim.radians)
            components.append(bulge)
        galaxy = galsim.Add(components)
        gal_conv = galsim.Convolution(galaxy, psf)
        offset = offset if offset is None else offset.numpy()
        image = gal_conv.drawImage(nx=slen,
                                   ny=slen,
                                   method="auto",
                                   scale=self.pixel_scale,
                                   offset=offset)
        return torch.from_numpy(image.array).reshape(1, slen, slen)
Example #10
0
    def applyPSF(self, xPupil=None, yPupil=None, obj=None, **kwargs):
        """
        Apply the PSF to a GalSim GSObject

        This method accepts the x and y pupil coordinates in arc seconds as well
        as a GalSim GSObject.  The method calculates the PSF parameters based on xPupil
        and yPupil, constructs a Galsim GSObject corresponding to the PSF function, and convolves
        the PSF with the GSObject, returning the result of the convolution.

        In the case of point sources, this object returns the raw PSF, rather than attempting
        a convolution (since there is nothing to convolve with).

        @param [in] xPupil the x pupil coordinate in arc seconds

        @param [in] yPupil the y pupil coordinate in arc seconds

        @param [in] obj is a GalSim GSObject (an astronomical object) with which
        to convolve the PSF (optional)
        """

        #use the user-defined _getPSF method to calculate the PSF at these specific
        #coordinates and (optionally) wavelength
        psf = self._getPSF(xPupil=xPupil, yPupil=yPupil, **kwargs)

        if obj is None:
            #if there is no object, use a DeltaFunction as a point source
            obj = galsim.DeltaFunction()

        #convolve obj with the psf
        if isinstance(psf, galsim.Convolution):
            # If the psf is itself a Convolution object, convolve obj
            # with the individual components to ensure that the
            # obj_list of the returned obj lists those components
            # separately.
            return galsim.Convolution([obj] + psf.obj_list)
        else:
            return galsim.Convolve(obj, psf)
Example #11
0
def test_convolve_noise():
    """Test that noise propagation works properly for compount objects.
    """
    obj1 = galsim.Gaussian(sigma=1.7)
    obj2 = galsim.Gaussian(sigma=2.3)
    obj1.noise = galsim.UncorrelatedNoise(variance=0.3, scale=0.2)
    obj2.noise = galsim.UncorrelatedNoise(variance=0.5, scale=0.2)
    obj3 = galsim.Gaussian(sigma=2.9)

    # Convolve convolves the noise from a single component
    conv2 = galsim.Convolution([obj1, obj3])
    noise = galsim.Convolve([obj1.noise._profile, obj3, obj3])
    # xValue is too slow here.  Use drawImage to get variance.  (Just as CorrelatedNoise does.)
    variance = noise.drawImage(nx=1, ny=1, scale=1., method='sb')(1, 1)
    np.testing.assert_almost_equal(
        conv2.noise.getVariance(),
        variance,
        err_msg=
        "Convolution of two objects did not correctly propagate noise varinace"
    )
    conv2 = galsim.Convolution([obj2, obj3])
    noise = galsim.Convolve([obj2.noise._profile, obj3, obj3])
    variance = noise.drawImage(nx=1, ny=1, scale=1., method='sb')(1, 1)
    np.testing.assert_almost_equal(
        conv2.noise.getVariance(),
        variance,
        err_msg=
        "Convolution of two objects did not correctly propagate noise varinace"
    )

    # Convolution of multiple objects with noise attributes raises a warning and fails
    # to propagate noise properly.  (It takes the input noise from the first one.)
    conv2 = galsim.Convolution(obj1, obj2)
    conv3 = galsim.Convolution(obj1, obj2, obj3)
    with assert_warns(galsim.GalSimWarning):
        assert conv2.noise == obj1.noise.convolvedWith(obj2)
    with assert_warns(galsim.GalSimWarning):
        assert conv3.noise == obj1.noise.convolvedWith(
            galsim.Convolve(obj2, obj3))

    # Convolution with only one object uses that object's noise
    conv1 = galsim.Convolution(obj1)
    assert conv1.noise == obj1.noise

    # Other types don't propagate noise and give a warning about it.
    deconv = galsim.Deconvolution(obj2)
    autoconv = galsim.AutoConvolution(obj2)
    autocorr = galsim.AutoCorrelation(obj2)
    four = galsim.FourierSqrt(obj2)
    with assert_warns(galsim.GalSimWarning):
        assert deconv.noise is None
    with assert_warns(galsim.GalSimWarning):
        assert autoconv.noise is None
    with assert_warns(galsim.GalSimWarning):
        assert autocorr.noise is None
    with assert_warns(galsim.GalSimWarning):
        assert four.noise is None

    obj2.noise = None  # Remove obj2 noise for the rest.
    conv2 = galsim.Convolution(obj1, obj2)
    noise = galsim.Convolve([obj1.noise._profile, obj2, obj2])
    variance = noise.drawImage(nx=1, ny=1, scale=1., method='sb')(1, 1)
    np.testing.assert_almost_equal(
        conv2.noise.getVariance(),
        variance,
        err_msg=
        "Convolution of two objects did not correctly propagate noise varinace"
    )

    conv3 = galsim.Convolution(obj1, obj2, obj3)
    noise = galsim.Convolve([obj1.noise._profile, obj2, obj2, obj3, obj3])
    variance = noise.drawImage(nx=1, ny=1, scale=1., method='sb')(1, 1)
    np.testing.assert_almost_equal(
        conv3.noise.getVariance(),
        variance,
        err_msg=
        "Convolution of three objects did not correctly propagate noise varinace"
    )

    deconv = galsim.Deconvolution(obj2)
    autoconv = galsim.AutoConvolution(obj2)
    autocorr = galsim.AutoCorrelation(obj2)
    four = galsim.FourierSqrt(obj2)
    assert deconv.noise is None
    assert autoconv.noise is None
    assert autocorr.noise is None
    assert four.noise is None
Example #12
0
def test_convolve():
    """Test the convolution of a Moffat and a Box profile against a known result.
    """
    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.
    with assert_warns(galsim.GalSimWarning):
        # We'll do the real space convolution below
        conv = galsim.Convolve([psf, pixel], real_space=False)
        conv.drawImage(myImg, scale=dx, method="sb", 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"
        )
        assert psf.gsparams is galsim.GSParams.default
        assert pixel.gsparams is galsim.GSParams.default
        assert conv.gsparams is galsim.GSParams.default

        # Other ways to do the convolution:
        conv = galsim.Convolve(psf, pixel, real_space=False)
        conv.drawImage(myImg, scale=dx, method="sb", 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"
        )
        assert conv.gsparams is galsim.GSParams.default

        # Check with default_params
        conv = galsim.Convolve([psf, pixel],
                               real_space=False,
                               gsparams=default_params)
        conv.drawImage(myImg, scale=dx, method="sb", 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")
        # In this case, it's not the same object, but it should be ==
        assert conv.gsparams is not galsim.GSParams.default
        assert conv.gsparams == galsim.GSParams.default
        assert conv.gsparams is default_params
        # Also the components shouldn't have changed.
        assert conv.obj_list[0] is psf
        assert conv.obj_list[1] is pixel

        conv = galsim.Convolve([psf, pixel],
                               real_space=False,
                               gsparams=galsim.GSParams())
        conv.drawImage(myImg, scale=dx, method="sb", 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")
        assert conv.gsparams is not galsim.GSParams.default
        assert conv.gsparams == galsim.GSParams.default

    cen = galsim.PositionD(0, 0)
    np.testing.assert_equal(conv.centroid, cen)
    np.testing.assert_almost_equal(conv.flux, psf.flux * pixel.flux)
    # Not almost_equal.  Convolutions don't give a very good estimate.
    # They are almost always too high, which is actually ok for how we use max_sb for phot shooting.
    np.testing.assert_array_less(conv.xValue(cen), conv.max_sb)

    check_basic(conv, "Moffat * Pixel")

    # Test photon shooting.
    with assert_warns(galsim.GalSimWarning):
        do_shoot(conv, myImg, "Moffat * Pixel")

    # Convolution of just one argument should be equivalent to that argument.
    single = galsim.Convolve(psf)
    gsobject_compare(single, psf)
    check_basic(single, "`convolution' of single Moffat")
    do_pickle(single)
    do_shoot(single, myImg, "single Convolution")

    single = galsim.Convolve([psf])
    gsobject_compare(single, psf)
    check_basic(single, "`convolution' of single Moffat")
    do_pickle(single)

    single = galsim.Convolution(psf)
    gsobject_compare(single, psf)
    check_basic(single, "`convolution' of single Moffat")
    do_pickle(single)

    single = galsim.Convolution([psf])
    gsobject_compare(single, psf)
    check_basic(single, "`convolution' of single Moffat")
    do_pickle(single)

    # Should raise an exception for invalid arguments
    assert_raises(TypeError, galsim.Convolve)
    assert_raises(TypeError, galsim.Convolve, myImg)
    assert_raises(TypeError, galsim.Convolve, [myImg])
    assert_raises(TypeError, galsim.Convolve, [psf, myImg])
    assert_raises(TypeError, galsim.Convolve, [psf, psf, myImg])
    assert_raises(TypeError, galsim.Convolve, [psf, psf], realspace=False)
    assert_raises(TypeError, galsim.Convolution)
    assert_raises(TypeError, galsim.Convolution, myImg)
    assert_raises(TypeError, galsim.Convolution, [myImg])
    assert_raises(TypeError, galsim.Convolution, [psf, myImg])
    assert_raises(TypeError, galsim.Convolution, [psf, psf, myImg])
    assert_raises(TypeError, galsim.Convolution, [psf, psf], realspace=False)

    with assert_warns(galsim.GalSimWarning):
        triple = galsim.Convolve(psf, psf, pixel)
    assert_raises(galsim.GalSimError, triple.xValue, galsim.PositionD(0, 0))
    assert_raises(galsim.GalSimError, triple.drawReal, myImg)

    deconv = galsim.Convolve(psf, galsim.Deconvolve(pixel))
    assert_raises(galsim.GalSimError, deconv.xValue, galsim.PositionD(0, 0))
    assert_raises(galsim.GalSimError, deconv.drawReal, myImg)
    assert_raises(galsim.GalSimError, deconv.drawPhot, myImg, n_photons=10)
    assert_raises(galsim.GalSimError, deconv.makePhot, n_photons=10)