Surface Brightness Profiles

Base class

class jax_galsim.GSObject(*, gsparams=None, **params)[source]

Bases: object

Base class for all GalSim classes that represent some kind of surface brightness profile.

LAX-backend implementation of galsim.gsobject.GSObject().

Original GalSim Documentation

A GSObject is not intended to be constructed directly. Normally, you would use whatever derived class is appropriate for the surface brightness profile you want:

>>> gal = galsim.Sersic(n=4, half_light_radius=4.3)
>>> psf = galsim.Moffat(beta=3, fwhm=2.85)
>>> conv = galsim.Convolve([gal,psf])

All of these classes are subclasses of GSObject, so you should see those docstrings for more details about how to construct the various profiles. Here we discuss attributes and methods that are common to all GSObjects.

GSObjects are always defined in sky coordinates. So all sizes and other linear dimensions should be in terms of some kind of units on the sky, arcsec for instance. Only later (when they are drawn) is the connection to pixel coordinates established via a pixel scale or WCS. (See the documentation for galsim.BaseWCS for more details about how to specify various kinds of world coordinate systems more complicated than a simple pixel scale.)

For instance, if you eventually draw onto an image that has a pixel scale of 0.2 arcsec/pixel, then the normal thing to do would be to define your surface brightness profiles in terms of arcsec and then draw with pixel_scale=0.2. However, while arcsec are the usual choice of units for the sky coordinates, if you wanted, you could instead define the sizes of all your galaxies and PSFs in terms of radians and then use pixel_scale=0.2/206265 when you draw them.

Transforming methods:

The GSObject class uses an “immutable” design[1], so all methods that would potentially modify the object actually return a new object instead. This uses pointers and such behind the scenes, so it all happens efficiently, but it makes using the objects a bit simpler, since you don’t need to worry about some function changing your object behind your back.

In all cases below, we just give an example usage. See the docstrings for the methods for more details about how to use them.:

>>> obj = obj.shear(shear)      # Apply a shear to the object.
>>> obj = obj.dilate(scale)     # Apply a flux-preserving dilation.
>>> obj = obj.magnify(mu)       # Apply a surface-brightness-preserving magnification.
>>> obj = obj.rotate(theta)     # Apply a rotation.
>>> obj = obj.shift(dx,dy)      # Shft the object in real space.
>>> obj = obj.transform(dudx,dudy,dvdx,dvdy)    # Apply a general jacobian transformation.
>>> obj = obj.lens(g1,g2,mu)    # Apply both a lensing shear and magnification.
>>> obj = obj.withFlux(flux)    # Set a new flux value.
>>> obj = obj * ratio           # Scale the surface brightness profile by some factor.

Access Methods:

There are some access methods and properties that are available for all GSObjects. Again, see the docstrings for each method for more details.:

>>> obj.flux
>>> obj.centroid
>>> obj.nyquist_scale
>>> obj.stepk
>>> obj.maxk
>>> obj.has_hard_edges
>>> obj.is_axisymmetric
>>> obj.is_analytic_x
>>> obj.is_analytic_k
>>> obj.xValue(x,y) or obj.xValue(pos)
>>> obj.kValue(kx,ky) os obj.kValue(kpos)

Most subclasses have additional methods that are available for values that are particular to that specific surface brightness profile. e.g. sigma = gauss.sigma. However, note that class-specific methods are not available after performing one of the above transforming operations.:

>>> gal = galsim.Gaussian(sigma=5)
>>> gal = gal.shear(g1=0.2, g2=0.05)
>>> sigma = gal.sigma               # This will raise an exception.

It is however possible to access the original object that was transformed via the original attribute.:

>>> sigma = gal.original.sigma      # This works.

No matter how many transformations are performed, the original attribute will contain the _original_ object (not necessarily the most recent ancestor).

Drawing Methods:

The main thing to do with a GSObject once you have built it is to draw it onto an image. There are two methods that do this. In both cases, there are lots of optional parameters. See the docstrings for these methods for more details.:

>>> image = obj.drawImage(...)
>>> kimage = obj.drawKImage(...)

There two attributes that may be available for a GSObject.

Attributes:
original: This was mentioned above as a way to access the original object that has

been transformed by one of the transforming methods.

noise: Some types, like RealGalaxy, set this attribute to be the intrinsic noise that

is already inherent in the profile and will thus be present when you draw the object. The noise is propagated correctly through the various transforming methods, as well as convolutions and flux rescalings. Note that the noise attribute can be set directly by users even for GSObjects that do not naturally have one. The typical use for this attribute is to use it to whiten the noise in the image after drawing. See BaseCorrelatedNoise for more details.

GSParams:

All GSObject classes take an optional gsparams argument, so we document that feature here. For all documentation about the specific derived classes, please see the docstring for each one individually.

The gsparams argument can be used to specify various numbers that govern the tradeoff between accuracy and speed for the calculations made in drawing a GSObject. The numbers are encapsulated in a class called GSParams, and the user should make careful choices whenever they opt to deviate from the defaults. For more details about the parameters and their default values, please see the docstring of the GSParams class.

For example, let’s say you want to do something that requires an FFT larger than 4096 x 4096 (and you have enough memory to handle it!). Then you can create a new GSParams object with a larger maximum_fft_size and pass that to your GSObject on construction:

>>> gal = galsim.Sersic(n=4, half_light_radius=4.3)
>>> psf = galsim.Moffat(beta=3, fwhm=2.85)
>>> conv = galsim.Convolve([gal,psf])
>>> im = galsim.Image(1000,1000, scale=0.02)        # Note the very small pixel scale!
>>> im = conv.drawImage(image=im)                   # This uses the default GSParams.
galsim/errors.py:437: GalSimFFTSizeWarning: drawFFT requires a very large FFT.
The required FFT size would be 12288 x 12288, which requires 3.38 GB of memory.
If you can handle the large FFT and want to suppress this warning,
you may update gsparams.maximum_fft_size.
  warnings.warn(GalSimFFTSizeWarning(message, size))
>>> big_fft_params = galsim.GSParams(maximum_fft_size=12300)
>>> conv = galsim.Convolve([gal,psf],gsparams=big_fft_params)
>>> im = conv.drawImage(image=im)                   # Now it works (but is slow!)
>>> im.write('high_res_sersic.fits')

Note that for compound objects such as Convolution or Sum, not all GSParams can be changed when the compound object is created. In the example given here, it is possible to change parameters related to the drawing, but not the Fourier space parameters for the components that go into the Convolution. To get better sampling in Fourier space, for example, the gal and/or psf should be created with gsparams that have a non-default value of folding_threshold. This statement applies to the threshold and accuracy parameters.

property flux

The flux of the profile.

LAX-backend implementation of flux().

property gsparams

A GSParams object that sets various parameters relevant for speed/accuracy trade-offs.

LAX-backend implementation of gsparams().

property params

A Dictionary object containing all parameters of the internal represention of this object.

property maxk

The value of k beyond which aliasing can be neglected.

LAX-backend implementation of maxk().

property stepk

The sampling in k space necessary to avoid folding of image in x space.

LAX-backend implementation of stepk().

property nyquist_scale

The pixel spacing that does not alias maxk.

LAX-backend implementation of nyquist_scale().

property has_hard_edges

Whether there are any hard edges in the profile, which would require very small k spacing when working in the Fourier domain.

LAX-backend implementation of has_hard_edges().

property is_axisymmetric

Whether the profile is axially symmetric; affects efficiency of evaluation.

LAX-backend implementation of is_axisymmetric().

property is_analytic_x

Whether the real-space values can be determined immediately at any position without requiring a Discrete Fourier Transform.

LAX-backend implementation of is_analytic_x().

property is_analytic_k

Whether the k-space values can be determined immediately at any position without requiring a Discrete Fourier Transform.

LAX-backend implementation of is_analytic_k().

property centroid

The (x, y) centroid of an object as a PositionD.

LAX-backend implementation of centroid().

property positive_flux

The expectation value of flux in positive photons.

LAX-backend implementation of positive_flux().

Original GalSim Documentation

Some profiles, when rendered with photon shooting, need to shoot both positive- and negative-flux photons. For such profiles, this method returns the total flux of the positive-valued photons.

For profiles that don’t have this complication, this is equivalent to getFlux().

It should be generally true that obj.positive_flux - obj.negative_flux returns the same thing as obj.flux. Small difference may accrue from finite numerical accuracy in cases involving lookup tables, etc.

property negative_flux

Returns the expectation value of flux in negative photons.

LAX-backend implementation of negative_flux().

Original GalSim Documentation

Some profiles, when rendered with photon shooting, need to shoot both positive- and negative-flux photons. For such profiles, this method returns the total absolute flux of the negative-valued photons (i.e. as a positive value).

For profiles that don’t have this complication, this returns 0.

It should be generally true that obj.positive_flux - obj.negative_flux returns the same thing as obj.flux. Small difference may accrue from finite numerical accuracy in cases involving lookup tables, etc.

property max_sb

An estimate of the maximum surface brightness of the object.

LAX-backend implementation of max_sb().

Original GalSim Documentation

Some profiles will return the exact peak SB, typically equal to the value of obj.xValue(obj.centroid). However, not all profiles (e.g. Convolution) know how to calculate this value without just drawing the image and checking what the maximum value is. Clearly, this would be inefficient, so in these cases, some kind of estimate is returned, which will generally be conservative on the high side.

This routine is mainly used by the photon shooting process, where an overestimate of the maximum surface brightness is acceptable.

Note, for negative-flux profiles, this will return the absolute value of the most negative surface brightness. Technically, it is an estimate of the maximum deviation from zero, rather than the maximum value. For most profiles, these are the same thing.

xValue(*args, **kwargs)[source]

Returns the value of the object at a chosen 2D position in real space.

LAX-backend implementation of galsim.gsobject.xValue().

Parameters:

position – The position at which you want the surface brightness of the object.

Original GalSim Documentation

This function returns the surface brightness of the object at a particular position in real space. The position argument may be provided as a PositionD or PositionI argument, or it may be given as x,y (either as a tuple or as two arguments).

The object surface brightness profiles are typically defined in world coordinates, so the position here should be in world coordinates as well.

Not all GSObject classes can use this method. Classes like Convolution that require a Discrete Fourier Transform to determine the real space values will not do so for a single position. Instead a GalSimError will be raised. The xValue() method is available if and only if obj.is_analytic_x == True.

Users who wish to use the xValue() method for an object that is the convolution of other profiles can do so by drawing the convolved profile into an image, using the image to initialize a new InterpolatedImage, and then using the xValue() method for that new object.

Returns:

the surface brightness at that position.

kValue(*args, **kwargs)[source]

Returns the value of the object at a chosen 2D position in k space.

LAX-backend implementation of galsim.gsobject.kValue().

Parameters:

position – The position in k space at which you want the fourier amplitude.

Original GalSim Documentation

This function returns the amplitude of the fourier transform of the surface brightness profile at a given position in k space. The position argument may be provided as a Position argument, or it may be given as kx,ky (either as a tuple or as two arguments).

Technically, kValue() is available if and only if the given obj has obj.is_analytic_k == True, but this is the case for all GSObject classes currently, so that should never be an issue (unlike for xValue).

Returns:

the amplitude of the fourier transform at that position.

withGSParams(gsparams=None, **kwargs)[source]

Create a version of the current object with the given GSParams.

LAX-backend implementation of galsim.gsobject.withGSParams().

Original GalSim Documentation

You may either provide a GSParams instance:

>>> gsparams = galsim.GSParams(folding_threshold=1.e-4, maxk_threshold=1.e-4)
>>> obj = obj.withGSParams(gsparams)

or one or more named parameters as keyword arguments:

>>> obj = obj.withGSParams(folding_threshold=1.e-4, maxk_threshold=1.e-4)

Note

The latter style will leave all non-named parameters at their current values. It only updates the named parameters to the given values.

withFlux(flux)[source]

Create a version of the current object with a different flux.

LAX-backend implementation of galsim.gsobject.withFlux().

Parameters:

flux – The new flux for the object.

Original GalSim Documentation

This function is equivalent to obj.withScaledFlux(flux / obj.flux).

It creates a new object that has the same profile as the original, but with the surface brightness at every location rescaled such that the total flux will be the given value. Note that if flux is an SED, the return value will be a ChromaticObject with specified SED.

Returns:

the object with the new flux

withScaledFlux(flux_ratio)[source]

Create a version of the current object with the flux scaled by the given flux_ratio.

LAX-backend implementation of galsim.gsobject.withScaledFlux().

Parameters:

flux_ratio – The ratio by which to rescale the flux of the object when creating a new one.

