API Reference#

anacal Package#

High-level interface to AnaCal, the astronomical calibration library.

Exposes the compiled _anacal extension alongside convenient submodules such as fpfs, psf, simulation, and general utilities.

anacal.fpfs Module#

anacal.psf Module#

class anacal.psf.BasePsf[source]#

Bases: ABC

Abstract base PSF class.

abstractmethod draw(x, y, *args, **kwargs)[source]#

Draw the PSF image evaluated at position (x, y).

Parameters#

xfloat

X-coordinate, in pixels, at which to evaluate the PSF.

yfloat

Y-coordinate, in pixels, at which to evaluate the PSF.

*args

Optional positional arguments forwarded to subclass implementations.

**kwargs

Optional keyword arguments forwarded to subclass implementations.

Returns#

numpy.ndarray

Array representing the PSF image. Subclasses should document the expected shape and any normalization of the returned array.

Notes#

This method is abstract and must be implemented by subclasses.

anacal.simulation Module#

Simulation utilities for generating synthetic galaxy images.

Provides COSMOS-based galaxy generation, isolated and blended image simulations, and noise generation routines used for shear calibration studies.

class anacal.simulation.CosmosCatalog(filename=None, max_mag=None, min_mag=None, max_hlr=None, min_hlr=None, gal_type='mixed')[source]#

Bases: object

Filtered COSMOS galaxy catalogue for simulation input.

Reads a COSMOS FITS catalogue and applies magnitude, half-light radius, and morphology-type filters.

Parameters:
  • filename (str) – Path to the COSMOS FITS catalogue.

  • max_mag (float | None) – Upper magnitude cut (exclusive).

  • min_mag (float | None) – Lower magnitude cut (inclusive).

  • max_hlr (float | None) – Maximum half-light radius in arcseconds.

  • min_hlr (float | None) – Minimum half-light radius in arcseconds.

  • gal_type (str) – Galaxy morphology filter — "mixed" (all), "sersic" (single-component), "bulgedisk" (two-component), or "debug" (forced exponential).

cat_input#

Filtered catalogue array.

Type:

ndarray

ntrain#

Number of galaxies after filtering.

Type:

int

make_catalog(rng, n)[source]#

Draw n galaxies at random from the filtered catalogue.

Parameters:
  • rng (galsim.BaseDeviate) – GalSim random number generator.

  • n (int) – Number of galaxies to sample.

Returns:

ndarray – Randomly sampled catalogue rows.

Raises:

ValueError – If the catalogue has fewer than n entries.

anacal.simulation.coord_distort_1(x, y, xref, yref, gamma1, gamma2, kappa=0.0, inverse=False)[source]#

Apply shear and convergence distortion to coordinates.

Parameters:
  • x (np.ndarray) – x-coordinates in pixels.

  • y (np.ndarray) – y-coordinates in pixels.

  • xref (float) – Reference x-coordinate in pixels.

  • yref (float) – Reference y-coordinate in pixels.

  • gamma1 (float) – First component of shear (dimensionless).

  • gamma2 (float) – Second component of shear (dimensionless).

  • kappa (float, optional) – Convergence distortion. Defaults to 0.0.

  • inverse (bool, optional) – If True, transform from source plane to lens plane; otherwise transform from lens plane to source plane.

Returns:
  • Tuple[np.ndarray, np.ndarray] – Distorted x and y coordinates in

  • pixels.

Notes

This function returns new arrays and does not modify x or y.

References

Bartelmann, M., & Schneider, P. (2001). Weak gravitational lensing. Physics Reports, 340(4-5), 291–472.

anacal.simulation.coord_rotate(x, y, xref, yref, theta)[source]#

Rotate coordinates around a reference point.

Parameters:
  • x (np.ndarray) – x-coordinates in pixels.

  • y (np.ndarray) – y-coordinates in pixels.

  • xref (float) – Reference x-coordinate in pixels.

  • yref (float) – Reference y-coordinate in pixels.

  • theta (float) – Rotation angle in radians, positive anticlockwise.

Returns:
  • Tuple[np.ndarray, np.ndarray] – Rotated x and y coordinates in

  • pixels.

Notes

This function returns new arrays and does not modify x or y.

References

Rotation matrix: https://en.wikipedia.org/wiki/Rotation_matrix

anacal.simulation.generate_cosmos_gal(record, trunc_ratio=5.0, gsparams=None)[source]#

Generate a realistic COSMOS galaxy with Sersic/DeVaucouleurs profiles.

Builds either a bulge+disk model (DeVaucouleurs bulge + Exponential disk) or a single Sersic profile, applying intrinsic ellipticity from the catalogue fit parameters. Profiles are optionally truncated at trunc_ratio * half_light_radius.

