Correlated Noise
The pixel noise in real astronomical images can be correlated, so we have some functionality to enable simulating this effect in GalSim.
- BaseCorrelatedNoisedefines the correlated noise according to an input- GSObject. This is the base class for the other ways of defining correlated noise, and implements most of the useful methods of these classes.- Warning - This - GSObjectprofile must have two-fold rotational symmetry to represent a physical correlation function, and this requirement is not enforced by GalSim. Users need to ensure this fact in their calling code.
- CorrelatedNoisecomputes the correlated noise of in input- Image, e.g. a blank patch of sky in an image similar to the one you want to simulate.
- UncorrelatedNoiseis a- BaseCorrelatedNoisethat start with no correlations. This can then be sheared or convolved with other profiles to induce correlations.
- getCOSMOSNoiseis a function the returns a- BaseCorrelatedNoisecorresponding to the correlated noise found in the HST COSMOS F814W coadd images used by- RealGalaxy.
While adding correlated noise to images is a useful feature, this functionality was originally
implemented in GalSim in order to remove correlations.  Specifically, the RealGalaxy class
treats HST images as surface brightness profiles.  These images have correlated noise that resulted
from the drizzle image processing.  Furthermore, when sheared or convolved by a PSF, the
noise in these images becomes even more correlated.  If uncorrected, these pixel correlations
can lead to biases in weak lensing shear estimates of the rendered galaxies.
To produce more accurate image simulations using these galaxies as the underlying models (and especially avoid the weak lensing shear biases), it is often useful to “whiten” the correlated noise that results form these manipulations.
- Image.whitenNoisetakes a- BaseCorrelatedNoiseinstance as the estimate of the correlated noise already in an image, and attempts to add more noise to result in uncorrelated “white” noise.
- Image.symmetrizeNoisesimilarly adds noise, but only attempts to produce a noise profile with 4-fold (or generically any order) symmetry, which results in less added noise while still achieving the goal of not having correlated noise bias weak lensing shear measurements.
- class galsim.BaseCorrelatedNoise(rng, gsobject, wcs=galsim.PixelScale(1.0))[source]
- Bases: - object- A Base Class describing 2D correlated Gaussian random noise fields. - A BaseCorrelatedNoise will not generally be instantiated directly. This is recommended as the current - BaseCorrelatedNoise.__init__interface does not provide any guarantee that the input- GSObjectrepresents a physical correlation function, e.g. a profile that is an even function (two-fold rotationally symmetric in the plane) and peaked at the origin. The proposed pattern is that users instead instantiate derived classes, such as the- CorrelatedNoise, which are able to guarantee the above.- If you have the correlation function as an image on file, you can use the class method - from_file, which does confirm that the file has the appropriate symmetry.- The BaseCorrelatedNoise is therefore here primarily to define the way in which derived classes (currently only - CorrelatedNoiseand- UncorrelatedNoise) store the random deviate, noise correlation function profile and allow operations with it, generate images containing noise with these correlation properties, and generate covariance matrices according to the correlation function.- Parameters:
- rng – A - BaseDeviateinstance to use for generating the random numbers.
- gsobject – - The - GSObjectdefining the correlation function.
- wcs – The wcs for the image to define the phyical relationship between the pixels. [default: PixelScale(1.0)] 
 
 - applyTo(image)[source]