Original GalSim Documentation

This function is equivalent to obj.withFlux(flux_ratio * obj.flux). Indeed, withFlux() is implemented in terms of this one.

It creates a new object that has the same profile as the original, but with the surface brightness at every location scaled by the given amount. If flux_ratio is an SED, then the returned object is a ChromaticObject with the SED multiplied by its current flux.

Note that in this case the flux attribute of the GSObject being scaled gets interpreted as being dimensionless, instead of having its normal units of [photons/s/cm^2]. The photons/s/cm^2 units are (optionally) carried by the SED instead, or even left out entirely if the SED is dimensionless itself (see discussion in the ChromaticObject docstring). The GSObject flux attribute does still contribute to the ChromaticObject normalization, though. For example, the following are equivalent:

>>> chrom_obj = gsobj.withScaledFlux(sed * 3.0)
>>> chrom_obj2 = (gsobj * 3.0).withScaledFlux(sed)

An equivalent, and usually simpler, way to effect this scaling is:

>>> obj = obj * flux_ratio
Returns:

the object with the new flux.

expand(scale)[source]

Expand the linear size of the profile by the given scale factor, while preserving surface brightness.

LAX-backend implementation of galsim.gsobject.expand().

Parameters:

scale – The factor by which to scale the linear dimension of the object.

Original GalSim Documentation

e.g. half_light_radius <– half_light_radius * scale

This doesn’t correspond to either of the normal operations one would typically want to do to a galaxy. The functions dilate() and magnify() are the more typical usage. But this function is conceptually simple. It rescales the linear dimension of the profile, while preserving surface brightness. As a result, the flux will necessarily change as well.

See dilate() for a version that applies a linear scale factor while preserving flux.

See magnify() for a version that applies a scale factor to the area while preserving surface brightness.

Returns:

the expanded object.

dilate(scale)[source]

Dilate the linear size of the profile by the given scale factor, while preserving flux.

LAX-backend implementation of galsim.gsobject.dilate().

Parameters:

scale – The linear rescaling factor to apply.

Original GalSim Documentation

e.g. half_light_radius <– half_light_radius * scale

See expand() and magnify() for versions that preserve surface brightness, and thus changes the flux.

Returns:

the dilated object.

magnify(mu)[source]

Create a version of the current object with a lensing magnification applied to it, scaling the area and flux by mu at fixed surface brightness.

LAX-backend implementation of galsim.gsobject.magnify().

Parameters:

mu – The lensing magnification to apply.

Original GalSim Documentation

This process applies a lensing magnification mu, which scales the linear dimensions of the image by the factor sqrt(mu), i.e., half_light_radius <– half_light_radius * sqrt(mu) while increasing the flux by a factor of mu. Thus, magnify() preserves surface brightness.

See dilate() for a version that applies a linear scale factor while preserving flux.

See expand() for a version that applies a linear scale factor while preserving surface brightness.

Returns:

the magnified object.

shear(*args, **kwargs)[source]

Create a version of the current object with an area-preserving shear applied to it.

LAX-backend implementation of galsim.gsobject.shear().

Parameters:

shear – The Shear to be applied. Or, as described above, you may instead supply parameters do construct a shear directly. eg. obj.shear(g1=g1,g2=g2).

Original GalSim Documentation

The arguments may be either a Shear instance or arguments to be used to initialize one.

For more details about the allowed keyword arguments, see the Shear docstring.

The shear() method precisely preserves the area. To include a lensing distortion with the appropriate change in area, either use shear() with magnify(), or use lens(), which combines both operations.

Returns:

the sheared object.

lens(g1, g2, mu)[source]

Create a version of the current object with both a lensing shear and magnification applied to it.

LAX-backend implementation of galsim.gsobject.lens().

Parameters:
  • g1 – First component of lensing (reduced) shear to apply to the object.

  • g2 – Second component of lensing (reduced) shear to apply to the object.

  • mu – Lensing magnification to apply to the object. This is the factor by which the solid angle subtended by the object is magnified, preserving surface brightness.

Original GalSim Documentation

This GSObject method applies a lensing (reduced) shear and magnification. The shear must be specified using the g1, g2 definition of shear (see Shear for more details). This is the same definition as the outputs of the PowerSpectrum and NFWHalo classes, which compute shears according to some lensing power spectrum or lensing by an NFW dark matter halo. The magnification determines the rescaling factor for the object area and flux, preserving surface brightness.

Returns:

the lensed object.

rotate(theta)[source]

Rotate this object by an Angle theta.

LAX-backend implementation of galsim.gsobject.rotate().

Parameters:

theta – Rotation angle (Angle object, positive means anticlockwise).

Original GalSim Documentation
Returns:

the rotated object.

transform(dudx, dudy, dvdx, dvdy)[source]

Create a version of the current object with an arbitrary Jacobian matrix transformation applied to it.

LAX-backend implementation of galsim.gsobject.transform().

Parameters:
  • dudx – du/dx, where (x,y) are the current coords, and (u,v) are the new coords.

  • dudy – du/dy, where (x,y) are the current coords, and (u,v) are the new coords.

  • dvdx – dv/dx, where (x,y) are the current coords, and (u,v) are the new coords.

  • dvdy – dv/dy, where (x,y) are the current coords, and (u,v) are the new coords.

Original GalSim Documentation

This applies a Jacobian matrix to the coordinate system in which this object is defined. It changes a profile defined in terms of (x,y) to one defined in terms of (u,v) where:

u = dudx x + dudy y v = dvdx x + dvdy y

That is, an arbitrary affine transform, but without the translation (which is easily effected via the shift method).

Note that this function is similar to expand in that it preserves surface brightness, not flux. If you want to preserve flux, you should also do:

>>> prof *= 1./abs(dudx*dvdy - dudy*dvdx)
Returns:

the transformed object

shift(*args, **kwargs)[source]

Create a version of the current object shifted by some amount in real space.

LAX-backend implementation of galsim.gsobject.shift().

Parameters:
  • dx – Horizontal shift to apply.

  • dy – Vertical shift to apply.

Original GalSim Documentation

After this call, the caller’s type will be a GSObject. This means that if the caller was a derived type that had extra methods or properties beyond those defined in GSObject (e.g. Gaussian.sigma), then these methods are no longer available.

Note: in addition to the dx,dy parameter names, you may also supply dx,dy as a tuple, or as a Position object.

The shift coordinates here are sky coordinates. GSObject profiles are always defined in sky coordinates and only later (when they are drawn) is the connection to pixel coordinates established (via a pixel_scale or WCS). So a shift of dx moves the object horizontally in the sky (e.g. west in the local tangent plane of the observation), and dy moves the object vertically (north in the local tangent plane).

The units are typically arcsec, but we don’t enforce that anywhere. The units here just need to be consistent with the units used for any size values used by the GSObject. The connection of these units to the eventual image pixels is defined by either the pixel_scale or the wcs parameter of GSObject.drawImage.

Note: if you want to shift the object by a set number (or fraction) of pixels in the drawn image, you probably want to use the offset parameter of GSObject.drawImage rather than this method.

Alternatively, you may supply a single parameter as a Position instance, rather than the two components separately if that is more convenient.

Parameter:

offset: The shift to apply, given as PositionD(dx,dy) or PositionI(dx,dy)

Returns:

the shifted object.

drawImage(image=None, nx=None, ny=None, bounds=None, scale=None, wcs=None, dtype=None, method='auto', area=1.0, exptime=1.0, gain=1.0, add_to_image=False, center=None, use_true_center=True, offset=None, n_photons=None, rng=None, max_extra_noise=0.0, poisson_flux=None, sensor=None, photon_ops=(), n_subsample=3, maxN=None, save_photons=False, bandpass=None, setup_only=False, surface_ops=None)[source]

Draws an Image of the object.

LAX-backend implementation of galsim.gsobject.drawImage().

🔪 JAX-GalSim - The Sharp Bits 🔪

The JAX-GalSim version of drawImage

  • does not do extensive (any?) checking of the input settings.

  • uses a default of n_photons=None instead of n_photons=0 to indicate that the number of photons should be determined from the flux and gain

  • requires that the maxN option be a constant since PhotonArrays are allocated with maxN photons when this option is used and arrays in JAX must have static sizes.

Parameters:
  • image – If provided, this will be the image on which to draw the profile. If image is None, then an automatically-sized Image will be created. If image is given, but its bounds are undefined (e.g. if it was constructed with image = galsim.Image()), then it will be resized appropriately based on the profile’s size [default: None].

  • nx – If provided and image is None, use to set the x-direction size of the image. Must be accompanied by ny.

  • ny – If provided and image is None, use to set the y-direction size of the image. Must be accompanied by nx.

  • bounds – If provided and image is None, use to set the bounds of the image.

  • scale – If provided, use this as the pixel scale for the image. If scale is None and image is given, then take the provided image’s pixel scale. If scale is None and image is None, then use the Nyquist scale. If scale <= 0 (regardless of image), then use the Nyquist scale. If scale > 0 and image is given, then override image.scale with the value given as a keyword. [default: None]

  • wcs – If provided, use this as the wcs for the image (possibly overriding any existing image.wcs). At most one of scale or wcs may be provided. [default: None]

  • dtype – The data type to use for an automatically constructed image. Only valid if image is None. [default: None, which means to use numpy.float32]

  • method – Which method to use for rendering the image. See discussion above for the various options and what they do. [default: ‘auto’]

  • area – Collecting area of telescope in cm^2. [default: 1.]

  • exptime – Exposure time in s. [default: 1.]

  • gain – The number of photons per ADU (“analog to digital units”, the units of the numbers output from a CCD). [default: 1]

  • add_to_image – Whether to add flux to the existing image rather than clear out anything in the image before drawing. Note: This requires that image be provided and that it have defined bounds. [default: False]

  • center – The position on the image at which to place the nominal center of the object (usually the centroid, but not necessarily). [default: None]

  • use_true_center – If center is None, then the object is normally centered at the true center of the image (using the property image.true_center). If you would rather use the integer center (given by image.center), set this to False. [default: True]

  • offset – The offset in pixel coordinates at which to center the profile being drawn relative to either center (if given) or the center of the image (either the true center or integer center according to the use_true_center parameter). [default: None]

  • n_photons – If provided, the number of photons to use for photon shooting. If not provided (i.e. n_photons = 0), use as many photons as necessary to result in an image with the correct Poisson shot noise for the object’s flux. For positive definite profiles, this is equivalent to n_photons = flux. However, some profiles need more than this because some of the shot photons are negative (usually due to interpolants). [default: 0]

  • rng – If provided, a random number generator to use for photon shooting, which may be any kind of BaseDeviate object. If rng is None, one will be automatically created. [default: None]

  • max_extra_noise – If provided, the allowed extra noise in each pixel when photon shooting. This is only relevant if n_photons=0, so the number of photons is being automatically calculated. In that case, if the image noise is dominated by the sky background, then you can get away with using fewer shot photons than the full n_photons = flux. Essentially each shot photon can have a flux > 1, which increases the noise in each pixel. The max_extra_noise parameter specifies how much extra noise per pixel is allowed because of this approximation. A typical value for this might be max_extra_noise = sky_level / 100 where sky_level is the flux per pixel due to the sky. Note that this uses a “variance” definition of noise, not a “sigma” definition. [default: 0.]

  • poisson_flux – Whether to allow total object flux scaling to vary according to Poisson statistics for n_photons samples when photon shooting. [default: True, unless n_photons is given, in which case the default is False]

  • sensor – An optional Sensor instance, which will be used to accumulate the photons onto the image. [default: None]

  • photon_ops – A list of operators that can modify the photon array that will be applied in order before accumulating the photons on the sensor. [default: None]

  • n_subsample – The number of sub-pixels per final pixel to use for fft drawing when using a sensor. The sensor step needs to know the sub-pixel positions of the photons, which is lost in the fft method. So using smaller pixels for the fft step keeps some of that information, making the assumption of uniform flux per pixel less bad of an approximation. [default: 3]

  • maxN – Sets the maximum number of photons that will be added to the image at a time. (Memory requirements are proportional to this number.) .. note:: Using this parameter will not necessarily produce identical results as when not using it due to potentially different order of various random number generations in either the photon_ops, or the sensor, or (for method=’fft’) the conversion of the FFT image to photons. [default: None, which means no limit]

  • save_photons – If True, save the PhotonArray as image.photons. Only valid if method is ‘phot’ or sensor is not None. [default: False]

  • bandpass – This parameter is ignored, but is allowed to enable duck typing eqivalence between this method and the ChromaticObject.drawImage method. [default: None]

  • setup_only – Don’t actually draw anything on the image. Just make sure the image is set up correctly. This is used internally by GalSim, but there may be cases where the user will want the same functionality. [default: False]