Based on the GalSim COSMOS scene implementation.

Parameters:
  • record (ndarray) – One row of the COSMOS galaxy catalogue, containing bulgefit, sersicfit, use_bulgefit, hlr, and flux fields.

  • trunc_ratio (float) – Truncation radius in units of the half-light radius. Set to < 1 to disable truncation.

  • gsparams (galsim.GSParams | None) – GalSim rendering parameters.

Returns:
  • galsim.GSObject – GalSim galaxy object with intrinsic shape

  • applied.

anacal.simulation.generate_cosmos_gal_simple(record, gsparams=None, random_shape=False)[source]#

Generate a simplified COSMOS galaxy (Gaussian profiles only).

Uses Gaussian approximations for both bulge+disk and single-Sersic fits, which is faster than generate_cosmos_gal() and suitable for use with galsim.RandomKnots.

Parameters:
  • record (ndarray) – One row of the COSMOS galaxy catalogue.

  • gsparams (galsim.GSParams | None) – GalSim rendering parameters.

  • random_shape (bool) – Whether to apply intrinsic ellipticity from the catalogue fit parameters.

Returns:

galsim.GSObject – GalSim galaxy object.

anacal.simulation.make_blended_sim(out_dir, psf_obj, gname, ind0, cat_name=None, ny=5000, nx=5000, rfrac=0.46, scale=0.168, mag_zero=27.0, rot_field=0.0, shear_value=0.02, nrot=4, rescale_min_max=None, verbose=False)[source]#

Make a COSMOS-like blended galaxy image simulation.

Galaxies are randomly distributed within a circular aperture and sheared according to their photometric redshift bin.

Parameters:
  • out_dir (str) – Output directory (used to infer galaxy density).

  • psf_obj (galsim.GSObject) – PSF object for convolution.

  • gname (str) – Shear specification string.

  • ind0 (int) – Random seed index.

  • cat_name (str | None) – Path to a COSMOS FITS catalogue.

  • ny (int) – Image height in pixels.

  • nx (int) – Image width in pixels.

  • rfrac (float) – Fraction of min(nx, ny) used as the circular aperture radius.

  • scale (float) – Pixel scale in arcseconds.

  • mag_zero (float) – Magnitude zero-point.

  • rot_field (float) – Additional field rotation in radians.

  • shear_value (float) – Amplitude of the applied shear.

  • nrot (int) – Number of shape-noise-cancelling rotations.

  • rescale_min_max (list | NDArray | None) – Lower and upper bounds for random galaxy size rescaling.

  • verbose (bool) – Whether to show log info.

Returns:

NDArray – Blended galaxy image array of shape (ny, nx).

anacal.simulation.make_exposure_stamp(sim_method, rng, mag_zero, psf_obj, scale, cat_input, ngalx, ngaly, ngrid, rot_field, g1, g2, nrot_per_gal, do_shift, buff=0, draw_method='auto')[source]#

Render galaxies on a grid to build exposure stamps.

Places galaxies on a regular grid, applies shear, convolves with the PSF, and draws images for each field rotation angle.

Parameters:
  • sim_method (str) – Galaxy rendering method ("fft" or "mc").

  • rng (galsim.BaseDeviate) – GalSim random number generator.

  • mag_zero (float) – Magnitude zero-point.

  • psf_obj (galsim.GSObject) – PSF object for convolution.

  • scale (float) – Pixel scale in arcseconds.

  • cat_input (ndarray) – COSMOS galaxy catalogue rows.

  • ngalx (int) – Number of galaxies along the x-axis.

  • ngaly (int) – Number of galaxies along the y-axis.

  • ngrid (int) – Stamp size in pixels per galaxy.

  • rot_field (list[float]) – Field rotation angles in radians.

  • g1 (float) – First shear component.

  • g2 (float) – Second shear component.

  • nrot_per_gal (int) – Number of shape-noise-cancelling rotations per galaxy.

  • do_shift (bool) – Whether to apply random sub-pixel shifts.

  • buff (int) – Zero-padding buffer around the image boundary.

  • draw_method (str) – GalSim drawing method.

Returns:

list[NDArray] – List of exposure arrays, one per field rotation.

anacal.simulation.make_isolated_sim(ny, nx, psf_obj, gname, seed, cat_name=None, scale=0.168, mag_zero=27.0, rot_field=None, shear_value=0.02, ngrid=64, nrot_per_gal=4, max_mag=None, min_mag=None, max_hlr=None, min_hlr=None, gal_type='mixed', do_shift=False, npoints=30, sim_method='fft', buff=0, draw_method='auto', return_catalog=False, verbose=False)[source]#

Make an isolated galaxy image simulation on a regular grid.