- Apply this correlated Gaussian random noise field to an input - Image.- To add deviates to every element of an image, the syntax: - >>> image.addNoise(correlated_noise) - is preferred. However, this is equivalent to calling this instance’s - applyTomethod as follows:- >>> correlated_noise.applyTo(image) - On output the - Imageinstance- imagewill have been given additional noise according to the given- BaseCorrelatedNoiseinstance- correlated_noise. Normally,- image.scaleis used to determine the input pixel separation, and if- image.scale <= 0a pixel scale of 1 is assumed. If the image has a non-uniform WCS, the local uniform approximation at the center of the image will be used.- Note that the correlations defined in a correlated_noise object are defined in terms of world coordinates (i.e. typically arcsec on the sky). Some care is thus required if you apply correlated noise to an image with a non-trivial WCS. The correlations will have a specific direction and scale in world coordinates, so if you apply them to an image with a WCS that has a rotation or a different pixel scale than the original, the resulting correlations will have the correct direction and scale in world coordinates, but a different direction and/or scale in image coordinates. - If you want to override this behavior, you can view your image with the WCS of the correlation function and apply the noise to that. For example: - >>> image = galsim.Image(nx, ny, wcs=complicated_wcs) >>> noise = galsim.getCOSMOSNoise(rng=rng) >>> image.view(wcs=noise.wcs).addNoise(noise) - This will create noise whose pixel-to-pixel correlations match those of the original correlated noise image (in this case, the COSMOS images). If the input image has no WCS set, then it will be treated as having the same WCS as the noise. - Note that the correlated noise field in - imagewill be periodic across its boundaries: this is due to the fact that the internals of the- BaseCorrelatedNoisecurrently use a relatively simple implementation of noise generation using the Fast Fourier Transform. If you wish to avoid this property being present in your final- imageyou should add the noise to an- imageof greater extent than you need, and take a subset.- Parameters:
- image – The input - Imageobject.
 
 - convolvedWith(gsobject, gsparams=None)[source]