Original GalSim Documentation

The drawImage() method is used to draw an Image of the current object using one of several possible rendering methods (see below). It can create a new Image or can draw onto an existing one if provided by the image parameter. If the image is given, you can also optionally add to the given Image if add_to_image = True, but the default is to replace the current contents with new values.

Providing an input image:

Note that if you provide an image parameter, it is the image onto which the profile will be drawn. The provided image will be modified. A reference to the same image is also returned to provide a parallel return behavior to when image is None (described above).

This option is useful in practice because you may want to construct the image first and then draw onto it, perhaps multiple times. For example, you might be drawing onto a subimage of a larger image. Or you may want to draw different components of a complex profile separately. In this case, the returned value is typically ignored. For example:

>>> im1 = bulge.drawImage()
>>> im2 = disk.drawImage(image=im1, add_to_image=True)
>>> assert im1 is im2

>>> full_image = galsim.Image(2048, 2048, scale=pixel_scale)
>>> b = galsim.BoundsI(x-32, x+32, y-32, y+32)
>>> stamp = obj.drawImage(image = full_image[b])
>>> assert (stamp.array == full_image[b].array).all()

Letting drawImage create the image for you:

If drawImage() will be creating the image from scratch for you, then there are several ways to control the size of the new image. If the nx and ny keywords are present, then an image with these numbers of pixels on a side will be created. Similarly, if the bounds keyword is present, then an image with the specified bounds will be created. Note that it is an error to provide an existing Image when also specifying nx, ny, or bounds. In the absence of nx, ny, and bounds, drawImage will decide a good size to use based on the size of the object being drawn. Basically, it will try to use an area large enough to include at least 99.5% of the flux.

Note

This value 0.995 is really 1 - folding_threshold. You can change the value of folding_threshold for any object via GSParams.

You can set the pixel scale of the constructed image with the scale parameter, or set a WCS function with wcs. If you do not provide either scale or wcs, then drawImage() will default to using the Nyquist scale for the current object.

You can also set the data type used in the new Image with the dtype parameter that has the same options as for the Image constructor.

The drawing “method”:

There are several different possible methods drawImage() can use for rendering the image. This is set by the method parameter. The options are:

auto

This is the default, which will normally be equivalent to ‘fft’. However, if the object being rendered is simple (no convolution) and has hard edges (e.g. a Box or a truncated Moffat or Sersic), then it will switch to ‘real_space’, since that is often both faster and more accurate in these cases (due to ringing in Fourier space).

fft

The integration of the light within each pixel is mathematically equivalent to convolving by the pixel profile (a Pixel object) and sampling the result at the centers of the pixels. This method will do that convolution using a discrete Fourier transform. Furthermore, if the object (or any component of it) has been transformed via shear(), dilate(), etc., then these transformations are done in Fourier space as well.

real_space

This uses direct integrals (using the Gauss-Kronrod-Patterson algorithm) in real space for the integration over the pixel response. It is usually slower than the ‘fft’ method, but if the profile has hard edges that cause ringing in Fourier space, it can be faster and/or more accurate. If you use ‘real_space’ with something that is already a Convolution, then this will revert to ‘fft’, since the double convolution that is required to also handle the pixel response is far too slow to be practical using real-space integrals.

phot

This uses a technique called photon shooting to render the image. Essentially, the object profile is taken as a probability distribution from which a finite number of photons are “shot” onto the image. Each photon’s flux gets added to whichever pixel the photon hits. This process automatically accounts for the integration of the light over the pixel area, since all photons that hit any part of the pixel are counted. Convolutions and transformations are simple geometric processes in this framework. However, there are two caveats with this method: (1) the resulting image will have Poisson noise from the finite number of photons, and (2) it is not available for all object types (notably anything that includes a Deconvolution).

no_pixel

Instead of integrating over the pixels, this method will sample the profile at the centers of the pixels and multiply by the pixel area. If there is a convolution involved, the choice of whether this will use an FFT or real-space calculation is governed by the real_space parameter of the Convolution class. This method is the appropriate choice if you are using a PSF that already includes a convolution by the pixel response. For example, if you are using a PSF from an observed image of a star, then it has already been convolved by the pixel, so you would not want to do so again. Note: The multiplication by the pixel area gets the flux normalization right for the above use case. cf. method = 'sb'.

sb

This is a lot like ‘no_pixel’, except that the image values will simply be the sampled object profile’s surface brightness, not multiplied by the pixel area. This does not correspond to any real observing scenario, but it could be useful if you want to view the surface brightness profile of an object directly, without including the pixel integration.

The ‘phot’ method has a few extra parameters that adjust how it functions. The total number of photons to shoot is normally calculated from the object’s flux. This flux is taken to be given in photons/cm^2/s, so for most simple profiles, this times area * exptime will equal the number of photons shot. (See the discussion in Rowe et al, 2015, for why this might be modified for InterpolatedImage and related profiles.) However, you can manually set a different number of photons with n_photons. You can also set max_extra_noise to tell drawImage() to use fewer photons than normal (and so is faster) such that no more than that much extra noise is added to any pixel. This is particularly useful if you will be subsequently adding sky noise, and you can thus tolerate more noise than the normal number of photons would give you, since using fewer photons is of course faster. Finally, the default behavior is to have the total flux vary as a Poisson random variate, which is normally appropriate with photon shooting. But you can turn this off with poisson_flux=False. It also defaults to False if you set an explicit value for n_photons.

Given the periodicity implicit in the use of FFTs, there can occasionally be artifacts due to wrapping at the edges, particularly for objects that are quite extended (e.g., due to the nature of the radial profile). See GSParams for parameters that you can use to reduce the level of these artifacts, in particular folding_threshold may be helpful if you see such artifacts in your images.

Setting the offset:

The object will by default be drawn with its nominal center at the center location of the image. There is thus a qualitative difference in the appearance of the rendered profile when drawn on even- and odd-sized images. For a profile with a maximum at (0,0), this maximum will fall in the central pixel of an odd-sized image, but in the corner of the four central pixels of an even-sized image. There are three parameters that can affect this behavior. First, you can specify any arbitrary pixel position to center the object using the center parameter. If this is None, then it will pick one of the two potential “centers” of the image, either image.true_center or image.center. The latter is an integer position, which always corresponds to the center of some pixel, which for even sized images won’t (cannot) be the actual “true” center of the image. You can choose which of these two centers you want to use with the use_true_center parameters, which defaults to False. You can also arbitrarily offset the profile from the image center with the offset parameter to handle any aribtrary offset you want from the chosen center. (Typically, one would use only one of center or offset but it is permissible to use both.)

Setting the overall normalization:

Normally, the flux of the object should be equal to the sum of all the pixel values in the image, less some small amount of flux that may fall off the edge of the image (assuming you don’t use method='sb'). However, you may optionally set a gain value, which converts between photons and ADU (so-called analog-to-digital units), the units of the pixel values in real images. Normally, the gain of a CCD is in electrons/ADU, but in GalSim, we fold the quantum efficiency into the gain as well, so the units are photons/ADU.

Another caveat is that, technically, flux is really in units of photons/cm^2/s, not photons. So if you want, you can keep track of this properly and provide an area and exptime here. This detail is more important with chromatic objects where the SED is typically given in erg/cm^2/s/nm, so the exposure time and area are important details. With achromatic objects however, it is often more convenient to ignore these details and just consider the flux to be the total number of photons for this exposure, in which case, you would leave the area and exptime parameters at their default value of 1.

On return, the image will have an attribute added_flux, which will be set to the total flux added to the image. This may be useful as a sanity check that you have provided a large enough image to catch most of the flux. For example:

>>> obj.drawImage(image)
>>> assert image.added_flux > 0.99 * obj.flux

The appropriate threshold will depend on your particular application, including what kind of profile the object has, how big your image is relative to the size of your object, whether you are keeping poisson_flux=True, etc.

The following code snippet illustrates how gain, exptime, area, and method can all influence the relationship between the flux attribute of a GSObject and both the pixel values and .added_flux attribute of an Image drawn with drawImage():

>>> obj = galsim.Gaussian(fwhm=1)
>>> obj.flux
1.0
>>> im = obj.drawImage()
>>> im.added_flux
0.9999630988657515
>>> im.array.sum()
0.99996305
>>> im = obj.drawImage(exptime=10, area=10)
>>> im.added_flux
0.9999630988657525
>>> im.array.sum()
99.996315
>>> im = obj.drawImage(exptime=10, area=10, method='sb', scale=0.5, nx=10, ny=10)
>>> im.added_flux
0.9999973790505298
>>> im.array.sum()
399.9989
>>> im = obj.drawImage(exptime=10, area=10, gain=2)
>>> im.added_flux
0.9999630988657525
>>> im.array.sum()
49.998158

Using a non-trivial sensor:

Normally the sensor is modeled as an array of pixels where any photon that hits a given pixel is accumulated into that pixel. The final pixel value then just reflects the total number of pixels that hit each sensor. However, real sensors do not (quite) work this way.

In real CCDs, the photons travel some distance into the silicon before converting to electrons. Then the electrons diffuse laterally some amount as they are pulled by the electric field toward the substrate. Finally, previous electrons that have already been deposited will repel subsequent electrons, both slowing down their descent, leading to more diffusion, and pushing them laterally toward neighboring pixels, which is called the brighter-fatter effect.

Users interested in modeling this kind of effect can supply a sensor object to use for the accumulation step. See SiliconSensor for a class that models silicon-based CCD sensors.

Some related effects may need to be done to the photons at the surface layer before being passed into the sensor object. For instance, the photons may need to be given appropriate incidence angles according to the optics of the telescope (since this matters for where the photons are converted to electrons). You may also need to give the photons wavelengths according to the SED of the object. Such steps are specified in a photon_ops parameter, which should be a list of any such operations you wish to perform on the photon array before passing them to the sensor. See FRatioAngles and WavelengthSampler for two examples of such photon operators.

Since the sensor deals with photons, it is most natural to use this feature in conjunction with photon shooting (method='phot'). However, it is allowed with FFT methods too. But there is a caveat one should be aware of in this case. The FFT drawing is used to produce an intermediate image, which is then converted to a PhotonArray using the factory function PhotonArray.makeFromImage. This assigns photon positions randomly within each pixel where they were drawn, which isn’t always a particularly good approximation.

To improve this behavior, the intermediate image is drawn with smaller pixels than the target image, so the photons are given positions closer to their true locations. The amount of subsampling is controlled by the n_subsample parameter, which defaults to 3. Larger values will be more accurate at the expense of larger FFTs (i.e. slower and using more memory).

Returns:

the drawn Image.

drawReal(image, add_to_image=False)[source]

Draw this profile into an Image by direct evaluation at the location of each pixel.

LAX-backend implementation of galsim.gsobject.drawReal().

Parameters:
  • image – The Image onto which to place the flux. [required]

  • add_to_image – Whether to add flux to the existing image rather than clear out anything in the image before drawing. [default: False]

Original GalSim Documentation

This is usually called from the drawImage function, rather than called directly by the user. In particular, the input image must be already set up with defined bounds. The profile will be drawn centered on whatever pixel corresponds to (0,0) with the given bounds, not the image center (unlike drawImage). The image also must have a PixelScale wcs. The profile being drawn should have already been converted to image coordinates via:

>>> image_profile = original_wcs.toImage(original_profile)

Note that the image produced by drawReal represents the profile sampled at the center of each pixel and then multiplied by the pixel area. That is, the profile is NOT integrated over the area of the pixel. This is equivalent to method=’no_pixel’ in drawImage. If you want to render a profile integrated over the pixel, you can convolve with a Pixel first and draw that.

Returns:

The total flux drawn inside the image bounds.

getGoodImageSize(pixel_scale)[source]

Return a good size to use for drawing this profile.

LAX-backend implementation of galsim.gsobject.getGoodImageSize().

Parameters:

pixel_scale – The desired pixel scale of the image to be built.

Original GalSim Documentation

The size will be large enough to cover most of the flux of the object. Specifically, at least (1-gsparams.folding_threshold) (i.e. 99.5% by default) of the flux should fall in the image.

Also, the returned size is always an even number, which is usually desired in practice. Of course, if you prefer an odd-sized image, you can add 1 to the result.

Returns:

N, a good (linear) size of an image on which to draw this object.

drawFFT_makeKImage(image)[source]