Galaxies are drawn from a COSMOS catalogue, placed on an (ny // ngrid) x (nx // ngrid) grid, sheared, convolved with a PSF, and rendered into pixel arrays.

Parameters:
  • ny (int) – Number of pixels in the y-direction.

  • nx (int) – Number of pixels in the x-direction.

  • psf_obj (galsim.GSObject) – PSF object for convolution.

  • gname (str) – Shear specification string, e.g. "g1-0" or "g2-1". Format is "<component>-<index>" where index selects from [-shear_value, shear_value, 0].

  • seed (int) – Random seed for the simulation.

  • cat_name (str | None) – Path to a COSMOS FITS catalogue. Defaults to the bundled src_cosmos.fits.

  • scale (float) – Pixel scale in arcseconds.

  • mag_zero (float) – Magnitude zero-point (27 for HSC).

  • rot_field (list[float] | None) – Field rotation angles in radians. Defaults to [0.0].

  • shear_value (float) – Amplitude of the applied shear.

  • ngrid (int) – Stamp size in pixels per galaxy.

  • nrot_per_gal (int) – Number of shape-noise-cancelling rotations.

  • max_mag (float | None) – Upper magnitude cut.

  • min_mag (float | None) – Lower magnitude cut.

  • max_hlr (float | None) – Maximum half-light radius in arcseconds.

  • min_hlr (float | None) – Minimum half-light radius in arcseconds.

  • gal_type (str) – Galaxy morphology filter ("mixed", "sersic", "bulgedisk", or "debug").

  • do_shift (bool) – Whether to apply random sub-pixel offsets.

  • npoints (int) – Number of random knots ("mc" method only).

  • sim_method (str) – Galaxy rendering method ("fft" or "mc").

  • buff (int) – Zero-padding buffer in pixels.

  • draw_method (str) – GalSim drawing method.

  • return_catalog (bool) – If True, also return the input catalogue.

  • verbose (bool) – Whether to show log info.

Returns:
  • list[NDArray] | tuple[list[NDArray], ndarray] – Exposure arrays,

  • one per field rotation. If *return_catalog* is ``True``, returns

  • `` (exposures, cat_input)

anacal.simulation.make_noise_sim(out_dir, infname, ind0, ny=6400, nx=6400, scale=0.168, verbose=False)[source]#

Generate a pure COSMOS-correlated noise image.

Parameters:
  • out_dir (str) – Output directory (currently unused).

  • infname (str) – Path to the COSMOS noise correlation file.

  • ind0 (int) – Seed index for the random number generator.

  • ny (int) – Number of pixels in the y-direction.

  • nx (int) – Number of pixels in the x-direction.

  • scale (float) – Pixel scale in arcseconds.

  • verbose (bool) – Whether to show log info.

Returns:

NDArray – Noise image array of shape (ny, nx).

anacal.simulation.read_cosmos_catalog(filename)[source]#

Read a COSMOS galaxy catalogue from a FITS file.

Parameters:

filename (str) – Path to the FITS catalogue file.

Returns:

ndarray – Structured array of catalogue rows.

anacal.utils Module#

anacal.utils.numpy_to_qtensor(array: ndarray[tuple[Any, ...], dtype[floating[Any]]]) <MagicMock name='mock.qtensor' id='133044513972240'>[source]#

Create a math.qtensor from a (…, 5) numpy array.

anacal.utils.qtensor_to_numpy(tensor: <MagicMock name = 'mock.qtensor' id='133044513972240'>) ndarray[tuple[Any, ...], dtype[float64]][source]#

Convert a math.qtensor into a (…, 5) numpy array.

anacal.utils.qvector_to_qtensor(qvector: ~collections.abc.Iterable[<MagicMock name='mock.qnumber' id='133044513977808'>], shape: ~collections.abc.Sequence[int] | int) <MagicMock name='mock.qtensor' id='133044513972240'>[source]#

Convert a flat iterable of qnumber values into a qtensor.

Parameters:
  • qvector – Iterable containing math.qnumber elements, typically the output of anacal.image.ImageQ.prepare_qnumber_vector().

  • shape – Desired tensor shape expressed either as a sequence of integers or a single dimension length.

Returns:

math.qtensor – Tensor view over the provided qvector contents.

anacal.utils.resize_array(array: ndarray[tuple[Any, ...], dtype[Any]], target_shape: tuple[int, int] = (64, 64))[source]#

Resize a 2D array to a target shape.

Parameters:
  • array – Input array to be resized.

  • target_shape – Desired output shape as (height, width).

Returns:

NDArray[Any] – Array with the specified target_shape.

anacal.utils.rotate90(image)[source]#

Rotate a 2D image 90 degrees clockwise.

Parameters:

image – Input array with shape (H, W).

Returns:

NDArray[Any] – Rotated image of the same shape.