Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion galsim/interpolatedimage.py
Original file line number Diff line number Diff line change
Expand Up @@ -723,7 +723,6 @@ def _kValue(self, kpos):
def _shoot(self, photons, rng):
with convert_cpp_errors():
self._sbp.shoot(photons._pa, rng._rng)
photons.flux *= self._flux_per_photon

def _drawReal(self, image, jac=None, offset=(0.,0.), flux_scaling=1.):
dx,dy = offset
Expand Down
4 changes: 3 additions & 1 deletion galsim/sum.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,9 @@ def _shoot(self, photons, rng):
temp = PhotonArray(this_n)
temp._copyFrom(photons, slice(None), use, do_xy=False, do_flux=False)
obj._shoot(temp, rng)
temp.flux = fluxPerPhoton
# Normalize to the sum's photon weight, but keep the sign for profiles that
# include negative flux photons.
temp.flux = np.copysign(fluxPerPhoton, temp.flux)
photons._copyFrom(temp, use, slice(None))

def _drawKImage(self, image, jac=None):
Expand Down
3 changes: 3 additions & 0 deletions include/galsim/ProbabilityTree.h
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ namespace galsim {
/// @brief Destructor - kill the `Element`s that have been stored away
~ProbabilityTree() { if (_root) delete _root; }

/// @brief Total absolute flux retained by the tree. Valid after buildTree().
double getTotalAbsFlux() const { return _totalAbsFlux; }

/**
* @brief Choose a member of the tree based on a uniform deviate
*
Expand Down
2 changes: 1 addition & 1 deletion src/SBInterpolatedImage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1294,7 +1294,7 @@ namespace galsim {
assert(N>=0);

if (N<=0 || _pt.empty()) return;
double totalAbsFlux = _positiveFlux + _negativeFlux;
double totalAbsFlux = _pt.getTotalAbsFlux();
double fluxPerPhoton = totalAbsFlux / N;
dbg<<"posFlux = "<<_positiveFlux<<", negFlux = "<<_negativeFlux<<std::endl;
dbg<<"totFlux = "<<_positiveFlux-_negativeFlux<<", totAbsFlux = "<<totalAbsFlux<<std::endl;
Expand Down
26 changes: 22 additions & 4 deletions tests/test_interpolatedimage.py
Original file line number Diff line number Diff line change
Expand Up @@ -1585,11 +1585,13 @@ def test_ii_shoot(run_slow):
"""Test InterpolatedImage with photon shooting. Particularly the flux of the final image.
"""
rng = galsim.BaseDeviate(1234)
# Include a couple negative pixels to check the handling of positive and negative pixels
# in the shoot function.
ref_array = np.array([
[0.01, 0.08, 0.07, 0.02],
[0.13, 0.38, 0.52, 0.06],
[0.09, 0.41, 0.44, 0.09],
[0.04, 0.11, 0.10, 0.01] ])
[-0.01, 0.08, 0.07, -0.02],
[ 0.13, 0.38, 0.52, 0.06],
[ 0.09, 0.41, 0.44, 0.09],
[ 0.04, 0.11, 0.10, 0.01] ])
image_in = galsim.Image(ref_array)
interp_list = ['nearest', 'delta', 'linear', 'cubic', 'quintic',
'lanczos3', 'lanczos5', 'lanczos7']
Expand Down Expand Up @@ -1619,6 +1621,22 @@ def test_ii_shoot(run_slow):
rtol = 1.e-7
assert np.isclose(added_flux, obj.flux, rtol=rtol)
assert np.isclose(im.array.sum(), obj.flux, rtol=rtol)

# Because there are negative pixels, even when the interpolant is all positive, we
# always get some negative-flux photons here.
assert np.any(photons.flux < 0)

# The photon fluxes are not just +-1. The sum needs to be flux, but we also need the
# shot noise variance to be flux for Poisson statistics. The upshot is that with the
# negative flux photons, you need more than flux of them and their individual abs
# fluxes will be less than 1. Significantly so for the highly oscillatory interp
# kernels such as quintic and lanczos.
assert len(photons) > flux
expected_weight = (obj.positive_flux + obj.negative_flux) / len(photons)
assert expected_weight < 1.
np.testing.assert_allclose(np.abs(photons.flux), expected_weight)

# Drawing into an image and returning the photons directly must use the same weights.
photons2 = obj.makePhot(poisson_flux=False, rng=rng.duplicate())
assert photons2 == photons, "InterpolatedImage makePhot not equivalent to drawPhot"

Expand Down
50 changes: 50 additions & 0 deletions tests/test_sum.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,13 @@ def test_add():
myImg.array, savedImg.array, 5,
err_msg="Using GSObject sum += 0.25 * gauss2 disagrees with expected result")

# An interesting limit is the case of shooting a single photon. Then the photon can only
# be assigned to one component or the other (with the appropriate probability). It needs
# to end up with the full flux of the object, not a fraction of the flux.
for seed in range(1, 11):
photons = sum_gauss.shoot(1, galsim.BaseDeviate(seed))
np.testing.assert_allclose(photons.flux, sum_gauss.flux)

check_basic(sum_gauss, "sum of 2 Gaussians")

# Test photon shooting.
Expand Down Expand Up @@ -137,6 +144,49 @@ def test_add():
assert_raises(TypeError, galsim.Sum, [gauss1, gauss1], real_space=False)


@timer
def test_shoot_signed_flux():
"""Test photon shooting a Sum when some components include negative flux photons."""
# This test is in response to Issue #1352, reported by Axel Guinot.
# There had been an error that the flux normalization in Sum was setting every photon
# in a component to the fluxPerPhoton value. This was correct for most profiles, but not
# when a component shoots photons with negative flux. Primarily, this is anything with an
# InterpolatedImage (including the OpticalPSF that Axel was using).
# This is a simplified version of the script Axel posted in that issue.

# Make a Sum of the same profile twice, and then divide by 2. It should be equivalent
# to the component profile. Specifically, the expected total flux is 1.0. (Not exactly,
# because of the varying signs.)
rng = galsim.BaseDeviate(1234)
psf = galsim.OpticalPSF(lam_over_diam=0.1)
summed_psf = (psf + psf) / 2
n_photons = 100000
photons = summed_psf.shoot(n_photons, rng)
absolute_flux = summed_psf.positive_flux + summed_psf.negative_flux
assert np.any(photons.flux < 0)
np.testing.assert_allclose(np.abs(photons.flux), absolute_flux / n_photons)
np.testing.assert_allclose(photons.getTotalFlux(), 1., atol=0.02)

# Also check this using a photon operator.
star = galsim.DeltaFunction(flux=1000.)
photons = star.makePhot(n_photons=n_photons, poisson_flux=False,
photon_ops=[summed_psf], rng=rng)
assert np.any(photons.flux < 0)
np.testing.assert_allclose(photons.getTotalFlux(), star.flux, rtol=0.02)

# A similar idea exposed a different bug in InterpolatedImage. Here we make two profiles,
# one with all the pixels multiplied by 2, and another with them multiplied by -1.
# The Sum of these should be equivalent to a profile that does neither.
# There was a bug in the InterpolatedImage code that handled this incorrectly.
image = psf.drawImage(nx=33, ny=33, scale=0.05, dtype=float)
compensated_psf = galsim.InterpolatedImage(image * 2) + galsim.InterpolatedImage(image * -1)
expected_flux = image.array.sum()
np.testing.assert_allclose(compensated_psf.flux, expected_flux)
photons = compensated_psf.shoot(n_photons, rng)
assert np.any(photons.flux < 0)
np.testing.assert_allclose(photons.getTotalFlux(), expected_flux, rtol=0.02)


@timer
def test_sub_neg():
"""Test that a - b is the same as a + (-b)."""
Expand Down