This is a helper routine for drawFFT that just makes the (blank) k-space image onto which the profile will be drawn. This can be useful if you want to break up the calculation into parts for extra efficiency. E.g. save the k-space image of the PSF so drawing many models of the galaxy with the given PSF profile can avoid drawing the PSF each time.

LAX-backend implementation of galsim.gsobject.drawFFT_makeKImage().

Parameters:

image – The Image onto which to place the flux.

Original GalSim Documentation
Returns:

(kimage, wrap_size), where wrap_size is either the size of kimage or smaller if the result should be wrapped before doing the inverse fft.

drawFFT_finish(image, kimage, wrap_size, add_to_image)[source]

This is a helper routine for drawFFT that finishes the calculation, based on the drawn k-space image.

LAX-backend implementation of galsim.gsobject.drawFFT_finish().

Parameters:
  • image – The Image onto which to place the flux.

  • kimage – The k-space Image where the object was drawn.

  • wrap_size – The size of the region to wrap kimage, which must be either the same size as kimage or smaller.

  • add_to_image – Whether to add flux to the existing image rather than clear out anything in the image before drawing.

Original GalSim Documentation

It applies the Fourier transform to kimage and adds the result to image.

Returns:

The total flux drawn inside the image bounds.

drawFFT(image, add_to_image=False)[source]

Draw this profile into an Image by computing the k-space image and performing an FFT.

LAX-backend implementation of galsim.gsobject.drawFFT().

Parameters:
  • image – The Image onto which to place the flux. [required]

  • add_to_image – Whether to add flux to the existing image rather than clear out anything in the image before drawing. [default: False]

Original GalSim Documentation

This is usually called from the drawImage function, rather than called directly by the user. In particular, the input image must be already set up with defined bounds. The profile will be drawn centered on whatever pixel corresponds to (0,0) with the given bounds, not the image center (unlike drawImage). The image also must have a PixelScale wcs. The profile being drawn should have already been converted to image coordinates via:

>>> image_profile = original_wcs.toImage(original_profile)

Note that the Image produced by drawFFT represents the profile sampled at the center of each pixel and then multiplied by the pixel area. That is, the profile is NOT integrated over the area of the pixel. This is equivalent to method=’no_pixel’ in drawImage. If you want to render a profile integrated over the pixel, you can convolve with a Pixel first and draw that.

Returns:

The total flux drawn inside the image bounds.

drawKImage(image=None, nx=None, ny=None, bounds=None, scale=None, add_to_image=False, recenter=True, bandpass=None, setup_only=False)[source]

Draws the k-space (complex) Image of the object, with bounds optionally set by input Image instance.

LAX-backend implementation of galsim.gsobject.drawKImage().

Parameters:
  • image – If provided, this will be the Image onto which to draw the k-space image. If image is None, then an automatically-sized image will be created. If image is given, but its bounds are undefined, then it will be resized appropriately based on the profile’s size. [default: None]

  • nx – If provided and image is None, use to set the x-direction size of the image. Must be accompanied by ny.

  • ny – If provided and image is None, use to set the y-direction size of the image. Must be accompanied by nx.

  • bounds – If provided and image is None, use to set the bounds of the image.

  • scale – If provided, use this as the pixel scale, dk, for the images. If scale is None and image is given, then take the provided images’ pixel scale (which must be equal). If scale is None and image is None, then use the Nyquist scale. If scale <= 0 (regardless of image), then use the Nyquist scale. [default: None]

  • add_to_image – Whether to add to the existing images rather than clear out anything in the image before drawing. Note: This requires that image be provided and that it has defined bounds. [default: False]

  • recenter – Whether to recenter the image to put k = 0 at the center (True) or to trust the provided bounds (False). [default: True]

  • bandpass – This parameter is ignored, but is allowed to enable duck typing eqivalence between this method and the ChromaticObject.drawImage method. [default: None]

  • setup_only – Don’t actually draw anything on the image. Just make sure the image is set up correctly. This is used internally by GalSim, but there may be cases where the user will want the same functionality. [default: False]

Original GalSim Documentation

Normalization is always such that image(0,0) = flux. Unlike the real-space drawImage function, the (0,0) point will always be one of the actual pixel values. For even-sized images, it will be 1/2 pixel above and to the right of the true center of the image.

Another difference from drawImage is that a wcs other than a simple pixel scale is not allowed. There is no wcs parameter here, and if the images have a non-trivial wcs (and you don’t override it with the scale parameter), a TypeError will be raised.

Also, there is no convolution by a pixel. This is just a direct image of the Fourier transform of the surface brightness profile.

Returns:

an Image instance (created if necessary)

makePhot(n_photons=None, rng=None, max_extra_noise=0.0, poisson_flux=None, photon_ops=(), local_wcs=None, surface_ops=None)[source]

Make photons for a profile.

LAX-backend implementation of galsim.gsobject.makePhot().

🔪 JAX-GalSim - The Sharp Bits 🔪

The JAX-GalSim version of makePhot

  • does little to no error checking on the inputs

  • uses a default of n_photons=None instead of n_photons=0 to indicate that the number of photons should be determined from the flux and gain

Parameters:
  • n_photons – If provided, the number of photons to use for photon shooting. If not provided (i.e. n_photons = 0), use as many photons as necessary to result in an image with the correct Poisson shot noise for the object’s flux. For positive definite profiles, this is equivalent to n_photons = flux. However, some profiles need more than this because some of the shot photons are negative (usually due to interpolants). [default: 0]

  • rng – If provided, a random number generator to use for photon shooting, which may be any kind of BaseDeviate object. If rng is None, one will be automatically created, using the time as a seed. [default: None]

  • max_extra_noise – If provided, the allowed extra noise in each pixel when photon shooting. This is only relevant if n_photons=0, so the number of photons is being automatically calculated. In that case, if the image noise is dominated by the sky background, then you can get away with using fewer shot photons than the full n_photons = flux. Essentially each shot photon can have a flux > 1, which increases the noise in each pixel. The max_extra_noise parameter specifies how much extra noise per pixel is allowed because of this approximation. A typical value for this might be max_extra_noise = sky_level / 100 where sky_level is the flux per pixel due to the sky. Note that this uses a “variance” definition of noise, not a “sigma” definition. [default: 0.]

  • poisson_flux – Whether to allow total object flux scaling to vary according to Poisson statistics for n_photons samples when photon shooting. [default: True, unless n_photons is given, in which case the default is False]

  • photon_ops – A list of operators that can modify the photon array that will be applied in order before accumulating the photons on the sensor. [default: ()]

  • local_wcs – The local wcs in the original image. [default: None]

Original GalSim Documentation

This is equivalent to drawPhot, except that the photons are not placed onto an image. Instead, it just returns the PhotonArray.

Note

The (x,y) positions returned are in the same units as the distance units of the GSObject being rendered. If you want (x,y) in pixel coordinates, you should call this function for the profile in image coordinates:

>>> photons = image.wcs.toImage(obj).makePhot()

Or if you just want a simple pixel scale conversion from sky coordinates to image coordinates, you can instead do

>>> photons = obj.makePhot()
>>> photons.scaleXY(1./pixel_scale)
Returns:
  • a PhotonArray with the data about the photons.

drawPhot(image, gain=1.0, add_to_image=False, n_photons=None, rng=None, max_extra_noise=0.0, poisson_flux=None, sensor=None, photon_ops=(), maxN=None, orig_center=galsim.PositionI(x=0, y=0), local_wcs=None, surface_ops=None)[source]

Draw this profile into an Image by shooting photons.

LAX-backend implementation of galsim.gsobject.drawPhot().

🔪 JAX-GalSim - The Sharp Bits 🔪

The JAX-GalSim version of drawPhot

  • does little to no error checking on the inputs

  • uses a default of n_photons=None instead of n_photons=0 to indicate that the number of photons should be determined from the flux and gain

  • requires that the maxN option must be a constant

Parameters:
  • image – The Image onto which to place the flux. [required]

  • gain – The number of photons per ADU (“analog to digital units”, the units of the numbers output from a CCD). [default: 1.]

  • add_to_image – Whether to add to the existing images rather than clear out anything in the image before drawing. [default: False]

  • n_photons – If provided, the number of photons to use for photon shooting. If not provided (i.e. n_photons = 0), use as many photons as necessary to result in an image with the correct Poisson shot noise for the object’s flux. For positive definite profiles, this is equivalent to n_photons = flux. However, some profiles need more than this because some of the shot photons are negative (usually due to interpolants). [default: 0]

  • rng – If provided, a random number generator to use for photon shooting, which may be any kind of BaseDeviate object. If rng is None, one will be automatically created, using the time as a seed. [default: None]

  • max_extra_noise – If provided, the allowed extra noise in each pixel when photon shooting. This is only relevant if n_photons=0, so the number of photons is being automatically calculated. In that case, if the image noise is dominated by the sky background, then you can get away with using fewer shot photons than the full n_photons = flux. Essentially each shot photon can have a flux > 1, which increases the noise in each pixel. The max_extra_noise parameter specifies how much extra noise per pixel is allowed because of this approximation. A typical value for this might be max_extra_noise = sky_level / 100 where sky_level is the flux per pixel due to the sky. Note that this uses a “variance” definition of noise, not a “sigma” definition. [default: 0.]

  • poisson_flux – Whether to allow total object flux scaling to vary according to Poisson statistics for n_photons samples when photon shooting. [default: True, unless n_photons is given, in which case the default is False]

  • sensor – An optional Sensor instance, which will be used to accumulate the photons onto the image. [default: None]

  • photon_ops – A list of operators that can modify the photon array that will be applied in order before accumulating the photons on the sensor. [default: ()]

  • maxN – Sets the maximum number of photons that will be added to the image at a time. (Memory requirements are proportional to this number.) [default: None, which means no limit]

  • orig_center – The position of the image center in the original image coordinates. [default: (0,0)]

  • local_wcs – The local wcs in the original image. [default: None]

Original GalSim Documentation

This is usually called from the drawImage function, rather than called directly by the user. In particular, the input image must be already set up with defined bounds. The profile will be drawn centered on whatever pixel corresponds to (0,0) with the given bounds, not the image center (unlike drawImage). The image also must have a PixelScale wcs. The profile being drawn should have already been converted to image coordinates via:

>>> image_profile = original_wcs.toImage(original_profile)

Note that the image produced by drawPhot represents the profile integrated over the area of each pixel. This is equivalent to convolving the profile by a square Pixel profile and sampling the value at the center of each pixel, although this happens automatically by the shooting algorithm, so you do not need to manually convolve by a Pixel as you would for drawReal or drawFFT.

Returns:

(added_flux, photons) where: - added_flux is the total flux of photons that landed inside the image bounds, and - photons is the PhotonArray that was applied to the image.

shoot(n_photons, rng=None)[source]

Shoot photons into a PhotonArray.

LAX-backend implementation of galsim.gsobject.shoot().

Parameters:
  • n_photons – The number of photons to use for photon shooting.

  • rng – If provided, a random number generator to use for photon shooting, which may be any kind of BaseDeviate object. If rng is None, one will be automatically created, using the time as a seed. [default: None]

Original GalSim Documentation
Returns:

A PhotonArray.

applyTo(photon_array, local_wcs=None, rng=None)[source]

Apply this surface brightness profile as a convolution to an existing photon array.

LAX-backend implementation of galsim.gsobject.applyTo().

Parameters:
  • photon_array – A PhotonArray to apply the operator to.

  • local_wcs – A LocalWCS instance defining the local WCS for the current photon bundle in case the operator needs this information. [default: None]

  • rng – A random number generator to use to effect the convolution. [default: None]

Original GalSim Documentation

This method allows a GSObject to duck type as a PhotonOp, so one can apply a PSF in a photon_ops list.

tree_flatten()[source]

This function flattens the GSObject into a list of children nodes that will be traced by JAX and auxiliary static data.

classmethod tree_unflatten(aux_data, children)[source]

Recreates an instance of the class from flatten representation

class jax_galsim.gsparams.GSParams(minimum_fft_size=128, maximum_fft_size=8192, folding_threshold=0.005, stepk_minimum_hlr=5.0, maxk_threshold=0.001, kvalue_accuracy=1e-05, xvalue_accuracy=1e-05, table_spacing=1, realspace_relerr=0.0001, realspace_abserr=1e-06, integration_relerr=1e-06, integration_abserr=1e-08, shoot_accuracy=1e-05)[source]

Bases: object

GSParams stores a set of numbers that govern how a GSObject makes various speed/accuracy tradeoff decisions.

LAX-backend implementation of galsim.gsparams.GSParams().