- Convolve the correlated noise model with an input - GSObject.- The resulting correlated noise model will then give a statistical description of the noise field that would result from convolving noise generated according to the initial correlated noise with a kernel represented by - gsobject(e.g. a PSF).- The practical purpose of this method is that it allows us to model what is happening to noise in the images from Hubble Space Telescope that we use for simulating PSF convolved galaxies with the - RealGalaxyclass.- This modifies the representation of the correlation function, but leaves the random number generator unchanged. - Examples: - The following command simply applies a Moffat PSF with slope parameter beta=3. and FWHM=0.7: - >>> cn = cn.convolvedWith(galsim.Moffat(beta=3., fwhm=0.7)) - Often we will want to convolve with more than one function. For example, if we wanted to simulate how a noise field would look if convolved with a ground-based PSF (such as the Moffat above) and then rendered onto a new (typically larger) pixel grid, the following example command demonstrates the syntax: - >>> cn = cn.convolvedWith( ... galsim.Convolve([galsim.Deconvolve(galsim.Pixel(0.03)), ... galsim.Pixel(0.2), galsim.Moffat(3., fwhm=0.7), - Note, we also deconvolve by the original pixel, which should be the pixel size of the image from which the - correlated_noisewas made. This command above is functionally equivalent to:- >>> cn = cn.convolvedWith(galsim.Deconvolve(galsim.Pixel(0.03))) >>> cn = cn.convolvedWith(galsim.Pixel(0.2)) >>> cn = cn.convolvedWith(galsim.Moffat(beta=3., fwhm=0.7)) - as is demanded for a linear operation such as convolution. - Parameters:
- Returns:
- the new - BaseCorrelatedNoiseof the convolved profile.
 
 - copy(rng=None)[source]
- Returns a copy of the correlated noise model. - By default, the copy will share the - BaseDeviaterandom number generator with the parent instance. However, you can provide a new rng to use in the copy if you want with:- >>> cn_copy = cn.copy(rng=new_rng) 
 - dilate(scale)[source]
- Apply the appropriate changes to the scale and variance for when the object has an applied dilation. - Parameters:
- scale – The linear dilation scale factor. 
- Returns:
- a new - BaseCorrelatedNoiseobject with the specified dilation.
 
 - drawImage(image=None, scale=None, wcs=None, dtype=None, add_to_image=False)[source]
- A method for drawing profiles storing correlation functions. - This is a mild reimplementation of the - GSObject.drawImagemethod. The- methodis automatically set to ‘sb’ and cannot be changed, and the- gainis set to unity. Also, not all the normal parameters of the- GSObjectmethod are available.- If - scaleand- wcsare not set, and the- imagehas no- wcsattribute, then this will use the wcs of the- BaseCorrelatedNoiseobject.- Parameters:
- image – If provided, this will be the image on which to draw the profile. If - imageis None, then an automatically-sized- Imagewill be created. If- imageis 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].
- scale – If provided, use this as the pixel scale for the image. [default: None] 
- wcs – If provided, use this as the wcs for the image (possibly overriding any existing - image.wcs). At most one of- scaleor- wcsmay be provided. [default: None] Note: If no WCS is provided either via- scale,- wcsor- image.wcs, then the noise object’s wcs will be used.
- dtype – The data type to use for an automatically constructed image. Only valid if - imageis None. [default: None, which means to use numpy.float32]
- 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 - imagebe provided and that it have defined bounds. [default: False]
 
- Returns:
- an - Imageof the correlation function.
 
 - drawKImage(image=None, nx=None, ny=None, bounds=None, scale=None, add_to_image=False)[source]
- A method for drawing profiles storing correlation functions (i.e., power spectra) in Fourier space. - This is a mild reimplementation of the - GSObject.drawKImagemethod. The- gainis automatically set to unity and cannot be changed. Also, not all the normal parameters of the- GSObjectmethod are available.- If - scaleis not set, and- imagehas no- wcsattribute, then this will use the wcs of the- BaseCorrelatedNoiseobject, which must be a- PixelScale.- Parameters:
- image – If provided, this will be the - Imageonto which to draw the k-space image. If- imageis None, then an automatically-sized image will be created. If- imageis given, but its bounds are undefined, then it will be resized appropriately based on the profile’s size. [default: None]
- nx – If provided and - imageis None, use to set the x-direction size of the image. Must be accompanied by- ny.
- ny – If provided and - imageis None, use to set the y-direction size of the image. Must be accompanied by- nx.
- bounds – If provided and - imageis None, use to set the bounds of the image.
- scale – If provided, use this as the pixel scale, dk, for the images. If - scaleis None and- imageis given, then take the provided images’ pixel scale (which must be equal). If- scaleis None and- imageis 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 - imagebe provided and that it has defined bounds. [default: False]
 
- Returns:
- the tuple of - Imageinstances,- (re, im)(created if necessary)
 
 - expand(scale)[source]
- Scale the linear scale of correlations in this noise model by - scale.- Scales the linear dimensions of the image by the factor - scale, e.g.- half_light_radius<–- half_light_radius * scale.- Parameters:
- scale – The linear rescaling factor to apply. 
- Returns:
- a new - BaseCorrelatedNoiseobject with the specified expansion.
 
 - classmethod from_file(file_name, pixel_scale, rng=None, variance=0.0, x_interpolant=None, gsparams=None)[source]
- Read a correlated noise profile from a file. - The file should contain an image of the correlation. - The image should be square with odd size in each direction. 
- The central pixel corresponds to the zero-lag correlation, i.e. the variance. Call this pixel element (0,0). 
- The other pixels (i,j) give the cross-correlation of the noise for pixels separated by i pixels in the x direction (columns) and j pixels in the y direction (rows). 
- The image therefore must be 180 degree rotationally symmetric. i.e. the value at (i,j) must be the same as at (-i,-j). 
 - The pixel_scale is also required and defines the pixel scale of the original image. - The default - x_interpolantis a- galsim.Linear(), which uses bilinear interpolation. The use of this interpolant is an approximation that gives good empirical results without requiring internal convolution of the correlation function profile by a- Pixelobject when applying correlated noise to images: such an internal convolution has been found to be computationally costly in practice, requiring the Fourier transform of very large arrays.- The use of the bilinear interpolants means that the representation of correlated noise will be noticeably inaccurate in at least the following two regimes: - If the pixel scale of the desired final output (e.g. the target image of - BaseCorrelatedNoise.drawImage,- BaseCorrelatedNoise.applyToor- BaseCorrelatedNoise.whitenImage) is small relative to the separation between pixels in the- imageused to instantiate- cnas shown above.
- If the - BaseCorrelatedNoiseinstance- cnwas instantiated with an image of scale comparable to that in the final output, and- cnhas been rotated or otherwise transformed (e.g. via the- BaseCorrelatedNoise.rotate,- BaseCorrelatedNoise.shearmethods; see below).
 - Conversely, the approximation will work best in the case where the correlated noise used to instantiate the - cnis taken from an input image for which- image.scaleis smaller than that in the desired output. This is the most common use case in the practical treatment of correlated noise when simulating galaxies from space as observed in ground-based surveys.- Changing from the default bilinear interpolant is made possible, but not recommended. In our validation tests, we found that the Linear interpolant usually gave the most accurate results. - Parameters:
- file_name – The name of the file to read. 
- pixel_scale – The pixel scale of the original image. 
- rng – If provided, a random number generator to use as the random number generator of the resulting noise object. (may be any kind of - BaseDeviateobject) [default: None, in which case, one will be automatically created, using the time as a seed.]
- variance – Scales the correlation function so that its point variance, equivalent to its value at zero separation distance, matches this value. [default: 0., which means to use the variance in the original file.] 
- x_interpolant – Forces use of a non-default interpolant for interpolation of the internal lookup table in real space. See below for more details. [default: galsim.Linear()] 
- gsparams – An optional - GSParamsargument. [default: None]
 
- Returns:
- a - BaseCorrelatedNoiseinstance
 
 - getVariance()[source]
- Return the point variance of this noise field, equal to its correlation function value at zero distance. - This is the variance of values in an image filled with noise according to this model. 
 - lens(g1, g2, mu)[source]
- Apply the appropriate changes for when the object has an applied shear and magnification. - 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. 
 
- Returns:
- a new - BaseCorrelatedNoiseobject with the specified shear and magnification.
 
 - magnify(mu)[source]
- Apply the appropriate changes to the scale and variance for when the object has an applied magnification - mu.- Parameters:
- mu – The lensing magnification 
- Returns:
- a new - BaseCorrelatedNoiseobject with the specified magnification.
 
 - property rng
- The - BaseDeviatefor this object.
 - rotate(theta)[source]
- Apply a rotation - thetato this correlated noise model.- Parameters:
- theta – Rotation angle ( - Angleobject, positive means anticlockwise).
- Returns:
- a new - BaseCorrelatedNoiseobject with the specified rotation.
 
 - shear(*args, **kwargs)[source]
- Apply a shear to this correlated noise model, where arguments are either a - Shear, or arguments that will be used to initialize one.- For more details about the allowed keyword arguments, see the - Sheardocstring.- Parameters:
- shear – The shear to be applied. Or, as described above, you may instead supply parameters do construct a shear directly. eg. - corr.shear(g1=g1,g2=g2).
- Returns:
- a new - BaseCorrelatedNoiseobject with the specified shear.
 
 - symmetrizeImage(image, order=4)[source]
- Apply noise designed to impose N-fold symmetry on the existing noise in a (square) input - Image.- On input, The - Image,- image, is assumed to have correlated noise described by this- BaseCorrelatedNoiseinstance.- On output - imagewill have been given additional (correlated) noise designed to symmetrize the noise profile.- When called for a non-square image, this method will raise an exception, unlike the noise whitening routines. - The - orderof the symmetry can be supplied as a keyword argument, with the default being 4 because this is presumably the minimum required for the anisotropy of noise correlations to not affect shear statistics.- Note: the syntax - image.symmetrizeNoise(noise, order)is preferred, but it is equivalent to:- >>> correlated_noise.symmetrizeImage(image, order=order) - If the - imageoriginally contained noise with a correlation function described by the- correlated_noiseinstance, the combined noise after using the symmetrizeImage() method will have a noise correlation function with N-fold symmetry, where- N=order.- Note that the code doesn’t check that the “if” above is true: the user MUST make sure this is the case for the final noise correlation function to be symmetric in the requested way. - Normally, - image.scaleis used to determine the input pixel separation, and if- image.wcsis None, it will use the wcs of the noise. If the image has a non-uniform WCS, the local uniform approximation at the center of the image will be used.- If you are interested in a theoretical calculation of the variance in the final noise field after imposing symmetry, the symmetrizeImage() method in fact returns this variance. For example: - >>> variance = correlated_noise.symmetrizeImage(image, order=order) - For context, in comparison with the - whitenImagemethod for the case of noise correlation functions that are roughly like those in the COSMOS HST data, the amount of noise added to impose N-fold symmetry is usually much less than what is added to fully whiten the noise. The usage of symmetrizeImage() is totally analogous to the usage of- whitenImage.- Parameters:
- image – The square input - Imageobject.
- order – The order at which to require the noise to be symmetric. All noise fields are already 2-fold symmetric, so - ordershould be an even integer >2. [default: 4].
 
- Returns:
- the theoretically calculated variance of the combined noise fields in the updated image. 
 
 - transform(dudx, dudy, dvdx, dvdy)[source]
- Apply an arbitrary jacobian transformation to this correlated noise model. - 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. 
 
- Returns:
- a new - BaseCorrelatedNoiseobject with the specified transformation.
 
 - whitenImage(image)[source]
- Apply noise designed to whiten correlated Gaussian random noise in an input - Image.- On input, The - Image,- image, is assumed to have correlated noise described by this- BaseCorrelatedNoiseinstance.- On output - imagewill have been given additional (correlated) noise designed to whiten the noise profile.- Note: the syntax - image.whitenNoise(noise)is normally preferred, but it is equivalent to:- >>> correlated_noise.whitenImage(image) - If the - imageoriginally contained noise with a correlation function described by the- correlated_noiseinstance, the combined noise after using the whitenImage() method will be approximately uncorrelated. Tests using COSMOS noise fields suggest ~0.3% residual off-diagonal covariances after whitening, relative to the variance, although results may vary depending on the precise correlation function of the noise field. (See- devel/external/hst/compare_whitening_subtraction.pyfor the COSMOS tests.)- Note that the code doesn’t check that the “if” above is true: the user MUST make sure this is the case for the final noise to be uncorrelated. - Normally, - image.scaleis used to determine the input- Imagepixel separation, and if- image.wcsis None, it will use the wcs of the noise. If the image has a non-uniform WCS, the local uniform approximation at the center of the image will be used.- If you are interested in a theoretical calculation of the variance in the final noise field after whitening, the whitenImage() method in fact returns this variance. For example: - >>> variance = correlated_noise.whitenImage(image) - Example: - To see noise whitening in action, let us use a model of the correlated noise in COSMOS as returned by the - getCOSMOSNoisefunction. Let’s initialize and add noise to an image:- >>> cn = galsim.getCOSMOSNoise() >>> image = galsim.ImageD(256, 256, scale=0.03) >>> # The scale should match the COSMOS default since didn't specify another >>> image.addNoise(cn) - The - imagewill then contain a realization of a random noise field with COSMOS-like correlation. Using the whitenImage() method, we can now add more noise to- imagewith a power spectrum specifically designed to make the combined noise fields uncorrelated:- >>> cn.whitenImage(image) - Of course, this whitening comes at the cost of adding further noise to the image, but the algorithm is designed to make this additional noise (nearly) as small as possible. - Parameters:
- image – The input - Imageobject.
- Returns:
- the theoretically calculated variance of the combined noise fields in the updated image. 
 
 - withGSParams(gsparams=None, **kwargs)[source]
- Create a version of the current object with the given - GSParams.
 - withScaledVariance(variance_ratio)[source]
- Scale the entire correlated noise field by the given factor. - This is equivalent to cn * variance_ratio. - Parameters:
- variance_ratio – The factor by which to scale the variance of the correlation function profile. 
- Returns:
- a - BaseCorrelatedNoiseobject whose variance and covariances have been scaled up by the given factor.
 
 - withVariance(variance)[source]
- Set the point variance of the noise field, equal to its correlation function value at zero distance, to an input - variance. The rest of the correlated noise field is scaled proportionally.- Parameters:
- variance – The desired point variance in the noise. 
- Returns:
- a - BaseCorrelatedNoiseobject with the new variance.
 
 
- class galsim.CorrelatedNoise(image, rng=None, scale=None, wcs=None, x_interpolant=None, correct_periodicity=True, subtract_mean=False, gsparams=None)[source]
- Bases: - BaseCorrelatedNoise- A class that represents 2D correlated noise fields calculated from an input - Image.- This class stores an internal representation of a 2D, discrete correlation function, and allows a number of subsequent operations including interpolation, shearing, magnification and rendering of the correlation function profile into an output - Image.- The class also allows correlated Gaussian noise fields to be generated according to the correlation function, and added to an - Image: see- BaseCorrelatedNoise.applyTo.- It also provides methods for whitening or imposing N-fold symmetry on pre-existing noise that shares the same spatial correlations: see - BaseCorrelatedNoise.whitenImageand- BaseCorrelatedNoise.symmetrizeImage, respectively.- It also allows the combination of multiple correlation functions by addition, and for the scaling of the total variance they represent by scalar factors. - Parameters:
- image – The image from which to derive the correlated noise profile 
- rng – A - BaseDeviateinstance to use for generating the random numbers.
- scale – If provided, use this as the pixel scale. Normally, the scale (or wcs) is taken from the image.wcs field, but you may override that by providing either scale or wcs. [default: use image.wcs if defined, else 1.0, unless - wcsis provided]
- wcs – If provided, use this as the wcs for the image. At most one of - scaleor- wcsmay be provided. [default: None]
- x_interpolant – The interpolant to use for interpolating the image of the correlation function. (See below.) [default: galsim.Linear()] 
- correct_periodicity – Whether to correct for the effects of periodicity. (See below.) [default: True] 
- subtract_mean – Whether to subtract off the mean value from the image before computing the correlation function. [default: False] 
- gsparams – An optional - GSParamsargument. [default: None]
 
 - Basic example: - >>> cn = galsim.CorrelatedNoise(image, rng=rng) - Instantiates a CorrelatedNoise using the pixel scale information contained in - image.scale(assumes the scale is unity if- image.scale <= 0.) by calculating the correlation function in the input- image. The input- rngmust be a- BaseDeviateor derived class instance, setting the random number generation for the noise.- Optional Inputs: - >>> cn = galsim.CorrelatedNoise(image, rng=rng, scale=0.2) - The example above instantiates a CorrelatedNoise, but forces the use of the pixel scale - scaleto set the units of the internal lookup table.:- >>> cn = galsim.CorrelatedNoise(image, rng=rng, x_interpolant=galsim.Lanczos(5)) - The example above instantiates a CorrelatedNoise, but forces use of a non-default interpolant for interpolation of the internal lookup table in real space. - The default - x_interpolantis- galsim.Linear(), which uses bilinear interpolation. The use of this interpolant is an approximation that gives good empirical results without requiring internal convolution of the correlation function profile by a- Pixelobject when applying correlated noise to images: such an internal convolution has been found to be computationally costly in practice, requiring the Fourier transform of very large arrays.- The use of the bilinear interpolants means that the representation of correlated noise will be noticeably inaccurate in at least the following two regimes: - If the pixel scale of the desired final output (e.g. the target image of - BaseCorrelatedNoise.drawImage,- BaseCorrelatedNoise.applyToor- BaseCorrelatedNoise.whitenImage) is small relative to the separation between pixels in the- imageused to instantiate- cnas shown above.
- If the CorrelatedNoise instance - cnwas instantiated with an image of scale comparable to that in the final output, and- cnhas been rotated or otherwise transformed (e.g. via the- BaseCorrelatedNoise.rotate,- BaseCorrelatedNoise.shearmethods; see below).
 - Conversely, the approximation will work best in the case where the correlated noise used to instantiate the - cnis taken from an input image for which- image.scaleis smaller than that in the desired output. This is the most common use case in the practical treatment of correlated noise when simulating galaxies from space telescopes, such as COSMOS.- Changing from the default bilinear interpolant is made possible, but not recommended. In our validation tests, we found that the Linear interpolant usually gave the most accurate results. - There is also an option to switch off an internal correction for assumptions made about the periodicity in the input noise image. If you wish to turn this off you may, e.g.: - >>> cn = galsim.CorrelatedNoise(image, rng=rng, correct_periodicity=False) - The default and generally recommended setting is - correct_periodicity=True.- Users should note that the internal calculation of the discrete correlation function in - imagewill assume that- imageis periodic across its boundaries, introducing a dilution bias in the estimate of inter-pixel correlations that increases with separation. Unless you know that the noise in- imageis indeed periodic (perhaps because you generated it to be so), you will not generally wish to use the- correct_periodicity=Falseoption.- By default, the image is not mean subtracted before the correlation function is estimated. To do an internal mean subtraction, you can set the - subtract_meankeyword to- True, e.g.:- >>> cn = galsim.CorrelatedNoise(image, rng=rng, subtract_mean=True) - Using the - subtract_meanoption will introduce a small underestimation of variance and other correlation function values due to a bias on the square of the sample mean. This bias reduces as the input image becomes larger, and in the limit of uncorrelated noise tends to the constant term- variance/N**2for an N x N sized- image.- It is therefore recommended that a background/sky subtraction is applied to the - imagebefore it is given as an input to the- CorrelatedNoise, allowing the default- subtract_mean=False. If such a background model is global or based on large regions on sky then assuming that the image has a zero population mean will be reasonable, and won’t introduce a bias in covariances from an imperfectly-estimated sample mean subtraction. If this is not possible, just be aware that- subtract_mean=Truewill bias the correlation function low to some level.- You may also specify a gsparams argument. See the docstring for - GSParamsfor more information about this option.- Methods: - The main way that a CorrelatedNoise is used is to add correlated noise to an image. The syntax: - >>> image.addNoise(cn) - is preferred, although: - >>> cn.applyTo(image) - is equivalent. See the - Image.addNoisemethod docstring for more information. The- image.scaleis used to get the pixel scale of the input image unless this is <= 0, in which case a scale of 1 is assumed.- A number of methods familiar from - GSObjectinstances have also been implemented directly as- cnmethods, so that the following commands are all legal:- >>> image = cn.drawImage(im, scale) >>> cn = cn.shear(s) >>> cn = cn.expand(m) >>> cn = cn.rotate(theta * galsim.degrees) >>> cn = cn.transform(dudx, dudy, dvdx, dvdy) - See the individual method docstrings for more details. The - shiftmethod is not available since a correlation function must always be centred and peaked at the origin.- The methods: - >>> var = cn.getVariance() >>> cn1 = cn.withVariance(variance) >>> cn2 = cn.withScaledVariance(variance_ratio) - can be used to get and set the point variance of the correlated noise, equivalent to the zero separation distance correlation function value. - The - BaseCorrelatedNoise.withVariancemethod scales the whole internal correlation function so that its point variance matches- variance.- Similarly, - BaseCorrelatedNoise.withScaledVariancescales the entire function by the given factor.- Arithmetic Operators: - Addition, multiplication and division operators are defined to work in an intuitive way for correlation functions. - Addition works simply to add the internally-stored correlation functions, so that: - >>> cn3 = cn2 + cn1 >>> cn4 += cn5 - provides a representation of the correlation function of two linearly summed fields represented by the individual correlation function operands. - What happens to the internally stored random number generators in the examples above? For all addition operations it is the - BaseDeviatebelonging to the instance on the left-hand side of the operator that is retained.- In the example above therefore, it is the random number generator from - cn2that will be stored and used by- cn3, and- cn4will retain its random number generator after in-place addition of- cn5. The random number generator of- cn5is not affected by the operation.- The multiplication and division operators, e.g.: - >>> cn1 /= 3. >>> cn2 = cn1 * 3 - scale the overall correlation function by a scalar operand. The random number generators are not affected by these scaling operations. 
- class galsim.UncorrelatedNoise(variance, rng=None, scale=None, wcs=None, gsparams=None)[source]
- Bases: - BaseCorrelatedNoise- A class that represents 2D correlated noise fields that are actually (at least initially) uncorrelated. Subsequent applications of things like - BaseCorrelatedNoise.shearor- BaseCorrelatedNoise.convolvedWithwill induce correlations.- The noise is characterized by a variance in each image pixel and a pixel size and shape. The - variancevalue refers to the noise variance in each pixel. If the pixels are square (the usual case), you can specify the size using the- scaleparameter. If not, they are effectively specified using the local wcs function that defines the pixel shape. i.e.:- >>> world_pix = wcs.toWorld(Pixel(1.)) - should return the pixel profile in world coordinates. - Parameters:
- variance – The noise variance value to model as being uniform and uncorrelated over the whole image. 
- rng – If provided, a random number generator to use as the random number generator of the resulting noise object. (may be any kind of - BaseDeviateobject) [default: None, in which case, one will be automatically created, using the time as a seed.]
- scale – If provided, use this as the pixel scale. [default: 1.0, unless - wcsis provided]
- wcs – If provided, use this as the wcs for the image. At most one of - scaleor- wcsmay be provided. [default: None]
- gsparams – An optional - GSParamsargument. [default: None]
 
 
- galsim.getCOSMOSNoise(file_name=None, rng=None, cosmos_scale=0.03, variance=0.0, x_interpolant=None, gsparams=None)[source]
- Returns a representation of correlated noise in the HST COSMOS F814W unrotated science coadd images. - See http://cosmos.astro.caltech.edu/astronomer/hst.html for information about the COSMOS survey, and Leauthaud et al (2007) for detailed information about the unrotated F814W coadds used for weak lensing science. - This function uses a stacked estimate of the correlation function in COSMOS noise fields. The correlation function was computed by the GalSim team as described in: - GalSim/devel/external/hst/make_cosmos_cfimage.py - The resulting file is distributed with GalSim as: - os.path.join('galsim.meta_data.share_dir', 'acs_I_unrot_sci_20_cf.fits') - Parameters:
- file_name – If provided, override the usual location of the file with the given file name. [default: None] 
- rng – If provided, a random number generator to use as the random number generator of the resulting noise object. (may be any kind of - BaseDeviateobject) [default: None, in which case, one will be automatically created, using the time as a seed.]
- cosmos_scale – COSMOS ACS F814W coadd image pixel scale in the units you are using to describe - GSObjectinstances and image scales in GalSim. [default: 0.03 (arcsec), see below for more information.]
- variance – Scales the correlation function so that its point variance, equivalent to its value at zero separation distance, matches this value. [default: 0., which means to use the variance in the original COSMOS noise fields.] 
- x_interpolant – Forces use of a non-default interpolant for interpolation of the internal lookup table in real space. See below for more details. [default: galsim.Linear()] 
- gsparams – An optional - GSParamsargument. [default: None]
 
- Returns:
- a - BaseCorrelatedNoiseinstance representing correlated noise in F814W COSMOS images.
 - The default - x_interpolantis a- galsim.Linear(), which uses bilinear interpolation. The use of this interpolant is an approximation that gives good empirical results without requiring internal convolution of the correlation function profile by a- Pixelobject when applying correlated noise to images: such an internal convolution has been found to be computationally costly in practice, requiring the Fourier transform of very large arrays.- The use of the bilinear interpolants means that the representation of correlated noise will be noticeably inaccurate in at least the following two regimes: - If the pixel scale of the desired final output (e.g. the target image of - BaseCorrelatedNoise.drawImage,- BaseCorrelatedNoise.applyToor- BaseCorrelatedNoise.whitenImage) is small relative to the separation between pixels in the- imageused to instantiate- cnas shown above.
- If the - BaseCorrelatedNoiseinstance- cnwas instantiated with an image of scale comparable to that in the final output, and- cnhas been rotated or otherwise transformed (e.g. via the- BaseCorrelatedNoise.rotate,- BaseCorrelatedNoise.shearmethods; see below).
 - Conversely, the approximation will work best in the case where the correlated noise used to instantiate the - cnis taken from an input image for which- image.scaleis smaller than that in the desired output. This is the most common use case in the practical treatment of correlated noise when simulating galaxies from COSMOS, for which this function is expressly designed.- Changing from the default bilinear interpolant is made possible, but not recommended. In our validation tests, we found that the Linear interpolant usually gave the most accurate results. - You may also specify a gsparams argument. See the docstring for - GSParamsfor more information about this option.- Note - The ACS coadd images in COSMOS have a pixel scale of 0.03 arcsec, and so the pixel scale - cosmos_scaleadopted in the representation of of the correlation function takes a default value- cosmos_scale = 0.03- If you wish to use other units, ensure that the input keyword - cosmos_scaletakes the value corresponding to 0.03 arcsec in your chosen system.- Example: - The following commands use this function to generate a 300 pixel x 300 pixel image of noise with HST COSMOS correlation properties (substitute in your own file and path for the - filestring):- >>> rng = galsim.BaseDeviate(123456) >>> noise = galsim.getCOSMOSNoise(rng=rng) >>> image = galsim.ImageD(nx, ny, scale=0.03) >>> image.addNoise(cf) - If your image has some other pixel scale or a complicated WCS, then the applied noise will have the correct correlations in world coordinates, which may not be what you wanted if you expected the pixel-to-pixel correlations to match the COSMOS noise profile. However, in this case, you would want to view your image with the COSMOS pixel scale when you apply the noise: - >>> image = galsim.Image(nx, ny, wcs=complicated_wcs) >>> noise = galsim.getCOSMOSNoise(rng=rng) >>> image.view(wcs=noise.wcs).addNoise(noise) - The FITS file - out.fitsshould then contain an image of randomly-generated, COSMOS-like noise.