Parameters:
  • minimum_fft_size (int) – The minimum size of any FFT that may need to be performed. [default: 128]

  • maximum_fft_size (int) – The maximum allowed size of an image for performing an FFT without warning. This is more about memory use than accuracy. We have this maximum value to inform a user who accidentally performs an extremely large FFT why they just crashed the program. GalSim used to raise an exception indicating that the image is too large, which is often a sign of an error in the user’s code. However, we now just emit a warning about the large FFT, so if the code crashes you have some indication of why. If you have the memory to handle it, you can raise this limit to allow the calculation to happen without seeing the warning. [default: 8192] .. note:: To revert to the old behavior of raising an exception, you may set galsim.errors.raise_fft_size_error = True.

  • folding_threshold (float) – This sets a maximum amount of real space folding that is allowed, an effect caused by the periodic nature of FFTs. FFTs implicitly use periodic boundary conditions, and a profile specified on a finite grid in Fourier space corresponds to a real space image that will have some overlap with the neighboring copies of the real space profile. As the step size in k increases, the spacing between neighboring aliases in real space decreases, increasing the amount of folded, overlapping flux. folding_threshold is used to set an appropriate step size in k to allow at most this fraction of the flux to be folded. This parameter is also relevant when you let GalSim decide how large an image to use for your object. The image is made to be large enough that at most a fraction folding_threshold of the total flux is allowed to fall off the edge of the image. [default: 5.e-3]

  • stepk_minimum_hlr (float) – In addition to the above constraint for aliasing, also set stepk such that pi/stepk is at least stepk_minimum_hlr times the profile’s half-light radius (for profiles that have a well-defined half-light radius). [default: 5]

  • maxk_threshold (float) – This sets the maximum amplitude of the high frequency modes in Fourier space that are excluded by truncating the FFT at some maximum k value. Lowering this parameter can help minimize the effect of “ringing” if you see that in your images. [default: 1.e-3]

  • kvalue_accuracy (float) – This sets the accuracy of values in Fourier space. Whenever there is some kind of approximation to be made in the calculation of a Fourier space value, the error in the approximation is constrained to be no more than this value times the total flux. [default: 1.e-5]

  • xvalue_accuracy (float) – This sets the accuracy of values in real space. Whenever there is some kind of approximation to be made in the calculation of a real space value, the error in the approximation is constrained to be no more than this value times the total flux. [default: 1.e-5]

  • table_spacing (int) – Several profiles use lookup tables for either the Hankel transform (Sersic, Moffat) or the real space radial function (Kolmogorov). We try to estimate a good spacing between values in the lookup tables based on either xvalue_accuracy or kvalue_accuracy as appropriate. However, you may change the spacing with this parameter. Using table_spacing < 1 will use a spacing value that is that much smaller than the default, which should produce more accurate interpolations. [default: 1]

  • realspace_relerr (float) – This sets the relative error tolerance for real-space integration. [default: 1.e-4]

  • realspace_abserr (float) – This sets the absolute error tolerance for real-space integration. [default: 1.e-6] The estimated integration error for the flux value in each pixel when using the real-space rendering method (either explicitly with method='real_space' or if it is triggered automatically with method='auto') is constrained to be no larger than either realspace_relerr times the pixel flux or realspace_abserr times the object’s total flux.

  • integration_relerr (float) – The relative error tolerance for integrations other than real-space rendering. [default: 1.e-6]

  • integration_abserr (float) – The absolute error tolerance for integrations other than real-space rendering. [default: 1.e-8]

  • shoot_accuracy (float) – This sets the relative accuracy on the total flux when photon shooting. The photon shooting algorithm at times needs to make approximations, such as how high in radius it needs to sample the radial profile. When such approximations need to be made, it makes sure that the resulting fractional error in the flux will be at most this much. [default: 1.e-5]

Original GalSim Documentation

All GSObject classes can take an optional parameter named gsparams, which would be an instance of this class. e.g.:

>>> gsp = galsim.GSParams(folding_threshold=1.e-3)
>>> gal = galsim.Sersic(n=3.4, half_light_radius=3.2, flux=200, gsparams=gsp)

One can also update the parameters for an existing object using the method GSObject.withGSParams. e.g.:

>>> gal = gal.withGSParams(kvalue_accuracy=1.e-8)

All parameters have reasonable default values. You only need to specify the ones you want to change.

After construction, all of the above parameters are available as read-only attributes.

minimum_fft_size: int = 128
maximum_fft_size: int = 8192
folding_threshold: float = 0.005
stepk_minimum_hlr: float = 5.0
maxk_threshold: float = 0.001
kvalue_accuracy: float = 1e-05
xvalue_accuracy: float = 1e-05
table_spacing: int = 1
realspace_relerr: float = 0.0001
realspace_abserr: float = 1e-06
integration_relerr: float = 1e-06
integration_abserr: float = 1e-08
shoot_accuracy: float = 1e-05
classmethod from_galsim(gsparams)[source]

Create a jax_galsim GSParams from a galsim.GSParams object.

to_galsim()[source]
static check(gsparams, default=None, **kwargs)[source]

Checks that gsparams is either a valid GSParams instance or None.

LAX-backend implementation of galsim.gsparams.check().

Original GalSim Documentation

In the former case, it returns gsparams, in the latter it returns default (GSParams.default if no other default specified).

withParams(**kwargs)[source]

Return a GSParams that is identical to the current one except for any keyword arguments given here, which supersede the current value.

LAX-backend implementation of galsim.gsparams.withParams().

static combine(gsp_list)[source]

Combine a list of GSParams instances using the most restrictive parameter from each.

LAX-backend implementation of galsim.gsparams.combine().

Original GalSim Documentation

Uses the minimum value for most parameters. For the following parameters, it uses the maximum numerical value: minimum_fft_size, maximum_fft_size, stepk_minimum_hlr.

default = galsim.GSParams(128,8192,0.005,5.0,0.001,1e-05,1e-05,1,0.0001,1e-06,1e-06,1e-08,1e-05)

Analytic profiles

class jax_galsim.Gaussian(half_light_radius=None, sigma=None, fwhm=None, flux=1.0, gsparams=None)[source]

Bases: GSObject

A class describing a 2D Gaussian surface brightness profile.

LAX-backend implementation of galsim.gaussian.Gaussian().

Parameters:
  • sigma – The value of sigma of the profile. Typically given in arcsec. [One of sigma, fwhm, or half_light_radius is required.]

  • fwhm – The full-width-half-max of the profile. Typically given in arcsec. [One of sigma, fwhm, or half_light_radius is required.]

  • half_light_radius – The half-light radius of the profile. Typically given in arcsec. [One of sigma, fwhm, or half_light_radius is required.]

  • flux – The flux (in photons/cm^2/s) of the profile. [default: 1]

  • gsparams – An optional GSParams argument. [default: None]

Original GalSim Documentation

The Gaussian surface brightness profile is characterized by two properties, its flux and the characteristic size sigma where the radial profile of the circular Gaussian drops off as

\[I(r) \sim e^{-\frac{r^2}{2 \sigma^2}}\]

A Gaussian can be initialized using one (and only one) of three possible size parameters: sigma, fwhm, or half_light_radius. Exactly one of these three is required.

property sigma

The sigma of this Gaussian profile

LAX-backend implementation of sigma().

property half_light_radius

The half-light radius of this Gaussian profile

LAX-backend implementation of half_light_radius().

property fwhm

The FWHM of this Gaussian profile

LAX-backend implementation of fwhm().

withFlux(flux)[source]

Create a version of the current object with a different flux.

LAX-backend implementation of galsim.gaussian.withFlux().

Parameters:

flux – The new flux for the object.

Original GalSim Documentation

This function is equivalent to obj.withScaledFlux(flux / obj.flux).

It creates a new object that has the same profile as the original, but with the surface brightness at every location rescaled such that the total flux will be the given value. Note that if flux is an SED, the return value will be a ChromaticObject with specified SED.

Returns:

the object with the new flux

class jax_galsim.Moffat(beta, scale_radius=None, half_light_radius=None, fwhm=None, trunc=0.0, flux=1.0, gsparams=None)[source]

Bases: GSObject

A class describing a Moffat surface brightness profile.

LAX-backend implementation of galsim.moffat.Moffat().

🔪 JAX-GalSim - The Sharp Bits 🔪

The JAX-GalSim version of the Moffat profile

  • does not support truncation or beta < 1.1

  • does not support gsparams.maxk_thresholds > 0.1

  • does not support autodiff with respect to the beta parameter for Fourier-space evaluations

Parameters:
  • beta – The beta parameter of the profile.

  • scale_radius – The scale radius of the profile. Typically given in arcsec. [One of scale_radius, fwhm, or half_light_radius is required.]

  • half_light_radius – The half-light radius of the profile. Typically given in arcsec. [One of scale_radius, fwhm, or half_light_radius is required.]

  • fwhm – The full-width-half-max of the profile. Typically given in arcsec. [One of scale_radius, fwhm, or half_light_radius is required.]

  • trunc – An optional truncation radius at which the profile is made to drop to zero, in the same units as the size parameter. [default: 0, indicating no truncation]

  • flux – The flux (in photons/cm^2/s) of the profile. [default: 1]

  • gsparams – An optional GSParams argument. [default: None]

Original GalSim Documentation

The Moffat surface brightness profile is

\[I(R) \sim \left(1 + (r/r_0)^2\right)^{-\beta}\]

where \(r_0\) is scale_radius.

The GalSim representation of a Moffat profile also includes an optional truncation beyond a given radius.

For more information, refer to

A Moffat can be initialized using one (and only one) of three possible size parameters: scale_radius, fwhm, or half_light_radius. Exactly one of these three is required.

property beta

The beta parameter of this Moffat profile.

LAX-backend implementation of beta().

property trunc

The truncation radius (if any) of this Moffat profile.

LAX-backend implementation of trunc().

property scale_radius

The scale radius of this Moffat profile.

LAX-backend implementation of scale_radius().

property half_light_radius

The half-light radius of this Moffat profile.

LAX-backend implementation of half_light_radius().

property fwhm

This decorator will act similarly to @property, but will be efficient for multiple access to values that require some significant calculation.

LAX-backend implementation of galsim._utilities.fwhm().

Original GalSim Documentation

It works by replacing the attribute with the computed value, so after the first access, the property (an attribute of the class) is superseded by the new attribute of the instance.

Note that is should only be used for non-mutable data, since the calculation will not be repeated if anything about the instance changes.

Usage:

@lazy_property
def slow_function_to_be_used_as_a_property(self):
    x =  ...  # Some slow calculation.
    return x

Base on an answer from http://stackoverflow.com/a/6849299

withFlux(flux)[source]

Create a version of the current object with a different flux.

LAX-backend implementation of galsim.moffat.withFlux().

Parameters:

flux – The new flux for the object.

Original GalSim Documentation

This function is equivalent to obj.withScaledFlux(flux / obj.flux).

It creates a new object that has the same profile as the original, but with the surface brightness at every location rescaled such that the total flux will be the given value. Note that if flux is an SED, the return value will be a ChromaticObject with specified SED.

Returns:

the object with the new flux

class jax_galsim.Exponential(half_light_radius=None, scale_radius=None, flux=1.0, gsparams=None)[source]

Bases: GSObject

A class describing an exponential profile.

LAX-backend implementation of galsim.exponential.Exponential().

Parameters:
  • half_light_radius – The half-light radius of the profile. Typically given in arcsec. [One of scale_radius or half_light_radius is required.]

  • scale_radius – The scale radius of the profile. Typically given in arcsec. [One of scale_radius or half_light_radius is required.]

  • flux – The flux (in photons/cm^2/s) of the profile. [default: 1]

  • gsparams – An optional GSParams argument. [default: None]

Original GalSim Documentation

Surface brightness profile with

\[I(r) \sim e^{-r/r_0}\]

where \(r_0\) is the scale_radius. This is a special case of the Sersic profile, but is given a separate class since the Fourier transform has closed form and can be generated without lookup tables.

An Exponential can be initialized using one (and only one) of two possible size parameters: scale_radius or half_light_radius. Exactly one of these two is required.

property scale_radius

The scale radius of the profile.

LAX-backend implementation of scale_radius().

property half_light_radius

The half-light radius of the profile.

LAX-backend implementation of half_light_radius().

withFlux(flux)[source]

Create a version of the current object with a different flux.

LAX-backend implementation of galsim.exponential.withFlux().

Parameters:

flux – The new flux for the object.

Original GalSim Documentation

This function is equivalent to obj.withScaledFlux(flux / obj.flux).

It creates a new object that has the same profile as the original, but with the surface brightness at every location rescaled such that the total flux will be the given value. Note that if flux is an SED, the return value will be a ChromaticObject with specified SED.

Returns:

the object with the new flux

class jax_galsim.Spergel(nu, scale_radius=None, half_light_radius=None, flux=1.0, gsparams=None)[source]

Bases: GSObject

A class describing a Spergel profile.

LAX-backend implementation of galsim.spergel.Spergel().

🔪 JAX-GalSim - The Sharp Bits 🔪

The fully normalized Spergel profile (used in both standard GalSim and JAX-GalSim) is

\[I(r) = flux \times \left(2\pi 2^\nu \Gamma(1+\nu) r_0^2\right)^{-1} \times \left(\frac{r}{r_0}\right)^\nu K_\nu\left(\frac{r}{r_0}\right)\]

with the following Fourier expression

\[\hat{I}(k) = flux / (1 + (k r_0)^2)^{1+\nu}\]

where \(r_0\) is the scale_radius, and \(\nu\) mandatory to be in [-0.85,4.0]

The JAX-GalSim implementation does not support autodiff with respect to \(\nu\) for real-space evaluations.

Parameters:
  • nu – The Spergel index, nu.

  • half_light_radius – The half-light radius of the profile. Typically given in arcsec. [One of scale_radius or half_light_radius is required.]

  • scale_radius – The scale radius of the profile. Typically given in arcsec. [One of scale_radius or half_light_radius is required.]

  • flux – The flux (in photons/cm^2/s) of the profile. [default: 1]

  • gsparams – An optional GSParams argument. [default: None]

Original GalSim Documentation

The Spergel surface brightness profile is characterized by three properties: its Spergel index nu, its flux, and either the half_light_radius or scale_radius. Given these properties, the surface brightness profile scales as

\[I(r) \sim \left(\frac{r}{r_0}\right)^\nu K_\nu\left(\frac{r}{r_0}\right)\]

where \(r_0\) is the scale_radius and \(K_\nu\) is the modified Bessel function of the second kind.

The Spergel profile is intended as a generic galaxy profile, somewhat like a Sersic profile, but with the advantage of being analytic in both real space and Fourier space. The Spergel index \(\nu\) plays a similar role to the Sersic index \(n\), in that it adjusts the relative peakiness of the profile core and the relative prominence of the profile wings. At \(\nu = 0.5\), the Spergel profile is equivalent to an Exponential profile (or alternatively an :math`n = 1` Sersic profile). At \(\nu = -0.6\) (and in the radial range near the half-light radius), the Spergel profile is similar to a DeVaucouleurs profile or \(n = 4\) Sersic profile.

Note that for \(\nu <= 0\), the Spergel profile surface brightness diverges at the origin. This may lead to rendering problems if the profile is not convolved by either a PSF or a pixel and the profile center is precisely on a pixel center.

Due to its analytic Fourier transform and depending on the indices \(n\) and \(\nu\), the Spergel profile can be considerably faster to draw than the roughly equivalent Sersic profile. For example, the \(\nu = -0.6\) Spergel profile is roughly 3x faster to draw than an \(n = 4\) Sersic profile once the Sersic profile cache has been set up. However, if not taking advantage of the cache, for example, if drawing Sersic profiles with \(n\) continuously varying near 4.0 and Spergel profiles with \(\nu\) continuously varying near -0.6, then the Spergel profiles are about 50x faster to draw. At the other end of the galaxy profile spectrum, the \(\nu = 0.5\) Spergel profile, \(n = 1\) Sersic profile, and the Exponential profile all take about the same amount of time to draw if cached, and the Spergel profile is about 2x faster than the Sersic profile if uncached.

For more information, refer to

D. N. Spergel, “ANALYTICAL GALAXY PROFILES FOR PHOTOMETRIC AND LENSING ANALYSIS,” ASTROPHYS J SUPPL S 191(1), 58-65 (2010) [doi:10.1088/0067-0049/191/1/58].

The allowed range of values for the nu parameter is -0.85 <= nu <= 4. An exception will be thrown if you provide a value outside that range. The lower limit is set above the theoretical lower limit of -1 due to numerical difficulties integrating the very peaky nu < -0.85 profiles. The upper limit is set to avoid numerical difficulties evaluating the modified Bessel function of the second kind.

A Spergel profile can be initialized using one (and only one) of two possible size parameters: scale_radius or half_light_radius. Exactly one of these two is required.

property nu

The Spergel index, nu

LAX-backend implementation of nu().

property scale_radius

The scale radius

LAX-backend implementation of scale_radius().

property half_light_radius

The half-light radius

LAX-backend implementation of half_light_radius().

calculateFluxRadius(f)[source]

Return the radius within which the total flux is f

LAX-backend implementation of galsim.spergel.calculateFluxRadius().

calculateIntegratedFlux(r)[source]

Return the integrated flux out to a given radius, r

LAX-backend implementation of galsim.spergel.calculateIntegratedFlux().

withFlux(flux)[source]

Create a version of the current object with a different flux.

LAX-backend implementation of galsim.spergel.withFlux().

Parameters:

flux – The new flux for the object.

Original GalSim Documentation

This function is equivalent to obj.withScaledFlux(flux / obj.flux).

It creates a new object that has the same profile as the original, but with the surface brightness at every location rescaled such that the total flux will be the given value. Note that if flux is an SED, the return value will be a ChromaticObject with specified SED.

Returns:

the object with the new flux

Pixel / box profiles

class jax_galsim.Box(width, height, flux=1.0, gsparams=None)[source]

Bases: GSObject

A class describing a box profile. This is just a 2D top-hat function, where the width and height are allowed to be different.

LAX-backend implementation of galsim.box.Box().

Parameters:
  • width – The width of the Box.

  • height – The height of the Box.

  • flux – The flux (in photons/cm^2/s) of the profile. [default: 1]

  • gsparams – An optional GSParams argument. [default: None]

property width

The width of the Box.

LAX-backend implementation of width().

property height

The height of the Box.

LAX-backend implementation of height().

withFlux(flux)[source]

Create a version of the current object with a different flux.

LAX-backend implementation of galsim.box.withFlux().

Parameters:

flux – The new flux for the object.

Original GalSim Documentation

This function is equivalent to obj.withScaledFlux(flux / obj.flux).

It creates a new object that has the same profile as the original, but with the surface brightness at every location rescaled such that the total flux will be the given value. Note that if flux is an SED, the return value will be a ChromaticObject with specified SED.

Returns:

the object with the new flux

classmethod tree_unflatten(aux_data, children)[source]

Recreates an instance of the class from flatten representation

class jax_galsim.Pixel(scale, flux=1.0, gsparams=None)[source]

Bases: Box

A class describing a pixel profile. This is just a 2D square top-hat function.

LAX-backend implementation of galsim.box.Pixel().

Parameters:
  • scale – The linear scale size of the pixel. Typically given in arcsec.

  • flux – The flux (in photons/cm^2/s) of the profile. This should almost certainly be left at the default value of 1. [default: 1]

  • gsparams – An optional GSParams argument. [default: None]

Original GalSim Documentation

This class is typically used to represent a pixel response function. It is used internally by the GSObject.drawImage function, but there may be cases where the user would want to use this profile directly.

property scale

The linear scale size of the Pixel.

LAX-backend implementation of scale().

withFlux(flux)[source]

Create a version of the current object with a different flux.

LAX-backend implementation of galsim.box.withFlux().

Parameters:

flux – The new flux for the object.

Original GalSim Documentation

This function is equivalent to obj.withScaledFlux(flux / obj.flux).

It creates a new object that has the same profile as the original, but with the surface brightness at every location rescaled such that the total flux will be the given value. Note that if flux is an SED, the return value will be a ChromaticObject with specified SED.

Returns:

the object with the new flux

tree_flatten()[source]

This function flattens the GSObject into a list of children nodes that will be traced by JAX and auxiliary static data.

classmethod tree_unflatten(aux_data, children)[source]

Recreates an instance of the class from flatten representation

Compound profiles

class jax_galsim.Sum(*args, gsparams=None, propagate_gsparams=True)[source]

Bases: GSObject

A class for adding 2 or more GSObject instances.

LAX-backend implementation of galsim.sum.Sum().

🔪 JAX-GalSim - The Sharp Bits 🔪

Does not support ChromaticObject at this point.

Parameters:
  • args – Unnamed args should be a list of objects to add.

  • gsparams – An optional GSParams argument. [default: None]

  • propagate_gsparams – Whether to propagate gsparams to each of the components. This is normally a good idea, but there may be use cases where one would not want to do this. [default: True]

Original GalSim Documentation

The Sum class is used to represent the sum of multiple GSObject instances. For example, it might be used to represent a multiple-component galaxy as the sum of an Exponential and a DeVaucouleurs, or to represent a PSF as the sum of multiple Gaussian objects.

Typically, you do not need to construct a Sum object explicitly. Normally, you would just use the + operator, which returns a Sum:

>>> bulge = galsim.Sersic(n=3, half_light_radius=0.8)
>>> disk = galsim.Exponential(half_light_radius=1.4)
>>> gal = bulge + disk
>>> psf = galsim.Gaussian(sigma=0.3, flux=0.3) + galsim.Gaussian(sigma=0.8, flux=0.7)

You can also use the Add() factory function, which returns a Sum object if none of the individual objects are chromatic:

>>> gal = galsim.Add([bulge,disk])

Note: if gsparams is unspecified (or None), then the Sum instance will use the most restrictive combination of parameters from each of the component objects. Normally, this means the smallest numerical value (e.g. folding_threshold, xvalue_accuracy, etc.), but for a few parameters, the largest numerical value is used. See GSParams.combine for details.

Furthermore, the gsparams used for the Sum (either given explicitly or derived from the components) will normally be applied to each of the components. It doesn’t usually make much sense to apply stricter-than-normal accuracy or threshold values to one component but not another in a Sum, so this ensures that they all have consistent rendering behavior. However, if you want to keep the existing gsparams of the component objects (e.g. because one object is much fainter and can thus use looser accuracy tolerances), then you may set propagate_gsparams=False.

property obj_list

The list of objects being added.

LAX-backend implementation of obj_list().

property flux

The flux of the profile.

LAX-backend implementation of flux().

withGSParams(gsparams=None, **kwargs)[source]

Create a version of the current object with the given gsparams

LAX-backend implementation of galsim.sum.withGSParams().

Original GalSim Documentation

Note

Unless you set propagate_gsparams=False, this method will also update the gsparams of each object being added.

tree_flatten()[source]

This function flattens the GSObject into a list of children nodes that will be traced by JAX and auxiliary static data.

classmethod tree_unflatten(aux_data, children)[source]

Recreates an instance of the class from flatten representation

class jax_galsim.Add(*args, **kwargs)[source]

Bases:

A function for adding 2 or more GSObject or ChromaticObject instances.

LAX-backend implementation of galsim.sum.Add().

🔪 JAX-GalSim - The Sharp Bits 🔪

Does not support ChromaticObject at this point.

Parameters:
  • args – Unnamed args should be a list of objects to add.

  • gsparams – An optional GSParams argument. [default: None]

  • propagate_gsparams – Whether to propagate gsparams to each of the components. This is normally a good idea, but there may be use cases where one would not want to do this. [default: True]

Original GalSim Documentation

This function will inspect its input arguments to decide if a Sum object or a ChromaticSum object is required to represent the sum of surface brightness profiles.

Typically, you do not need to call Add() explicitly. Normally, you would just use the + operator, which returns a Sum:

>>> bulge = galsim.Sersic(n=3, half_light_radius=0.8)
>>> disk = galsim.Exponential(half_light_radius=1.4)
>>> gal = bulge + disk
>>> psf = galsim.Gaussian(sigma=0.3, flux=0.3) + galsim.Gaussian(sigma=0.8, flux=0.7)

If one of the items is chromatic, it will return a ChromaticSum:

>>> disk = galsim.Exponential(half_light_radius=1.4) * galsim.SED(sed_file)
>>> gal = bulge + disk
Returns:

a Sum or ChromaticSum instance as appropriate.

class jax_galsim.Convolution(*args, **kwargs)[source]

Bases: GSObject

A class for convolving 2 or more GSObject instances.

LAX-backend implementation of galsim.convolve.Convolution().

🔪 JAX-GalSim - The Sharp Bits 🔪

Only supports ‘fft’ convolution.

Parameters:
  • args – Unnamed args should be a list of objects to convolve.

  • real_space – Whether to use real space convolution. [default: None, which means to automatically decide this according to whether the objects have hard edges.]

  • gsparams – An optional GSParams argument. [default: None]

  • propagate_gsparams – Whether to propagate gsparams to each of the components. This is normally a good idea, but there may be use cases where one would not want to do this. [default: True]

Original GalSim Documentation

The convolution will normally be done using discrete Fourier transforms of each of the component profiles, multiplying them together, and then transforming back to real space.

There is also an option to do the convolution as integrals in real space. To do this, use the optional keyword argument `real_space = True. Currently, the real-space integration is only enabled for convolving 2 profiles. (Aside from the trivial implementaion for 1 profile.) If you try to use it for more than 2 profiles, an exception will be raised.

The real-space convolution is normally slower than the DFT convolution. The exception is if both component profiles have hard edges, e.g. a truncated Moffat or Sersic with a Pixel. In that case, the highest frequency maxk for each component is quite large since the ringing dies off fairly slowly. So it can be quicker to use real-space convolution instead. Also, real-space convolution tends to be more accurate in this case as well.

If you do not specify either real_space = True or False explicitly, then we check if there are 2 profiles, both of which have hard edges. In this case, we automatically use real-space convolution. In all other cases, the default is not to use real-space convolution.

The normal way to use this class is to use the Convolve() factory function:

>>> gal = galsim.Sersic(n, half_light_radius)
>>> psf = galsim.Gaussian(sigma)
>>> final = galsim.Convolve([gal, psf])

The objects to be convolved may be provided either as multiple unnamed arguments (e.g. Convolve(psf, gal)) or as a list (e.g. Convolve([psf, gal])). Any number of objects may be provided using either syntax. (Well, the list has to include at least 1 item.)

Note: if gsparams is unspecified (or None), then the Convolution instance will use the most restrictive combination of parameters from each of the component objects. Normally, this means the smallest numerical value (e.g. folding_threshold, xvalue_accuracy, etc.), but for a few parameters, the largest numerical value is used. See GSParams.combine for details.

Furthermore, the gsparams used for the Convolution (either given explicitly or derived from the components) will normally be applied to each of the components. It doesn’t usually make much sense to apply stricter-than-normal accuracy or threshold values to one component but not another in a Convolution, so this ensures that they all have consistent rendering behavior. However, if you want to keep the existing gsparams of the component objects, then you may set propagate_gsparams=False.

property obj_list

The list of objects being convolved.

LAX-backend implementation of obj_list().

property real_space

Whether this Convolution should be drawn using real-space convolution rather than FFT convolution.

LAX-backend implementation of real_space().

withGSParams(gsparams=None, **kwargs)[source]

Create a version of the current object with the given gsparams

LAX-backend implementation of galsim.convolve.withGSParams().

Original GalSim Documentation

Note

Unless you set propagate_gsparams=False, this method will also update the gsparams of each object being convolved.

tree_flatten()[source]

This function flattens the GSObject into a list of children nodes that will be traced by JAX and auxiliary static data.

classmethod tree_unflatten(aux_data, children)[source]

Recreates an instance of the class from flatten representation

class jax_galsim.Convolve(*args, **kwargs)[source]

Bases:

A function for convolving 2 or more GSObject or ChromaticObject instances.

LAX-backend implementation of galsim.convolve.Convolve().

🔪 JAX-GalSim - The Sharp Bits 🔪

Does not support ChromaticConvolutions

Parameters:
  • args – Unnamed args should be a list of objects to convolve.

  • real_space – Whether to use real space convolution. [default: None, which means to automatically decide this according to whether the objects have hard edges.]

  • gsparams – An optional GSParams argument. [default: None]

  • propagate_gsparams – Whether to propagate gsparams to each of the components. This is normally a good idea, but there may be use cases where one would not want to do this. [default: True]

Original GalSim Documentation

This function will inspect its input arguments to decide if a Convolution object or a ChromaticConvolution object is required to represent the convolution of surface brightness profiles.

Returns:

a Convolution or ChromaticConvolution instance as appropriate.

class jax_galsim.Deconvolution(obj, gsparams=None, propagate_gsparams=True)[source]

Bases: GSObject

A class for deconvolving a GSObject.

LAX-backend implementation of galsim.convolve.Deconvolution().

Parameters:
  • obj – The object to deconvolve.

  • gsparams – An optional GSParams argument. [default: None]

  • propagate_gsparams – Whether to propagate gsparams to the deconvolved object. This is normally a good idea, but there may be use cases where one would not want to do this. [default: True]

Original GalSim Documentation

The Deconvolution class represents a deconvolution kernel. Note that the Deconvolution class, or compound objects (Sum, Convolution) that include a Deconvolution as one of the components, cannot be photon-shot using the ‘phot’ method of GSObject.drawImage method.

You may also specify a gsparams argument. See the docstring for GSParams for more information about this option. Note: if gsparams is unspecified (or None), then the Deconvolution instance inherits the same GSParams as the object being deconvolved.

The normal way to use this class is to use the Deconvolve() factory function:

>>> inv_psf = galsim.Deconvolve(psf)
>>> deconv_gal = galsim.Convolve(inv_psf, gal)
property orig_obj

The original object that is being deconvolved.

LAX-backend implementation of orig_obj().

withGSParams(gsparams=None, **kwargs)[source]

Create a version of the current object with the given gsparams

LAX-backend implementation of galsim.convolve.withGSParams().

Original GalSim Documentation

Note

Unless you set propagate_gsparams=False, this method will also update the gsparams of the wrapped component object.

tree_flatten()[source]

This function flattens the GSObject into a list of children nodes that will be traced by JAX and auxiliary static data.

classmethod tree_unflatten(aux_data, children)[source]

Recreates an instance of the class from flatten representation

class jax_galsim.Deconvolve(obj, gsparams=None, propagate_gsparams=True)[source]

Bases:

A function for deconvolving by either a GSObject or ChromaticObject.

LAX-backend implementation of galsim.convolve.Deconvolve().

🔪 JAX-GalSim - The Sharp Bits 🔪

Does not support ChromaticDeconvolution

Parameters:
  • obj – The object to deconvolve.

  • gsparams – An optional GSParams argument. [default: None]

  • propagate_gsparams – Whether to propagate gsparams to the deconvolved object. This is normally a good idea, but there may be use cases where one would not want to do this. [default: True]

Original GalSim Documentation

This function will inspect its input argument to decide if a Deconvolution object or a ChromaticDeconvolution object is required to represent the deconvolution by a surface brightness profile.

Returns:

a Deconvolution or ChromaticDeconvolution instance as appropriate.

class jax_galsim.DeltaFunction(flux=1.0, gsparams=None)[source]

Bases: GSObject

A class describing a DeltaFunction surface brightness profile.

LAX-backend implementation of galsim.deltafunction.DeltaFunction().

Parameters:
  • flux – The flux (in photons/cm^2/s) of the profile. [default: 1]

  • gsparams – An optional GSParams argument. [default: None]

Original GalSim Documentation

The DeltaFunction surface brightness profile is characterized by a single property, its flux.

A DeltaFunction can be initialized with a specified flux.

withFlux(flux)[source]

Create a version of the current object with a different flux.

LAX-backend implementation of galsim.deltafunction.withFlux().

Parameters:

flux – The new flux for the object.

Original GalSim Documentation

This function is equivalent to obj.withScaledFlux(flux / obj.flux).

It creates a new object that has the same profile as the original, but with the surface brightness at every location rescaled such that the total flux will be the given value. Note that if flux is an SED, the return value will be a ChromaticObject with specified SED.

Returns:

the object with the new flux

Interpolated image

class jax_galsim.InterpolatedImage(image, x_interpolant=None, k_interpolant=None, normalization='flux', scale=None, wcs=None, flux=None, pad_factor=4.0, noise_pad_size=0, noise_pad=0.0, rng=None, pad_image=None, calculate_stepk=True, calculate_maxk=True, use_cache=True, use_true_center=True, depixelize=False, offset=None, gsparams=None, _force_stepk=0.0, _force_maxk=0.0, _recenter_image=True, hdu=None, _obj=None)[source]

Bases: Transformation

A class describing non-parametric profiles specified using an Image, which can be interpolated for the purpose of carrying out transformations.

LAX-backend implementation of galsim.interpolatedimage.InterpolatedImage().

🔪 JAX-GalSim - The Sharp Bits 🔪

The JAX equivalent of galsim.InterpolatedImage does not support:

  • noise padding

  • the pad_image options

  • depixelize

  • most of the bounds checks, type checks, and dtype casts done by galsim

Parameters:
  • image – The Image from which to construct the object. This may be either an Image instance or a string indicating a fits file from which to read the image. In the latter case, the hdu kwarg can be used to specify a particular HDU in that file.

  • x_interpolant – Either an Interpolant instance or a string indicating which real-space interpolant should be used. Options are ‘nearest’, ‘sinc’, ‘linear’, ‘cubic’, ‘quintic’, or ‘lanczosN’ where N should be the integer order to use. [default: galsim.Quintic()]

  • k_interpolant – Either an Interpolant instance or a string indicating which k-space interpolant should be used. Options are ‘nearest’, ‘sinc’, ‘linear’, ‘cubic’, ‘quintic’, or ‘lanczosN’ where N should be the integer order to use. We strongly recommend leaving this parameter at its default value; see text above for details. [default: galsim.Quintic()]

  • normalization – Two options for specifying the normalization of the input Image: - “flux” or “f” means that the sum of the pixels is normalized to be equal to the total flux. - “surface brightness” or “sb” means that the pixels sample the surface brightness distribution at each location. This is overridden if you specify an explicit flux value. [default: “flux”]

  • scale – If provided, use this as the pixel scale for the Image; this will override the pixel scale stored by the provided Image, in any. If scale is None, then take the provided image’s pixel scale. [default: None]

  • wcs – If provided, use this as the wcs for the image. At most one of scale or wcs may be provided. [default: None]

  • flux – Optionally specify a total flux for the object, which overrides the implied flux normalization from the Image itself. [default: None]

  • pad_factor – Factor by which to pad the Image with zeros. We strongly recommend leaving this parameter at its default value; see text above for details. [default: 4]

  • noise_pad_size – If provided, the image will be padded out to this size (in arcsec) with the noise specified by noise_pad. This is important if you are planning to whiten the resulting image. You want to make sure that the noise-padded image is larger than the postage stamp onto which you are drawing this object. [default: None]

  • noise_pad – Noise properties to use when padding the original image with noise. This can be specified in several ways: a) as a float, which is interpreted as being a variance to use when padding with uncorrelated Gaussian noise; b) as a galsim.BaseCorrelatedNoise, which contains information about the desired noise power spectrum - any random number generator passed to the rng keyword will take precedence over that carried in an input BaseCorrelatedNoise instance; c) as an Image of a noise field, which is used to calculate the desired noise power spectrum; or d) as a string which is interpreted as a filename containing an example noise field with the proper noise power spectrum (as an Image in the first HDU). It is important to keep in mind that the calculation of the correlation function that is internally stored within a BaseCorrelatedNoise object is a non-negligible amount of overhead, so the recommended means of specifying a correlated noise field for padding are (b) or (d). In the case of (d), if the same file is used repeatedly, then the use_cache keyword (see below) can be used to prevent the need for repeated CorrelatedNoise initializations. [default: 0, i.e., pad with zeros]

  • use_cache – Specify whether to cache noise_pad read in from a file to save having to build a CorrelatedNoise object repeatedly from the same image. [default: True]

  • rng – If padding by noise, the user can optionally supply the random noise generator to use for drawing random numbers as rng (may be any kind of BaseDeviate object). Such a user-input random number generator takes precedence over any stored within a user-input BaseCorrelatedNoise instance (see the noise_pad parameter). If rng=None, one will be automatically created, using the time as a seed. [default: None]

  • pad_imageImage to be used for deterministically padding the original image. This can be specified in two ways: - as an Image; or - as a string which is interpreted as a filename containing an image to use (in the first HDU). The pad_image scale or wcs is ignored. It uses the same scale or wcs for both the image and the pad_image. The user should be careful to ensure that the image used for padding has roughly zero mean. The purpose of this keyword is to allow for a more flexible representation of some noise field around an object; if the user wishes to represent the sky level around an object, they should do that after they have drawn the final image instead. [default: None]

  • calculate_stepk – Specify whether to perform an internal determination of the extent of the object being represented by the InterpolatedImage; often this is useful in choosing an optimal value for the stepsize in the Fourier space lookup table. If you know a priori an appropriate maximum value for stepk, then you may also supply that here instead of a bool value, in which case the stepk value is still calculated, but will not go above the provided value. [default: True]

  • calculate_maxk – Specify whether to perform an internal determination of the highest spatial frequency needed to accurately render the object being represented by the InterpolatedImage; often this is useful in choosing an optimal value for the extent of the Fourier space lookup table. If you know a priori an appropriate maximum value for maxk, then you may also supply that here instead of a bool value, in which case the maxk value is still calculated, but will not go above the provided value. [default: True]

  • use_true_center – Similar to the same parameter in the GSObject.drawImage function, this sets whether to use the true center of the provided image as the center of the profile (if use_true_center=True) or the nominal center given by image.center (if use_true_center=False) [default: True]

  • depixelize – Whether to try to remove the effect of the pixelization. If this is True, then drawing this profile with method=’auto’ should render an image equivalent to the input image. If this is False (the default), then you would need to draw with method=’no_pixel’ to get an equivalent image. See discussion above. [default: False]

  • offset – The location in the input image to use as the center of the profile. This should be specified relative to the center of the input image (either the true center if use_true_center=True, or the nominal center if use_true_center=False). [default: None]

  • gsparams – An optional GSParams argument. [default: None]

  • hdu – When reading in an Image from a file, this parameter can be used to select a particular HDU in the file. [default: None]

  • _force_stepk – Override the normal stepk calculation (using gsparams.folding_threshold) and force stepk to the given value. [default: 0]

  • _force_maxk – Override the normal maxk calculation (using gsparams.maxk_threshold) and force maxk to the given value. This option in particular can help reduce FFT artifacts in a manner that is currently unobtainable by lowering maxk_threshold. [default: 0]

Original GalSim Documentation

The InterpolatedImage class is useful if you have a non-parametric description of an object as an Image, that you wish to manipulate / transform using GSObject methods such as GSObject.shear, GSObject.magnify, GSObject.shift, etc. Note that when convolving an InterpolatedImage, the use of real-space convolution is not recommended, since it is typically a great deal slower than Fourier-space convolution for this kind of object.

There are three options for determining the flux of the profile.

  1. You can simply specify a flux value explicitly.

  2. If you set normalization = 'flux', the flux will be taken as the sum of the pixel values in the input image. This corresponds to an image that was drawn with drawImage(method='no_pixel'). This is the default if flux is not given.

  3. If you set normalization = 'sb', the pixel values are treated as samples of the surface brightness profile at each location. This corresponds to an image drawn with drawImage(method='sb'). The flux is then the sum of the pixels in the input image multiplied by the pixel area.

You can also use images that were drawn with one of the pixel-integrating methods (‘auto’, ‘phot’, ‘fft’, or ‘real_space’), or real images where nature has integrated over the pixel for you. However, the resulting profile will by default include a convolution by a Pixel (this is equivalent to integration over the pixel). This is often acceptable, and the resulting InterpolatedImage object can be convolved by other profiles as usual. One just needs to remember to draw the final convolved profile using method='no_pixel' to avoid including the pixel convolution a second time. In particular, one should not use it in conjunction with photon shooting, for the same reason.

However, if you want to try to remove the effect of the pixel and have the InterpolatedImage model the pre-pixelized profile, then you can set depixelize=True. This will call Image.depixelize on the image automatically to try to remove the effect of the pixelization. We recommend using a Lanczos interpolant with this option for best results. (Higher order tends to work better here.) This step can be rather slow and memory-demanding, so use this with caution. But if used, the resulting profile represents the true underlying profile, without the pixel convolution. It can therefore be rotated, sheared, etc. And when rendering, one should use the methods that do involve integration over the pixel: auto, phot, etc.

Warning

Input images that are undersampled and/or noisy may not necessarily work well with the depixelize=True option. Users should treat this option with some care and validate that the results are sufficiently accurate for your particular use case.

If the input Image has a scale or wcs associated with it, then there is no need to specify one as a parameter here. But if one is provided, that will override any scale or wcs that is native to the Image.

The user may optionally specify an interpolant, x_interpolant, for real-space manipulations (e.g., shearing, resampling). If none is specified, then by default, a Quintic interpolant is used. The user may also choose to specify two quantities that can affect the Fourier space convolution: the k-space interpolant (k_interpolant) and the amount of padding to include around the original images (pad_factor). The default values for x_interpolant, k_interpolant, and pad_factor were chosen based on the tests of branch #389 to reach good accuracy without being excessively slow. Users should be particularly wary about changing k_interpolant and pad_factor from the defaults without careful testing. The user is given complete freedom to choose interpolants and pad factors, and no warnings are raised when the code is modified to choose some combination that is known to give significant error. More details can be found in http://arxiv.org/abs/1401.2636, especially table 1, and in comment https://github.com/GalSim-developers/GalSim/issues/389#issuecomment-26166621 and the following comments.

The user can choose to pad the image with a noise profile if desired. To do so, specify the target size for the noise padding in noise_pad_size, and specify the kind of noise to use in noise_pad. The noise_pad option may be a Gaussian random noise of some variance, or a Gaussian but correlated noise field that is specified either as a BaseCorrelatedNoise instance, an Image (from which a correlated noise model is derived), or a string (interpreted as a filename of an image to use for deriving a CorrelatedNoise). The user can also pass in a random number generator to be used for noise generation. Finally, the user can pass in a pad_image for deterministic image padding.

By default, the InterpolatedImage recalculates the Fourier-space step and number of points to use for further manipulations, rather than using the most conservative possibility. For typical objects representing galaxies and PSFs this can easily make the difference between several seconds (conservative) and 0.04s (recalculated). However, the user can turn off this option, and may especially wish to do so when using images that do not contain a high S/N object - e.g., images of noise fields.

Example:

>>> interpolated_image = galsim.InterpolatedImage(
        image, x_interpolant=None, k_interpolant=None, normalization='flux', scale=None,
        wcs=None, flux=None, pad_factor=4., noise_pad_size=0, noise_pad=0., use_cache=True,
        pad_image=None, rng=None, calculate_stepk=True, calculate_maxk=True,
        use_true_center=True, offset=None, hdu=None)

Initializes interpolated_image as an InterpolatedImage instance.

For comparison of the case of padding with noise or zero when the image itself includes noise, compare im1 and im2 from the following code snippet (which can be executed from the examples/ directory):

>>> image = galsim.fits.read('data/147246.0_150.416558_1.998697_masknoise.fits')
>>> int_im1 = galsim.InterpolatedImage(image)
>>> int_im2 = galsim.InterpolatedImage(image, noise_pad='data/blankimg.fits')
>>> im1 = galsim.ImageF(1000,1000)
>>> im2 = galsim.ImageF(1000,1000)
>>> int_im1.drawImage(im1, method='no_pixel')
>>> int_im2.drawImage(im2, method='no_pixel')

Examination of these two images clearly shows how padding with a correlated noise field that is similar to the one in the real data leads to a more reasonable appearance for the result when re-drawn at a different size.

property x_interpolant

The real-space Interpolant for this profile.

LAX-backend implementation of x_interpolant().

property k_interpolant

The Fourier-space Interpolant for this profile.

LAX-backend implementation of k_interpolant().

property image

The underlying Image being interpolated.

LAX-backend implementation of image().

tree_flatten()[source]

This function flattens the InterpolatedImage into a list of children nodes that will be traced by JAX and auxiliary static data.

classmethod tree_unflatten(aux_data, children)[source]

Recreates an instance of the class from flatten representation

withGSParams(gsparams=None, **kwargs)[source]

Create a version of the current object with the given GSParams.

LAX-backend implementation of galsim.interpolatedimage.withGSParams().

Original GalSim Documentation

You may either provide a GSParams instance:

>>> gsparams = galsim.GSParams(folding_threshold=1.e-4, maxk_threshold=1.e-4)
>>> obj = obj.withGSParams(gsparams)

or one or more named parameters as keyword arguments:

>>> obj = obj.withGSParams(folding_threshold=1.e-4, maxk_threshold=1.e-4)

Note

The latter style will leave all non-named parameters at their current values. It only updates the named parameters to the given values.

Transformations

class jax_galsim.Transform(obj, jac=(1.0, 0.0, 0.0, 1.0), offset=galsim.PositionD(x=0.0, y=0.0), flux_ratio=1.0, gsparams=None, propagate_gsparams=True)[source]

Bases:

A function for transforming either a GSObject or ChromaticObject.

LAX-backend implementation of galsim.transform.Transform().

🔪 JAX-GalSim - The Sharp Bits 🔪

Does not support Chromatic Objects or Convolutions.

Parameters:
  • obj – The object to be transformed.

  • jac – A list or tuple ( dudx, dudy, dvdx, dvdy ) describing the Jacobian of the transformation. Use None to indicate that the Jacobian is the 2x2 unit matrix. [default: None]

  • offset – A galsim.PositionD or tuple giving the offset by which to shift the profile. [default: (0.,0.)]

  • flux_ratio – A factor by which to multiply the surface brightness of the object. (Technically, not necessarily the flux. See above.) [default: 1]

  • gsparams – An optional GSParams argument. [default: None]

  • propagate_gsparams – Whether to propagate gsparams to the transformed object. This is normally a good idea, but there may be use cases where one would not want to do this. [default: True]

Original GalSim Documentation

This function will inspect its input argument to decide if a Transformation object or a ChromaticTransformation object is required to represent the resulting transformed object.

Note: the name of the flux_ratio parameter is technically wrong here if the jacobian has a non-unit determinant, since that would also scale the flux. The flux_ratio parameter actually only refers to an overall amplitude ratio for the surface brightness profile. The total flux scaling is actually |det(jac)| * flux_ratio.

Returns:

a Transformation or ChromaticTransformation instance as appropriate.

class jax_galsim.Transformation(obj, jac=(1.0, 0.0, 0.0, 1.0), offset=galsim.PositionD(x=0.0, y=0.0), flux_ratio=1.0, gsparams=None, propagate_gsparams=True)[source]

Bases: GSObject

A class for modeling an affine transformation of a GSObject instance.

LAX-backend implementation of galsim.transform.Transformation().

Parameters:
  • obj – The object to be transformed.

  • jac – A list, tuple or numpy array ( dudx, dudy, dvdx, dvdy ) describing the Jacobian of the transformation. Use None to indicate that the Jacobian is the 2x2 unit matrix. [default: None]

  • offset – A galsim.PositionD or tuple giving the offset by which to shift the profile. [default: (0.,0.)]

  • flux_ratio – A factor by which to multiply the surface brightness of the object. (Technically, not necessarily the flux. See above.) [default: 1]

  • gsparams – An optional GSParams argument. [default: None]

  • propagate_gsparams – Whether to propagate gsparams to the transformed object. This is normally a good idea, but there may be use cases where one would not want to do this. [default: True]

Original GalSim Documentation

Typically, you do not need to construct a Transformation object explicitly. This is the type returned by the various transformation methods of GSObject such as GSObject.shear, GSObject.rotate, GSObject.shift, GSObject.transform, etc.

All the various transformations can be described as a combination of a jacobian matrix (i.e. GSObject.transform) and a translation (GSObject.shift), which are described by (dudx,dudy,dvdx,dvdy) and (dx,dy) respectively.

Note

The name of the flux_ratio parameter is technically wrong here if the jacobian has a non-unit determinant, since that would also scale the flux. The flux_ratio parameter actually only refers to an overall amplitude ratio for the surface brightness profile. The total flux scaling is actually |det(jac)| * flux_ratio.

Attributes:

original: The original object that is being transformed. jac: The jacobian of the transformation matrix. offset: The offset being applied. flux_ratio: The amount by which the overall surface brightness amplitude is multiplied. gsparams: The usual gsparams attribute that all GSObject classes have.

Note: if gsparams is unspecified (or None), then the Transformation instance inherits the GSParams from obj. Also, note that parameters related to the Fourier-space calculations must be set when initializing obj, NOT when creating the Transform (at which point the accuracy and threshold parameters will simply be ignored).

property original

The original object being transformed.

LAX-backend implementation of original().

property jac

The Jacobian of the transforamtion.

LAX-backend implementation of jac().

property offset

The offset of the transformation.

LAX-backend implementation of offset().

property flux_ratio

The flux ratio of the transformation.

LAX-backend implementation of flux_ratio().

withGSParams(gsparams=None, **kwargs)[source]

Create a version of the current object with the given gsparams

LAX-backend implementation of galsim.transform.withGSParams().

Original GalSim Documentation

Note

Unless you set propagate_gsparams=False, this method will also update the gsparams of the wrapped component object.

tree_flatten()[source]

This function flattens the Transform into a list of children nodes that will be traced by JAX and auxiliary static data.

classmethod tree_unflatten(aux_data, children)[source]

Recreates an instance of the class from flatten representation